babylon.2.1-beta.debug.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (r === void 0) { r = 0; }
  6. if (g === void 0) { g = 0; }
  7. if (b === void 0) { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. // Operators
  16. Color3.prototype.toArray = function (array, index) {
  17. if (index === undefined) {
  18. index = 0;
  19. }
  20. array[index] = this.r;
  21. array[index + 1] = this.g;
  22. array[index + 2] = this.b;
  23. return this;
  24. };
  25. Color3.prototype.toColor4 = function (alpha) {
  26. if (alpha === void 0) { alpha = 1; }
  27. return new Color4(this.r, this.g, this.b, alpha);
  28. };
  29. Color3.prototype.asArray = function () {
  30. var result = [];
  31. this.toArray(result, 0);
  32. return result;
  33. };
  34. Color3.prototype.toLuminance = function () {
  35. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  36. };
  37. Color3.prototype.multiply = function (otherColor) {
  38. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  39. };
  40. Color3.prototype.multiplyToRef = function (otherColor, result) {
  41. result.r = this.r * otherColor.r;
  42. result.g = this.g * otherColor.g;
  43. result.b = this.b * otherColor.b;
  44. return this;
  45. };
  46. Color3.prototype.equals = function (otherColor) {
  47. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  48. };
  49. Color3.prototype.scale = function (scale) {
  50. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  51. };
  52. Color3.prototype.scaleToRef = function (scale, result) {
  53. result.r = this.r * scale;
  54. result.g = this.g * scale;
  55. result.b = this.b * scale;
  56. return this;
  57. };
  58. Color3.prototype.add = function (otherColor) {
  59. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  60. };
  61. Color3.prototype.addToRef = function (otherColor, result) {
  62. result.r = this.r + otherColor.r;
  63. result.g = this.g + otherColor.g;
  64. result.b = this.b + otherColor.b;
  65. return this;
  66. };
  67. Color3.prototype.subtract = function (otherColor) {
  68. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  69. };
  70. Color3.prototype.subtractToRef = function (otherColor, result) {
  71. result.r = this.r - otherColor.r;
  72. result.g = this.g - otherColor.g;
  73. result.b = this.b - otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. return this;
  84. };
  85. Color3.prototype.copyFromFloats = function (r, g, b) {
  86. this.r = r;
  87. this.g = g;
  88. this.b = b;
  89. return this;
  90. };
  91. // Statics
  92. Color3.FromArray = function (array, offset) {
  93. if (offset === void 0) { offset = 0; }
  94. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  95. };
  96. Color3.FromInts = function (r, g, b) {
  97. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  98. };
  99. Color3.Lerp = function (start, end, amount) {
  100. var r = start.r + ((end.r - start.r) * amount);
  101. var g = start.g + ((end.g - start.g) * amount);
  102. var b = start.b + ((end.b - start.b) * amount);
  103. return new Color3(r, g, b);
  104. };
  105. Color3.Red = function () {
  106. return new Color3(1, 0, 0);
  107. };
  108. Color3.Green = function () {
  109. return new Color3(0, 1, 0);
  110. };
  111. Color3.Blue = function () {
  112. return new Color3(0, 0, 1);
  113. };
  114. Color3.Black = function () {
  115. return new Color3(0, 0, 0);
  116. };
  117. Color3.White = function () {
  118. return new Color3(1, 1, 1);
  119. };
  120. Color3.Purple = function () {
  121. return new Color3(0.5, 0, 0.5);
  122. };
  123. Color3.Magenta = function () {
  124. return new Color3(1, 0, 1);
  125. };
  126. Color3.Yellow = function () {
  127. return new Color3(1, 1, 0);
  128. };
  129. Color3.Gray = function () {
  130. return new Color3(0.5, 0.5, 0.5);
  131. };
  132. return Color3;
  133. })();
  134. BABYLON.Color3 = Color3;
  135. var Color4 = (function () {
  136. function Color4(r, g, b, a) {
  137. this.r = r;
  138. this.g = g;
  139. this.b = b;
  140. this.a = a;
  141. }
  142. // Operators
  143. Color4.prototype.addInPlace = function (right) {
  144. this.r += right.r;
  145. this.g += right.g;
  146. this.b += right.b;
  147. this.a += right.a;
  148. return this;
  149. };
  150. Color4.prototype.asArray = function () {
  151. var result = [];
  152. this.toArray(result, 0);
  153. return result;
  154. };
  155. Color4.prototype.toArray = function (array, index) {
  156. if (index === undefined) {
  157. index = 0;
  158. }
  159. array[index] = this.r;
  160. array[index + 1] = this.g;
  161. array[index + 2] = this.b;
  162. array[index + 3] = this.a;
  163. return this;
  164. };
  165. Color4.prototype.add = function (right) {
  166. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  167. };
  168. Color4.prototype.subtract = function (right) {
  169. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  170. };
  171. Color4.prototype.subtractToRef = function (right, result) {
  172. result.r = this.r - right.r;
  173. result.g = this.g - right.g;
  174. result.b = this.b - right.b;
  175. result.a = this.a - right.a;
  176. return this;
  177. };
  178. Color4.prototype.scale = function (scale) {
  179. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  180. };
  181. Color4.prototype.scaleToRef = function (scale, result) {
  182. result.r = this.r * scale;
  183. result.g = this.g * scale;
  184. result.b = this.b * scale;
  185. result.a = this.a * scale;
  186. return this;
  187. };
  188. Color4.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  190. };
  191. Color4.prototype.clone = function () {
  192. return new Color4(this.r, this.g, this.b, this.a);
  193. };
  194. Color4.prototype.copyFrom = function (source) {
  195. this.r = source.r;
  196. this.g = source.g;
  197. this.b = source.b;
  198. this.a = source.a;
  199. return this;
  200. };
  201. // Statics
  202. Color4.Lerp = function (left, right, amount) {
  203. var result = new Color4(0, 0, 0, 0);
  204. Color4.LerpToRef(left, right, amount, result);
  205. return result;
  206. };
  207. Color4.LerpToRef = function (left, right, amount, result) {
  208. result.r = left.r + (right.r - left.r) * amount;
  209. result.g = left.g + (right.g - left.g) * amount;
  210. result.b = left.b + (right.b - left.b) * amount;
  211. result.a = left.a + (right.a - left.a) * amount;
  212. };
  213. Color4.FromArray = function (array, offset) {
  214. if (offset === void 0) { offset = 0; }
  215. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  216. };
  217. Color4.FromInts = function (r, g, b, a) {
  218. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  219. };
  220. return Color4;
  221. })();
  222. BABYLON.Color4 = Color4;
  223. var Vector2 = (function () {
  224. function Vector2(x, y) {
  225. this.x = x;
  226. this.y = y;
  227. }
  228. Vector2.prototype.toString = function () {
  229. return "{X: " + this.x + " Y:" + this.y + "}";
  230. };
  231. // Operators
  232. Vector2.prototype.toArray = function (array, index) {
  233. if (index === void 0) { index = 0; }
  234. array[index] = this.x;
  235. array[index + 1] = this.y;
  236. return this;
  237. };
  238. Vector2.prototype.asArray = function () {
  239. var result = [];
  240. this.toArray(result, 0);
  241. return result;
  242. };
  243. Vector2.prototype.copyFrom = function (source) {
  244. this.x = source.x;
  245. this.y = source.y;
  246. return this;
  247. };
  248. Vector2.prototype.copyFromFloats = function (x, y) {
  249. this.x = x;
  250. this.y = y;
  251. return this;
  252. };
  253. Vector2.prototype.add = function (otherVector) {
  254. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  255. };
  256. Vector2.prototype.addVector3 = function (otherVector) {
  257. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  258. };
  259. Vector2.prototype.subtract = function (otherVector) {
  260. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  261. };
  262. Vector2.prototype.subtractInPlace = function (otherVector) {
  263. this.x -= otherVector.x;
  264. this.y -= otherVector.y;
  265. return this;
  266. };
  267. Vector2.prototype.multiplyInPlace = function (otherVector) {
  268. this.x *= otherVector.x;
  269. this.y *= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiply = function (otherVector) {
  273. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  274. };
  275. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  276. result.x = this.x * otherVector.x;
  277. result.y = this.y * otherVector.y;
  278. return this;
  279. };
  280. Vector2.prototype.multiplyByFloats = function (x, y) {
  281. return new Vector2(this.x * x, this.y * y);
  282. };
  283. Vector2.prototype.divide = function (otherVector) {
  284. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  285. };
  286. Vector2.prototype.divideToRef = function (otherVector, result) {
  287. result.x = this.x / otherVector.x;
  288. result.y = this.y / otherVector.y;
  289. return this;
  290. };
  291. Vector2.prototype.negate = function () {
  292. return new Vector2(-this.x, -this.y);
  293. };
  294. Vector2.prototype.scaleInPlace = function (scale) {
  295. this.x *= scale;
  296. this.y *= scale;
  297. return this;
  298. };
  299. Vector2.prototype.scale = function (scale) {
  300. return new Vector2(this.x * scale, this.y * scale);
  301. };
  302. Vector2.prototype.equals = function (otherVector) {
  303. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  304. };
  305. // Properties
  306. Vector2.prototype.length = function () {
  307. return Math.sqrt(this.x * this.x + this.y * this.y);
  308. };
  309. Vector2.prototype.lengthSquared = function () {
  310. return (this.x * this.x + this.y * this.y);
  311. };
  312. // Methods
  313. Vector2.prototype.normalize = function () {
  314. var len = this.length();
  315. if (len === 0)
  316. return this;
  317. var num = 1.0 / len;
  318. this.x *= num;
  319. this.y *= num;
  320. return this;
  321. };
  322. Vector2.prototype.clone = function () {
  323. return new Vector2(this.x, this.y);
  324. };
  325. // Statics
  326. Vector2.Zero = function () {
  327. return new Vector2(0, 0);
  328. };
  329. Vector2.FromArray = function (array, offset) {
  330. if (offset === void 0) { offset = 0; }
  331. return new Vector2(array[offset], array[offset + 1]);
  332. };
  333. Vector2.FromArrayToRef = function (array, offset, result) {
  334. result.x = array[offset];
  335. result.y = array[offset + 1];
  336. };
  337. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  338. var squared = amount * amount;
  339. var cubed = amount * squared;
  340. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  341. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  342. return new Vector2(x, y);
  343. };
  344. Vector2.Clamp = function (value, min, max) {
  345. var x = value.x;
  346. x = (x > max.x) ? max.x : x;
  347. x = (x < min.x) ? min.x : x;
  348. var y = value.y;
  349. y = (y > max.y) ? max.y : y;
  350. y = (y < min.y) ? min.y : y;
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  354. var squared = amount * amount;
  355. var cubed = amount * squared;
  356. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  357. var part2 = (-2.0 * cubed) + (3.0 * squared);
  358. var part3 = (cubed - (2.0 * squared)) + amount;
  359. var part4 = cubed - squared;
  360. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  361. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  362. return new Vector2(x, y);
  363. };
  364. Vector2.Lerp = function (start, end, amount) {
  365. var x = start.x + ((end.x - start.x) * amount);
  366. var y = start.y + ((end.y - start.y) * amount);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Dot = function (left, right) {
  370. return left.x * right.x + left.y * right.y;
  371. };
  372. Vector2.Normalize = function (vector) {
  373. var newVector = vector.clone();
  374. newVector.normalize();
  375. return newVector;
  376. };
  377. Vector2.Minimize = function (left, right) {
  378. var x = (left.x < right.x) ? left.x : right.x;
  379. var y = (left.y < right.y) ? left.y : right.y;
  380. return new Vector2(x, y);
  381. };
  382. Vector2.Maximize = function (left, right) {
  383. var x = (left.x > right.x) ? left.x : right.x;
  384. var y = (left.y > right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Transform = function (vector, transformation) {
  388. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  389. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Distance = function (value1, value2) {
  393. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  394. };
  395. Vector2.DistanceSquared = function (value1, value2) {
  396. var x = value1.x - value2.x;
  397. var y = value1.y - value2.y;
  398. return (x * x) + (y * y);
  399. };
  400. return Vector2;
  401. })();
  402. BABYLON.Vector2 = Vector2;
  403. var Vector3 = (function () {
  404. function Vector3(x, y, z) {
  405. this.x = x;
  406. this.y = y;
  407. this.z = z;
  408. }
  409. Vector3.prototype.toString = function () {
  410. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  411. };
  412. // Operators
  413. Vector3.prototype.asArray = function () {
  414. var result = [];
  415. this.toArray(result, 0);
  416. return result;
  417. };
  418. Vector3.prototype.toArray = function (array, index) {
  419. if (index === void 0) { index = 0; }
  420. array[index] = this.x;
  421. array[index + 1] = this.y;
  422. array[index + 2] = this.z;
  423. return this;
  424. };
  425. Vector3.prototype.toQuaternion = function () {
  426. var result = new Quaternion(0, 0, 0, 1);
  427. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  428. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  429. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  430. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  431. var cosy = Math.cos(this.y * 0.5);
  432. var siny = Math.sin(this.y * 0.5);
  433. result.x = coszMinusx * siny;
  434. result.y = -sinzMinusx * siny;
  435. result.z = sinxPlusz * cosy;
  436. result.w = cosxPlusz * cosy;
  437. return result;
  438. };
  439. Vector3.prototype.addInPlace = function (otherVector) {
  440. this.x += otherVector.x;
  441. this.y += otherVector.y;
  442. this.z += otherVector.z;
  443. return this;
  444. };
  445. Vector3.prototype.add = function (otherVector) {
  446. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  447. };
  448. Vector3.prototype.addToRef = function (otherVector, result) {
  449. result.x = this.x + otherVector.x;
  450. result.y = this.y + otherVector.y;
  451. result.z = this.z + otherVector.z;
  452. return this;
  453. };
  454. Vector3.prototype.subtractInPlace = function (otherVector) {
  455. this.x -= otherVector.x;
  456. this.y -= otherVector.y;
  457. this.z -= otherVector.z;
  458. return this;
  459. };
  460. Vector3.prototype.subtract = function (otherVector) {
  461. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  462. };
  463. Vector3.prototype.subtractToRef = function (otherVector, result) {
  464. result.x = this.x - otherVector.x;
  465. result.y = this.y - otherVector.y;
  466. result.z = this.z - otherVector.z;
  467. return this;
  468. };
  469. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  470. return new Vector3(this.x - x, this.y - y, this.z - z);
  471. };
  472. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  473. result.x = this.x - x;
  474. result.y = this.y - y;
  475. result.z = this.z - z;
  476. return this;
  477. };
  478. Vector3.prototype.negate = function () {
  479. return new Vector3(-this.x, -this.y, -this.z);
  480. };
  481. Vector3.prototype.scaleInPlace = function (scale) {
  482. this.x *= scale;
  483. this.y *= scale;
  484. this.z *= scale;
  485. return this;
  486. };
  487. Vector3.prototype.scale = function (scale) {
  488. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  489. };
  490. Vector3.prototype.scaleToRef = function (scale, result) {
  491. result.x = this.x * scale;
  492. result.y = this.y * scale;
  493. result.z = this.z * scale;
  494. };
  495. Vector3.prototype.equals = function (otherVector) {
  496. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  497. };
  498. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  499. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  500. };
  501. Vector3.prototype.equalsToFloats = function (x, y, z) {
  502. return this.x === x && this.y === y && this.z === z;
  503. };
  504. Vector3.prototype.multiplyInPlace = function (otherVector) {
  505. this.x *= otherVector.x;
  506. this.y *= otherVector.y;
  507. this.z *= otherVector.z;
  508. return this;
  509. };
  510. Vector3.prototype.multiply = function (otherVector) {
  511. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  512. };
  513. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  514. result.x = this.x * otherVector.x;
  515. result.y = this.y * otherVector.y;
  516. result.z = this.z * otherVector.z;
  517. return this;
  518. };
  519. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  520. return new Vector3(this.x * x, this.y * y, this.z * z);
  521. };
  522. Vector3.prototype.divide = function (otherVector) {
  523. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  524. };
  525. Vector3.prototype.divideToRef = function (otherVector, result) {
  526. result.x = this.x / otherVector.x;
  527. result.y = this.y / otherVector.y;
  528. result.z = this.z / otherVector.z;
  529. return this;
  530. };
  531. Vector3.prototype.MinimizeInPlace = function (other) {
  532. if (other.x < this.x)
  533. this.x = other.x;
  534. if (other.y < this.y)
  535. this.y = other.y;
  536. if (other.z < this.z)
  537. this.z = other.z;
  538. return this;
  539. };
  540. Vector3.prototype.MaximizeInPlace = function (other) {
  541. if (other.x > this.x)
  542. this.x = other.x;
  543. if (other.y > this.y)
  544. this.y = other.y;
  545. if (other.z > this.z)
  546. this.z = other.z;
  547. return this;
  548. };
  549. // Properties
  550. Vector3.prototype.length = function () {
  551. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  552. };
  553. Vector3.prototype.lengthSquared = function () {
  554. return (this.x * this.x + this.y * this.y + this.z * this.z);
  555. };
  556. // Methods
  557. Vector3.prototype.normalize = function () {
  558. var len = this.length();
  559. if (len === 0)
  560. return this;
  561. var num = 1.0 / len;
  562. this.x *= num;
  563. this.y *= num;
  564. this.z *= num;
  565. return this;
  566. };
  567. Vector3.prototype.clone = function () {
  568. return new Vector3(this.x, this.y, this.z);
  569. };
  570. Vector3.prototype.copyFrom = function (source) {
  571. this.x = source.x;
  572. this.y = source.y;
  573. this.z = source.z;
  574. return this;
  575. };
  576. Vector3.prototype.copyFromFloats = function (x, y, z) {
  577. this.x = x;
  578. this.y = y;
  579. this.z = z;
  580. return this;
  581. };
  582. // Statics
  583. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  584. var d0 = Vector3.Dot(vector0, axis) - size;
  585. var d1 = Vector3.Dot(vector1, axis) - size;
  586. var s = d0 / (d0 - d1);
  587. return s;
  588. };
  589. Vector3.FromArray = function (array, offset) {
  590. if (!offset) {
  591. offset = 0;
  592. }
  593. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  594. };
  595. Vector3.FromArrayToRef = function (array, offset, result) {
  596. result.x = array[offset];
  597. result.y = array[offset + 1];
  598. result.z = array[offset + 2];
  599. };
  600. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatsToRef = function (x, y, z, result) {
  606. result.x = x;
  607. result.y = y;
  608. result.z = z;
  609. };
  610. Vector3.Zero = function () {
  611. return new Vector3(0, 0, 0);
  612. };
  613. Vector3.Up = function () {
  614. return new Vector3(0, 1.0, 0);
  615. };
  616. Vector3.TransformCoordinates = function (vector, transformation) {
  617. var result = Vector3.Zero();
  618. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  619. return result;
  620. };
  621. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  622. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  623. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  624. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  625. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  626. result.x = x / w;
  627. result.y = y / w;
  628. result.z = z / w;
  629. };
  630. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  631. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  632. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  633. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  634. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  635. result.x = rx / rw;
  636. result.y = ry / rw;
  637. result.z = rz / rw;
  638. };
  639. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  640. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  641. var m0 = SIMD.float32x4.load(transformation.m, 0);
  642. var m1 = SIMD.float32x4.load(transformation.m, 4);
  643. var m2 = SIMD.float32x4.load(transformation.m, 8);
  644. var m3 = SIMD.float32x4.load(transformation.m, 12);
  645. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  646. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  647. SIMD.float32x4.storeXYZ(result._data, 0, r);
  648. };
  649. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  650. var v0 = SIMD.float32x4.splat(x);
  651. var v1 = SIMD.float32x4.splat(y);
  652. var v2 = SIMD.float32x4.splat(z);
  653. var m0 = SIMD.float32x4.load(transformation.m, 0);
  654. var m1 = SIMD.float32x4.load(transformation.m, 4);
  655. var m2 = SIMD.float32x4.load(transformation.m, 8);
  656. var m3 = SIMD.float32x4.load(transformation.m, 12);
  657. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  658. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  659. SIMD.float32x4.storeXYZ(result._data, 0, r);
  660. };
  661. Vector3.TransformNormal = function (vector, transformation) {
  662. var result = Vector3.Zero();
  663. Vector3.TransformNormalToRef(vector, transformation, result);
  664. return result;
  665. };
  666. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  667. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  668. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  669. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  670. };
  671. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  672. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  673. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  674. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  675. };
  676. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  677. var squared = amount * amount;
  678. var cubed = amount * squared;
  679. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  680. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  681. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  682. return new Vector3(x, y, z);
  683. };
  684. Vector3.Clamp = function (value, min, max) {
  685. var x = value.x;
  686. x = (x > max.x) ? max.x : x;
  687. x = (x < min.x) ? min.x : x;
  688. var y = value.y;
  689. y = (y > max.y) ? max.y : y;
  690. y = (y < min.y) ? min.y : y;
  691. var z = value.z;
  692. z = (z > max.z) ? max.z : z;
  693. z = (z < min.z) ? min.z : z;
  694. return new Vector3(x, y, z);
  695. };
  696. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  697. var squared = amount * amount;
  698. var cubed = amount * squared;
  699. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  700. var part2 = (-2.0 * cubed) + (3.0 * squared);
  701. var part3 = (cubed - (2.0 * squared)) + amount;
  702. var part4 = cubed - squared;
  703. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  704. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  705. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  706. return new Vector3(x, y, z);
  707. };
  708. Vector3.Lerp = function (start, end, amount) {
  709. var x = start.x + ((end.x - start.x) * amount);
  710. var y = start.y + ((end.y - start.y) * amount);
  711. var z = start.z + ((end.z - start.z) * amount);
  712. return new Vector3(x, y, z);
  713. };
  714. Vector3.Dot = function (left, right) {
  715. return (left.x * right.x + left.y * right.y + left.z * right.z);
  716. };
  717. Vector3.Cross = function (left, right) {
  718. var result = Vector3.Zero();
  719. Vector3.CrossToRef(left, right, result);
  720. return result;
  721. };
  722. Vector3.CrossToRef = function (left, right, result) {
  723. result.x = left.y * right.z - left.z * right.y;
  724. result.y = left.z * right.x - left.x * right.z;
  725. result.z = left.x * right.y - left.y * right.x;
  726. };
  727. Vector3.Normalize = function (vector) {
  728. var result = Vector3.Zero();
  729. Vector3.NormalizeToRef(vector, result);
  730. return result;
  731. };
  732. Vector3.NormalizeToRef = function (vector, result) {
  733. result.copyFrom(vector);
  734. result.normalize();
  735. };
  736. Vector3.Project = function (vector, world, transform, viewport) {
  737. var cw = viewport.width;
  738. var ch = viewport.height;
  739. var cx = viewport.x;
  740. var cy = viewport.y;
  741. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  742. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  743. return Vector3.TransformCoordinates(vector, finalMatrix);
  744. };
  745. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  746. var matrix = world.multiply(transform);
  747. matrix.invert();
  748. source.x = source.x / viewportWidth * 2 - 1;
  749. source.y = -(source.y / viewportHeight * 2 - 1);
  750. var vector = Vector3.TransformCoordinates(source, matrix);
  751. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  752. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  753. vector = vector.scale(1.0 / num);
  754. }
  755. return vector;
  756. };
  757. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  758. var matrix = world.multiply(view).multiply(projection);
  759. matrix.invert();
  760. source.x = source.x / viewportWidth * 2 - 1;
  761. source.y = -(source.y / viewportHeight * 2 - 1);
  762. var vector = Vector3.TransformCoordinates(source, matrix);
  763. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  764. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  765. vector = vector.scale(1.0 / num);
  766. }
  767. return vector;
  768. };
  769. Vector3.Minimize = function (left, right) {
  770. var min = left.clone();
  771. min.MinimizeInPlace(right);
  772. return min;
  773. };
  774. Vector3.Maximize = function (left, right) {
  775. var max = left.clone();
  776. max.MaximizeInPlace(right);
  777. return max;
  778. };
  779. Vector3.Distance = function (value1, value2) {
  780. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  781. };
  782. Vector3.DistanceSquared = function (value1, value2) {
  783. var x = value1.x - value2.x;
  784. var y = value1.y - value2.y;
  785. var z = value1.z - value2.z;
  786. return (x * x) + (y * y) + (z * z);
  787. };
  788. Vector3.Center = function (value1, value2) {
  789. var center = value1.add(value2);
  790. center.scaleInPlace(0.5);
  791. return center;
  792. };
  793. return Vector3;
  794. })();
  795. BABYLON.Vector3 = Vector3;
  796. //Vector4 class created for EulerAngle class conversion to Quaternion
  797. var Vector4 = (function () {
  798. function Vector4(x, y, z, w) {
  799. this.x = x;
  800. this.y = y;
  801. this.z = z;
  802. this.w = w;
  803. }
  804. Vector4.prototype.toString = function () {
  805. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  806. };
  807. // Operators
  808. Vector4.prototype.asArray = function () {
  809. var result = [];
  810. this.toArray(result, 0);
  811. return result;
  812. };
  813. Vector4.prototype.toArray = function (array, index) {
  814. if (index === undefined) {
  815. index = 0;
  816. }
  817. array[index] = this.x;
  818. array[index + 1] = this.y;
  819. array[index + 2] = this.z;
  820. array[index + 3] = this.w;
  821. return this;
  822. };
  823. Vector4.prototype.addInPlace = function (otherVector) {
  824. this.x += otherVector.x;
  825. this.y += otherVector.y;
  826. this.z += otherVector.z;
  827. this.w += otherVector.w;
  828. return this;
  829. };
  830. Vector4.prototype.add = function (otherVector) {
  831. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  832. };
  833. Vector4.prototype.addToRef = function (otherVector, result) {
  834. result.x = this.x + otherVector.x;
  835. result.y = this.y + otherVector.y;
  836. result.z = this.z + otherVector.z;
  837. result.w = this.w + otherVector.w;
  838. return this;
  839. };
  840. Vector4.prototype.subtractInPlace = function (otherVector) {
  841. this.x -= otherVector.x;
  842. this.y -= otherVector.y;
  843. this.z -= otherVector.z;
  844. this.w -= otherVector.w;
  845. return this;
  846. };
  847. Vector4.prototype.subtract = function (otherVector) {
  848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  849. };
  850. Vector4.prototype.subtractToRef = function (otherVector, result) {
  851. result.x = this.x - otherVector.x;
  852. result.y = this.y - otherVector.y;
  853. result.z = this.z - otherVector.z;
  854. result.w = this.w - otherVector.w;
  855. return this;
  856. };
  857. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  858. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  859. };
  860. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  861. result.x = this.x - x;
  862. result.y = this.y - y;
  863. result.z = this.z - z;
  864. result.w = this.w - w;
  865. return this;
  866. };
  867. Vector4.prototype.negate = function () {
  868. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  869. };
  870. Vector4.prototype.scaleInPlace = function (scale) {
  871. this.x *= scale;
  872. this.y *= scale;
  873. this.z *= scale;
  874. this.w *= scale;
  875. return this;
  876. };
  877. Vector4.prototype.scale = function (scale) {
  878. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  879. };
  880. Vector4.prototype.scaleToRef = function (scale, result) {
  881. result.x = this.x * scale;
  882. result.y = this.y * scale;
  883. result.z = this.z * scale;
  884. result.w = this.w * scale;
  885. };
  886. Vector4.prototype.equals = function (otherVector) {
  887. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  888. };
  889. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  890. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  891. };
  892. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  893. return this.x === x && this.y === y && this.z === z && this.w === w;
  894. };
  895. Vector4.prototype.multiplyInPlace = function (otherVector) {
  896. this.x *= otherVector.x;
  897. this.y *= otherVector.y;
  898. this.z *= otherVector.z;
  899. this.w *= otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.multiply = function (otherVector) {
  903. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  904. };
  905. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  906. result.x = this.x * otherVector.x;
  907. result.y = this.y * otherVector.y;
  908. result.z = this.z * otherVector.z;
  909. result.w = this.w * otherVector.w;
  910. return this;
  911. };
  912. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  913. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  914. };
  915. Vector4.prototype.divide = function (otherVector) {
  916. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  917. };
  918. Vector4.prototype.divideToRef = function (otherVector, result) {
  919. result.x = this.x / otherVector.x;
  920. result.y = this.y / otherVector.y;
  921. result.z = this.z / otherVector.z;
  922. result.w = this.w / otherVector.w;
  923. return this;
  924. };
  925. Vector4.prototype.MinimizeInPlace = function (other) {
  926. if (other.x < this.x)
  927. this.x = other.x;
  928. if (other.y < this.y)
  929. this.y = other.y;
  930. if (other.z < this.z)
  931. this.z = other.z;
  932. if (other.w < this.w)
  933. this.w = other.w;
  934. return this;
  935. };
  936. Vector4.prototype.MaximizeInPlace = function (other) {
  937. if (other.x > this.x)
  938. this.x = other.x;
  939. if (other.y > this.y)
  940. this.y = other.y;
  941. if (other.z > this.z)
  942. this.z = other.z;
  943. if (other.w > this.w)
  944. this.w = other.w;
  945. return this;
  946. };
  947. // Properties
  948. Vector4.prototype.length = function () {
  949. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  950. };
  951. Vector4.prototype.lengthSquared = function () {
  952. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  953. };
  954. // Methods
  955. Vector4.prototype.normalize = function () {
  956. var len = this.length();
  957. if (len === 0)
  958. return this;
  959. var num = 1.0 / len;
  960. this.x *= num;
  961. this.y *= num;
  962. this.z *= num;
  963. this.w *= num;
  964. return this;
  965. };
  966. Vector4.prototype.clone = function () {
  967. return new Vector4(this.x, this.y, this.z, this.w);
  968. };
  969. Vector4.prototype.copyFrom = function (source) {
  970. this.x = source.x;
  971. this.y = source.y;
  972. this.z = source.z;
  973. this.w = source.w;
  974. return this;
  975. };
  976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. return this;
  982. };
  983. // Statics
  984. Vector4.FromArray = function (array, offset) {
  985. if (!offset) {
  986. offset = 0;
  987. }
  988. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  989. };
  990. Vector4.FromArrayToRef = function (array, offset, result) {
  991. result.x = array[offset];
  992. result.y = array[offset + 1];
  993. result.z = array[offset + 2];
  994. result.w = array[offset + 3];
  995. };
  996. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  997. result.x = array[offset];
  998. result.y = array[offset + 1];
  999. result.z = array[offset + 2];
  1000. result.w = array[offset + 3];
  1001. };
  1002. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1003. result.x = x;
  1004. result.y = y;
  1005. result.z = z;
  1006. result.w = w;
  1007. };
  1008. Vector4.Zero = function () {
  1009. return new Vector4(0, 0, 0, 0);
  1010. };
  1011. Vector4.Normalize = function (vector) {
  1012. var result = Vector4.Zero();
  1013. Vector4.NormalizeToRef(vector, result);
  1014. return result;
  1015. };
  1016. Vector4.NormalizeToRef = function (vector, result) {
  1017. result.copyFrom(vector);
  1018. result.normalize();
  1019. };
  1020. Vector4.Minimize = function (left, right) {
  1021. var min = left.clone();
  1022. min.MinimizeInPlace(right);
  1023. return min;
  1024. };
  1025. Vector4.Maximize = function (left, right) {
  1026. var max = left.clone();
  1027. max.MaximizeInPlace(right);
  1028. return max;
  1029. };
  1030. Vector4.Distance = function (value1, value2) {
  1031. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1032. };
  1033. Vector4.DistanceSquared = function (value1, value2) {
  1034. var x = value1.x - value2.x;
  1035. var y = value1.y - value2.y;
  1036. var z = value1.z - value2.z;
  1037. var w = value1.w - value2.w;
  1038. return (x * x) + (y * y) + (z * z) + (w * w);
  1039. };
  1040. Vector4.Center = function (value1, value2) {
  1041. var center = value1.add(value2);
  1042. center.scaleInPlace(0.5);
  1043. return center;
  1044. };
  1045. return Vector4;
  1046. })();
  1047. BABYLON.Vector4 = Vector4;
  1048. var Quaternion = (function () {
  1049. function Quaternion(x, y, z, w) {
  1050. if (x === void 0) { x = 0; }
  1051. if (y === void 0) { y = 0; }
  1052. if (z === void 0) { z = 0; }
  1053. if (w === void 0) { w = 1; }
  1054. this.x = x;
  1055. this.y = y;
  1056. this.z = z;
  1057. this.w = w;
  1058. }
  1059. Quaternion.prototype.toString = function () {
  1060. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1061. };
  1062. Quaternion.prototype.asArray = function () {
  1063. return [this.x, this.y, this.z, this.w];
  1064. };
  1065. Quaternion.prototype.equals = function (otherQuaternion) {
  1066. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1067. };
  1068. Quaternion.prototype.clone = function () {
  1069. return new Quaternion(this.x, this.y, this.z, this.w);
  1070. };
  1071. Quaternion.prototype.copyFrom = function (other) {
  1072. this.x = other.x;
  1073. this.y = other.y;
  1074. this.z = other.z;
  1075. this.w = other.w;
  1076. return this;
  1077. };
  1078. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1079. this.x = x;
  1080. this.y = y;
  1081. this.z = z;
  1082. this.w = w;
  1083. return this;
  1084. };
  1085. Quaternion.prototype.add = function (other) {
  1086. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1087. };
  1088. Quaternion.prototype.subtract = function (other) {
  1089. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1090. };
  1091. Quaternion.prototype.scale = function (value) {
  1092. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1093. };
  1094. Quaternion.prototype.multiply = function (q1) {
  1095. var result = new Quaternion(0, 0, 0, 1.0);
  1096. this.multiplyToRef(q1, result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1100. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1101. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1102. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1103. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1104. return this;
  1105. };
  1106. Quaternion.prototype.length = function () {
  1107. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1108. };
  1109. Quaternion.prototype.normalize = function () {
  1110. var length = 1.0 / this.length();
  1111. this.x *= length;
  1112. this.y *= length;
  1113. this.z *= length;
  1114. this.w *= length;
  1115. return this;
  1116. };
  1117. Quaternion.prototype.toEulerAngles = function () {
  1118. var result = Vector3.Zero();
  1119. this.toEulerAnglesToRef(result);
  1120. return result;
  1121. };
  1122. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1123. //result is an EulerAngles in the in the z-x-z convention
  1124. var qx = this.x;
  1125. var qy = this.y;
  1126. var qz = this.z;
  1127. var qw = this.w;
  1128. var qxy = qx * qy;
  1129. var qxz = qx * qz;
  1130. var qwy = qw * qy;
  1131. var qwz = qw * qz;
  1132. var qwx = qw * qx;
  1133. var qyz = qy * qz;
  1134. var sqx = qx * qx;
  1135. var sqy = qy * qy;
  1136. var determinant = sqx + sqy;
  1137. if (determinant !== 0.000 && determinant !== 1.000) {
  1138. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1139. result.y = Math.acos(1 - 2 * determinant);
  1140. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1141. }
  1142. else {
  1143. if (determinant === 0.0) {
  1144. result.x = 0.0;
  1145. result.y = 0.0;
  1146. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1147. }
  1148. else {
  1149. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1150. result.y = Math.PI;
  1151. result.z = 0.0;
  1152. }
  1153. }
  1154. return this;
  1155. };
  1156. Quaternion.prototype.toRotationMatrix = function (result) {
  1157. var xx = this.x * this.x;
  1158. var yy = this.y * this.y;
  1159. var zz = this.z * this.z;
  1160. var xy = this.x * this.y;
  1161. var zw = this.z * this.w;
  1162. var zx = this.z * this.x;
  1163. var yw = this.y * this.w;
  1164. var yz = this.y * this.z;
  1165. var xw = this.x * this.w;
  1166. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1167. result.m[1] = 2.0 * (xy + zw);
  1168. result.m[2] = 2.0 * (zx - yw);
  1169. result.m[3] = 0;
  1170. result.m[4] = 2.0 * (xy - zw);
  1171. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1172. result.m[6] = 2.0 * (yz + xw);
  1173. result.m[7] = 0;
  1174. result.m[8] = 2.0 * (zx + yw);
  1175. result.m[9] = 2.0 * (yz - xw);
  1176. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1177. result.m[11] = 0;
  1178. result.m[12] = 0;
  1179. result.m[13] = 0;
  1180. result.m[14] = 0;
  1181. result.m[15] = 1.0;
  1182. return this;
  1183. };
  1184. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1185. Quaternion.FromRotationMatrixToRef(matrix, this);
  1186. return this;
  1187. };
  1188. // Statics
  1189. Quaternion.FromRotationMatrix = function (matrix) {
  1190. var result = new Quaternion();
  1191. Quaternion.FromRotationMatrixToRef(matrix, result);
  1192. return result;
  1193. };
  1194. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1195. var data = matrix.m;
  1196. var m11 = data[0], m12 = data[4], m13 = data[8];
  1197. var m21 = data[1], m22 = data[5], m23 = data[9];
  1198. var m31 = data[2], m32 = data[6], m33 = data[10];
  1199. var trace = m11 + m22 + m33;
  1200. var s;
  1201. if (trace > 0) {
  1202. s = 0.5 / Math.sqrt(trace + 1.0);
  1203. result.w = 0.25 / s;
  1204. result.x = (m32 - m23) * s;
  1205. result.y = (m13 - m31) * s;
  1206. result.z = (m21 - m12) * s;
  1207. }
  1208. else if (m11 > m22 && m11 > m33) {
  1209. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1210. result.w = (m32 - m23) / s;
  1211. result.x = 0.25 * s;
  1212. result.y = (m12 + m21) / s;
  1213. result.z = (m13 + m31) / s;
  1214. }
  1215. else if (m22 > m33) {
  1216. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1217. result.w = (m13 - m31) / s;
  1218. result.x = (m12 + m21) / s;
  1219. result.y = 0.25 * s;
  1220. result.z = (m23 + m32) / s;
  1221. }
  1222. else {
  1223. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1224. result.w = (m21 - m12) / s;
  1225. result.x = (m13 + m31) / s;
  1226. result.y = (m23 + m32) / s;
  1227. result.z = 0.25 * s;
  1228. }
  1229. };
  1230. Quaternion.Inverse = function (q) {
  1231. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1232. };
  1233. Quaternion.Identity = function () {
  1234. return new Quaternion(0, 0, 0, 1);
  1235. };
  1236. Quaternion.RotationAxis = function (axis, angle) {
  1237. var result = new Quaternion();
  1238. var sin = Math.sin(angle / 2);
  1239. result.w = Math.cos(angle / 2);
  1240. result.x = axis.x * sin;
  1241. result.y = axis.y * sin;
  1242. result.z = axis.z * sin;
  1243. return result;
  1244. };
  1245. Quaternion.FromArray = function (array, offset) {
  1246. if (!offset) {
  1247. offset = 0;
  1248. }
  1249. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1250. };
  1251. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1252. var result = new Quaternion();
  1253. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1254. return result;
  1255. };
  1256. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1257. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1258. var halfRoll = roll * 0.5;
  1259. var halfPitch = pitch * 0.5;
  1260. var halfYaw = yaw * 0.5;
  1261. var sinRoll = Math.sin(halfRoll);
  1262. var cosRoll = Math.cos(halfRoll);
  1263. var sinPitch = Math.sin(halfPitch);
  1264. var cosPitch = Math.cos(halfPitch);
  1265. var sinYaw = Math.sin(halfYaw);
  1266. var cosYaw = Math.cos(halfYaw);
  1267. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1268. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1269. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1270. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1271. };
  1272. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1273. var result = new Quaternion();
  1274. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1275. return result;
  1276. };
  1277. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1278. // Produces a quaternion from Euler angles in the z-x-z orientation
  1279. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1280. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1281. var halfBeta = beta * 0.5;
  1282. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1283. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1284. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1285. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1286. };
  1287. Quaternion.Slerp = function (left, right, amount) {
  1288. var num2;
  1289. var num3;
  1290. var num = amount;
  1291. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1292. var flag = false;
  1293. if (num4 < 0) {
  1294. flag = true;
  1295. num4 = -num4;
  1296. }
  1297. if (num4 > 0.999999) {
  1298. num3 = 1 - num;
  1299. num2 = flag ? -num : num;
  1300. }
  1301. else {
  1302. var num5 = Math.acos(num4);
  1303. var num6 = (1.0 / Math.sin(num5));
  1304. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1305. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1306. }
  1307. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1308. };
  1309. return Quaternion;
  1310. })();
  1311. BABYLON.Quaternion = Quaternion;
  1312. var Matrix = (function () {
  1313. function Matrix() {
  1314. this.m = new Float32Array(16);
  1315. }
  1316. // Properties
  1317. Matrix.prototype.isIdentity = function () {
  1318. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1319. return false;
  1320. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1321. return false;
  1322. return true;
  1323. };
  1324. Matrix.prototype.determinant = function () {
  1325. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1326. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1327. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1328. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1329. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1330. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1331. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1332. };
  1333. // Methods
  1334. Matrix.prototype.toArray = function () {
  1335. return this.m;
  1336. };
  1337. Matrix.prototype.asArray = function () {
  1338. return this.toArray();
  1339. };
  1340. Matrix.prototype.invert = function () {
  1341. this.invertToRef(this);
  1342. return this;
  1343. };
  1344. Matrix.prototype.invertToRef = function (other) {
  1345. var l1 = this.m[0];
  1346. var l2 = this.m[1];
  1347. var l3 = this.m[2];
  1348. var l4 = this.m[3];
  1349. var l5 = this.m[4];
  1350. var l6 = this.m[5];
  1351. var l7 = this.m[6];
  1352. var l8 = this.m[7];
  1353. var l9 = this.m[8];
  1354. var l10 = this.m[9];
  1355. var l11 = this.m[10];
  1356. var l12 = this.m[11];
  1357. var l13 = this.m[12];
  1358. var l14 = this.m[13];
  1359. var l15 = this.m[14];
  1360. var l16 = this.m[15];
  1361. var l17 = (l11 * l16) - (l12 * l15);
  1362. var l18 = (l10 * l16) - (l12 * l14);
  1363. var l19 = (l10 * l15) - (l11 * l14);
  1364. var l20 = (l9 * l16) - (l12 * l13);
  1365. var l21 = (l9 * l15) - (l11 * l13);
  1366. var l22 = (l9 * l14) - (l10 * l13);
  1367. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1368. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1369. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1370. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1371. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1372. var l28 = (l7 * l16) - (l8 * l15);
  1373. var l29 = (l6 * l16) - (l8 * l14);
  1374. var l30 = (l6 * l15) - (l7 * l14);
  1375. var l31 = (l5 * l16) - (l8 * l13);
  1376. var l32 = (l5 * l15) - (l7 * l13);
  1377. var l33 = (l5 * l14) - (l6 * l13);
  1378. var l34 = (l7 * l12) - (l8 * l11);
  1379. var l35 = (l6 * l12) - (l8 * l10);
  1380. var l36 = (l6 * l11) - (l7 * l10);
  1381. var l37 = (l5 * l12) - (l8 * l9);
  1382. var l38 = (l5 * l11) - (l7 * l9);
  1383. var l39 = (l5 * l10) - (l6 * l9);
  1384. other.m[0] = l23 * l27;
  1385. other.m[4] = l24 * l27;
  1386. other.m[8] = l25 * l27;
  1387. other.m[12] = l26 * l27;
  1388. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1389. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1390. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1391. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1392. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1393. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1394. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1395. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1396. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1397. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1398. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1399. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1400. return this;
  1401. };
  1402. Matrix.prototype.invertToRefSIMD = function (other) {
  1403. var src = this.m;
  1404. var dest = other.m;
  1405. var row0, row1, row2, row3;
  1406. var tmp1;
  1407. var minor0, minor1, minor2, minor3;
  1408. var det;
  1409. // Load the 4 rows
  1410. var src0 = SIMD.float32x4.load(src, 0);
  1411. var src1 = SIMD.float32x4.load(src, 4);
  1412. var src2 = SIMD.float32x4.load(src, 8);
  1413. var src3 = SIMD.float32x4.load(src, 12);
  1414. // Transpose the source matrix. Sort of. Not a true transpose operation
  1415. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1416. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1417. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1418. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1419. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1420. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1421. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1422. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1423. // This is a true transposition, but it will lead to an incorrect result
  1424. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1425. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1426. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1427. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1428. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1429. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1430. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1431. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1432. // ----
  1433. tmp1 = SIMD.float32x4.mul(row2, row3);
  1434. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1435. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1436. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1437. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1438. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1439. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1440. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1441. // ----
  1442. tmp1 = SIMD.float32x4.mul(row1, row2);
  1443. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1444. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1445. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1446. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1447. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1448. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1449. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1450. // ----
  1451. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1452. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1453. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1454. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1455. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1456. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1457. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1458. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1459. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1460. // ----
  1461. tmp1 = SIMD.float32x4.mul(row0, row1);
  1462. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1463. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1464. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1465. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1466. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1467. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1468. // ----
  1469. tmp1 = SIMD.float32x4.mul(row0, row3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1471. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1472. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1473. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1474. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1475. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1476. // ----
  1477. tmp1 = SIMD.float32x4.mul(row0, row2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1480. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1481. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1482. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1483. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1484. // Compute determinant
  1485. det = SIMD.float32x4.mul(row0, minor0);
  1486. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1487. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1488. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1489. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1490. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1491. // These shuffles aren't necessary if the faulty transposition is done
  1492. // up at the top of this function.
  1493. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1494. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1495. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1496. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1497. // Compute final values by multiplying with 1/det
  1498. minor0 = SIMD.float32x4.mul(det, minor0);
  1499. minor1 = SIMD.float32x4.mul(det, minor1);
  1500. minor2 = SIMD.float32x4.mul(det, minor2);
  1501. minor3 = SIMD.float32x4.mul(det, minor3);
  1502. SIMD.float32x4.store(dest, 0, minor0);
  1503. SIMD.float32x4.store(dest, 4, minor1);
  1504. SIMD.float32x4.store(dest, 8, minor2);
  1505. SIMD.float32x4.store(dest, 12, minor3);
  1506. return this;
  1507. };
  1508. Matrix.prototype.setTranslation = function (vector3) {
  1509. this.m[12] = vector3.x;
  1510. this.m[13] = vector3.y;
  1511. this.m[14] = vector3.z;
  1512. return this;
  1513. };
  1514. Matrix.prototype.multiply = function (other) {
  1515. var result = new Matrix();
  1516. this.multiplyToRef(other, result);
  1517. return result;
  1518. };
  1519. Matrix.prototype.copyFrom = function (other) {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] = other.m[index];
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.copyToArray = function (array, offset) {
  1526. if (offset === void 0) { offset = 0; }
  1527. for (var index = 0; index < 16; index++) {
  1528. array[offset + index] = this.m[index];
  1529. }
  1530. return this;
  1531. };
  1532. Matrix.prototype.multiplyToRef = function (other, result) {
  1533. this.multiplyToArray(other, result.m, 0);
  1534. return this;
  1535. };
  1536. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1537. var tm0 = this.m[0];
  1538. var tm1 = this.m[1];
  1539. var tm2 = this.m[2];
  1540. var tm3 = this.m[3];
  1541. var tm4 = this.m[4];
  1542. var tm5 = this.m[5];
  1543. var tm6 = this.m[6];
  1544. var tm7 = this.m[7];
  1545. var tm8 = this.m[8];
  1546. var tm9 = this.m[9];
  1547. var tm10 = this.m[10];
  1548. var tm11 = this.m[11];
  1549. var tm12 = this.m[12];
  1550. var tm13 = this.m[13];
  1551. var tm14 = this.m[14];
  1552. var tm15 = this.m[15];
  1553. var om0 = other.m[0];
  1554. var om1 = other.m[1];
  1555. var om2 = other.m[2];
  1556. var om3 = other.m[3];
  1557. var om4 = other.m[4];
  1558. var om5 = other.m[5];
  1559. var om6 = other.m[6];
  1560. var om7 = other.m[7];
  1561. var om8 = other.m[8];
  1562. var om9 = other.m[9];
  1563. var om10 = other.m[10];
  1564. var om11 = other.m[11];
  1565. var om12 = other.m[12];
  1566. var om13 = other.m[13];
  1567. var om14 = other.m[14];
  1568. var om15 = other.m[15];
  1569. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1570. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1571. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1572. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1573. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1574. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1575. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1576. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1577. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1578. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1579. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1580. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1581. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1582. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1583. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1584. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1585. return this;
  1586. };
  1587. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1588. if (offset === void 0) { offset = 0; }
  1589. var tm = this.m;
  1590. var om = other.m;
  1591. var om0 = SIMD.float32x4.load(om, 0);
  1592. var om1 = SIMD.float32x4.load(om, 4);
  1593. var om2 = SIMD.float32x4.load(om, 8);
  1594. var om3 = SIMD.float32x4.load(om, 12);
  1595. var tm0 = SIMD.float32x4.load(tm, 0);
  1596. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1597. var tm1 = SIMD.float32x4.load(tm, 4);
  1598. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1599. var tm2 = SIMD.float32x4.load(tm, 8);
  1600. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1601. var tm3 = SIMD.float32x4.load(tm, 12);
  1602. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1603. };
  1604. Matrix.prototype.equals = function (value) {
  1605. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1606. };
  1607. Matrix.prototype.clone = function () {
  1608. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1609. };
  1610. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1611. translation.x = this.m[12];
  1612. translation.y = this.m[13];
  1613. translation.z = this.m[14];
  1614. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1615. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1616. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1617. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1618. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1619. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1620. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1621. rotation.x = 0;
  1622. rotation.y = 0;
  1623. rotation.z = 0;
  1624. rotation.w = 1;
  1625. return false;
  1626. }
  1627. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1628. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1629. return true;
  1630. };
  1631. // Statics
  1632. Matrix.FromArray = function (array, offset) {
  1633. var result = new Matrix();
  1634. if (!offset) {
  1635. offset = 0;
  1636. }
  1637. Matrix.FromArrayToRef(array, offset, result);
  1638. return result;
  1639. };
  1640. Matrix.FromArrayToRef = function (array, offset, result) {
  1641. for (var index = 0; index < 16; index++) {
  1642. result.m[index] = array[index + offset];
  1643. }
  1644. };
  1645. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1646. result.m[0] = initialM11;
  1647. result.m[1] = initialM12;
  1648. result.m[2] = initialM13;
  1649. result.m[3] = initialM14;
  1650. result.m[4] = initialM21;
  1651. result.m[5] = initialM22;
  1652. result.m[6] = initialM23;
  1653. result.m[7] = initialM24;
  1654. result.m[8] = initialM31;
  1655. result.m[9] = initialM32;
  1656. result.m[10] = initialM33;
  1657. result.m[11] = initialM34;
  1658. result.m[12] = initialM41;
  1659. result.m[13] = initialM42;
  1660. result.m[14] = initialM43;
  1661. result.m[15] = initialM44;
  1662. };
  1663. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1664. var result = new Matrix();
  1665. result.m[0] = initialM11;
  1666. result.m[1] = initialM12;
  1667. result.m[2] = initialM13;
  1668. result.m[3] = initialM14;
  1669. result.m[4] = initialM21;
  1670. result.m[5] = initialM22;
  1671. result.m[6] = initialM23;
  1672. result.m[7] = initialM24;
  1673. result.m[8] = initialM31;
  1674. result.m[9] = initialM32;
  1675. result.m[10] = initialM33;
  1676. result.m[11] = initialM34;
  1677. result.m[12] = initialM41;
  1678. result.m[13] = initialM42;
  1679. result.m[14] = initialM43;
  1680. result.m[15] = initialM44;
  1681. return result;
  1682. };
  1683. Matrix.Compose = function (scale, rotation, translation) {
  1684. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1685. var rotationMatrix = Matrix.Identity();
  1686. rotation.toRotationMatrix(rotationMatrix);
  1687. result = result.multiply(rotationMatrix);
  1688. result.setTranslation(translation);
  1689. return result;
  1690. };
  1691. Matrix.Identity = function () {
  1692. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1693. };
  1694. Matrix.IdentityToRef = function (result) {
  1695. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1696. };
  1697. Matrix.Zero = function () {
  1698. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1699. };
  1700. Matrix.RotationX = function (angle) {
  1701. var result = new Matrix();
  1702. Matrix.RotationXToRef(angle, result);
  1703. return result;
  1704. };
  1705. Matrix.Invert = function (source) {
  1706. var result = new Matrix();
  1707. source.invertToRef(result);
  1708. return result;
  1709. };
  1710. Matrix.RotationXToRef = function (angle, result) {
  1711. var s = Math.sin(angle);
  1712. var c = Math.cos(angle);
  1713. result.m[0] = 1.0;
  1714. result.m[15] = 1.0;
  1715. result.m[5] = c;
  1716. result.m[10] = c;
  1717. result.m[9] = -s;
  1718. result.m[6] = s;
  1719. result.m[1] = 0;
  1720. result.m[2] = 0;
  1721. result.m[3] = 0;
  1722. result.m[4] = 0;
  1723. result.m[7] = 0;
  1724. result.m[8] = 0;
  1725. result.m[11] = 0;
  1726. result.m[12] = 0;
  1727. result.m[13] = 0;
  1728. result.m[14] = 0;
  1729. };
  1730. Matrix.RotationY = function (angle) {
  1731. var result = new Matrix();
  1732. Matrix.RotationYToRef(angle, result);
  1733. return result;
  1734. };
  1735. Matrix.RotationYToRef = function (angle, result) {
  1736. var s = Math.sin(angle);
  1737. var c = Math.cos(angle);
  1738. result.m[5] = 1.0;
  1739. result.m[15] = 1.0;
  1740. result.m[0] = c;
  1741. result.m[2] = -s;
  1742. result.m[8] = s;
  1743. result.m[10] = c;
  1744. result.m[1] = 0;
  1745. result.m[3] = 0;
  1746. result.m[4] = 0;
  1747. result.m[6] = 0;
  1748. result.m[7] = 0;
  1749. result.m[9] = 0;
  1750. result.m[11] = 0;
  1751. result.m[12] = 0;
  1752. result.m[13] = 0;
  1753. result.m[14] = 0;
  1754. };
  1755. Matrix.RotationZ = function (angle) {
  1756. var result = new Matrix();
  1757. Matrix.RotationZToRef(angle, result);
  1758. return result;
  1759. };
  1760. Matrix.RotationZToRef = function (angle, result) {
  1761. var s = Math.sin(angle);
  1762. var c = Math.cos(angle);
  1763. result.m[10] = 1.0;
  1764. result.m[15] = 1.0;
  1765. result.m[0] = c;
  1766. result.m[1] = s;
  1767. result.m[4] = -s;
  1768. result.m[5] = c;
  1769. result.m[2] = 0;
  1770. result.m[3] = 0;
  1771. result.m[6] = 0;
  1772. result.m[7] = 0;
  1773. result.m[8] = 0;
  1774. result.m[9] = 0;
  1775. result.m[11] = 0;
  1776. result.m[12] = 0;
  1777. result.m[13] = 0;
  1778. result.m[14] = 0;
  1779. };
  1780. Matrix.RotationAxis = function (axis, angle) {
  1781. var s = Math.sin(-angle);
  1782. var c = Math.cos(-angle);
  1783. var c1 = 1 - c;
  1784. axis.normalize();
  1785. var result = Matrix.Zero();
  1786. result.m[0] = (axis.x * axis.x) * c1 + c;
  1787. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1788. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1789. result.m[3] = 0.0;
  1790. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1791. result.m[5] = (axis.y * axis.y) * c1 + c;
  1792. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1793. result.m[7] = 0.0;
  1794. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1795. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1796. result.m[10] = (axis.z * axis.z) * c1 + c;
  1797. result.m[11] = 0.0;
  1798. result.m[15] = 1.0;
  1799. return result;
  1800. };
  1801. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1802. var result = new Matrix();
  1803. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1807. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1808. this._tempQuaternion.toRotationMatrix(result);
  1809. };
  1810. Matrix.Scaling = function (x, y, z) {
  1811. var result = Matrix.Zero();
  1812. Matrix.ScalingToRef(x, y, z, result);
  1813. return result;
  1814. };
  1815. Matrix.ScalingToRef = function (x, y, z, result) {
  1816. result.m[0] = x;
  1817. result.m[1] = 0;
  1818. result.m[2] = 0;
  1819. result.m[3] = 0;
  1820. result.m[4] = 0;
  1821. result.m[5] = y;
  1822. result.m[6] = 0;
  1823. result.m[7] = 0;
  1824. result.m[8] = 0;
  1825. result.m[9] = 0;
  1826. result.m[10] = z;
  1827. result.m[11] = 0;
  1828. result.m[12] = 0;
  1829. result.m[13] = 0;
  1830. result.m[14] = 0;
  1831. result.m[15] = 1.0;
  1832. };
  1833. Matrix.Translation = function (x, y, z) {
  1834. var result = Matrix.Identity();
  1835. Matrix.TranslationToRef(x, y, z, result);
  1836. return result;
  1837. };
  1838. Matrix.TranslationToRef = function (x, y, z, result) {
  1839. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1840. };
  1841. Matrix.LookAtLH = function (eye, target, up) {
  1842. var result = Matrix.Zero();
  1843. Matrix.LookAtLHToRef(eye, target, up, result);
  1844. return result;
  1845. };
  1846. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1847. // Z axis
  1848. target.subtractToRef(eye, this._zAxis);
  1849. this._zAxis.normalize();
  1850. // X axis
  1851. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1852. this._xAxis.normalize();
  1853. // Y axis
  1854. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1855. this._yAxis.normalize();
  1856. // Eye angles
  1857. var ex = -Vector3.Dot(this._xAxis, eye);
  1858. var ey = -Vector3.Dot(this._yAxis, eye);
  1859. var ez = -Vector3.Dot(this._zAxis, eye);
  1860. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1861. };
  1862. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1863. var out = result.m;
  1864. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1865. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1866. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1867. // cc.kmVec3Subtract(f, pCenter, pEye);
  1868. var f = SIMD.float32x4.sub(center, eye);
  1869. // cc.kmVec3Normalize(f, f);
  1870. var tmp = SIMD.float32x4.mul(f, f);
  1871. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1872. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1873. // cc.kmVec3Assign(up, pUp);
  1874. // cc.kmVec3Normalize(up, up);
  1875. tmp = SIMD.float32x4.mul(up, up);
  1876. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1877. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1878. // cc.kmVec3Cross(s, f, up);
  1879. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1880. // cc.kmVec3Normalize(s, s);
  1881. tmp = SIMD.float32x4.mul(s, s);
  1882. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1883. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1884. // cc.kmVec3Cross(u, s, f);
  1885. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1886. // cc.kmVec3Normalize(s, s);
  1887. tmp = SIMD.float32x4.mul(s, s);
  1888. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1889. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1890. var zero = SIMD.float32x4.splat(0.0);
  1891. s = SIMD.float32x4.neg(s);
  1892. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1893. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1894. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1895. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1896. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1897. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1898. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1899. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1900. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1901. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1902. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1903. var b3 = SIMD.float32x4.neg(eye);
  1904. b3 = SIMD.float32x4.withW(b3, 1.0);
  1905. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1906. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1907. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1908. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1909. };
  1910. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1911. var matrix = Matrix.Zero();
  1912. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1913. return matrix;
  1914. };
  1915. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1916. var hw = 2.0 / width;
  1917. var hh = 2.0 / height;
  1918. var id = 1.0 / (zfar - znear);
  1919. var nid = znear / (znear - zfar);
  1920. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1921. };
  1922. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1923. var matrix = Matrix.Zero();
  1924. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1925. return matrix;
  1926. };
  1927. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1928. result.m[0] = 2.0 / (right - left);
  1929. result.m[1] = result.m[2] = result.m[3] = 0;
  1930. result.m[5] = 2.0 / (top - bottom);
  1931. result.m[4] = result.m[6] = result.m[7] = 0;
  1932. result.m[10] = -1.0 / (znear - zfar);
  1933. result.m[8] = result.m[9] = result.m[11] = 0;
  1934. result.m[12] = (left + right) / (left - right);
  1935. result.m[13] = (top + bottom) / (bottom - top);
  1936. result.m[14] = znear / (znear - zfar);
  1937. result.m[15] = 1.0;
  1938. };
  1939. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1940. var matrix = Matrix.Zero();
  1941. matrix.m[0] = (2.0 * znear) / width;
  1942. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1943. matrix.m[5] = (2.0 * znear) / height;
  1944. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1945. matrix.m[10] = -zfar / (znear - zfar);
  1946. matrix.m[8] = matrix.m[9] = 0.0;
  1947. matrix.m[11] = 1.0;
  1948. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1949. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1950. return matrix;
  1951. };
  1952. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1953. var matrix = Matrix.Zero();
  1954. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1955. return matrix;
  1956. };
  1957. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1958. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1959. var tan = 1.0 / (Math.tan(fov * 0.5));
  1960. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1961. if (v_fixed) {
  1962. result.m[0] = tan / aspect;
  1963. }
  1964. else {
  1965. result.m[0] = tan;
  1966. }
  1967. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1968. if (v_fixed) {
  1969. result.m[5] = tan;
  1970. }
  1971. else {
  1972. result.m[5] = tan * aspect;
  1973. }
  1974. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1975. result.m[8] = result.m[9] = 0.0;
  1976. result.m[10] = -zfar / (znear - zfar);
  1977. result.m[11] = 1.0;
  1978. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1979. result.m[14] = (znear * zfar) / (znear - zfar);
  1980. };
  1981. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1982. var cw = viewport.width;
  1983. var ch = viewport.height;
  1984. var cx = viewport.x;
  1985. var cy = viewport.y;
  1986. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1987. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1988. };
  1989. Matrix.Transpose = function (matrix) {
  1990. var result = new Matrix();
  1991. result.m[0] = matrix.m[0];
  1992. result.m[1] = matrix.m[4];
  1993. result.m[2] = matrix.m[8];
  1994. result.m[3] = matrix.m[12];
  1995. result.m[4] = matrix.m[1];
  1996. result.m[5] = matrix.m[5];
  1997. result.m[6] = matrix.m[9];
  1998. result.m[7] = matrix.m[13];
  1999. result.m[8] = matrix.m[2];
  2000. result.m[9] = matrix.m[6];
  2001. result.m[10] = matrix.m[10];
  2002. result.m[11] = matrix.m[14];
  2003. result.m[12] = matrix.m[3];
  2004. result.m[13] = matrix.m[7];
  2005. result.m[14] = matrix.m[11];
  2006. result.m[15] = matrix.m[15];
  2007. return result;
  2008. };
  2009. Matrix.Reflection = function (plane) {
  2010. var matrix = new Matrix();
  2011. Matrix.ReflectionToRef(plane, matrix);
  2012. return matrix;
  2013. };
  2014. Matrix.ReflectionToRef = function (plane, result) {
  2015. plane.normalize();
  2016. var x = plane.normal.x;
  2017. var y = plane.normal.y;
  2018. var z = plane.normal.z;
  2019. var temp = -2 * x;
  2020. var temp2 = -2 * y;
  2021. var temp3 = -2 * z;
  2022. result.m[0] = (temp * x) + 1;
  2023. result.m[1] = temp2 * x;
  2024. result.m[2] = temp3 * x;
  2025. result.m[3] = 0.0;
  2026. result.m[4] = temp * y;
  2027. result.m[5] = (temp2 * y) + 1;
  2028. result.m[6] = temp3 * y;
  2029. result.m[7] = 0.0;
  2030. result.m[8] = temp * z;
  2031. result.m[9] = temp2 * z;
  2032. result.m[10] = (temp3 * z) + 1;
  2033. result.m[11] = 0.0;
  2034. result.m[12] = temp * plane.d;
  2035. result.m[13] = temp2 * plane.d;
  2036. result.m[14] = temp3 * plane.d;
  2037. result.m[15] = 1.0;
  2038. };
  2039. Matrix._tempQuaternion = new Quaternion();
  2040. Matrix._xAxis = Vector3.Zero();
  2041. Matrix._yAxis = Vector3.Zero();
  2042. Matrix._zAxis = Vector3.Zero();
  2043. return Matrix;
  2044. })();
  2045. BABYLON.Matrix = Matrix;
  2046. var Plane = (function () {
  2047. function Plane(a, b, c, d) {
  2048. this.normal = new Vector3(a, b, c);
  2049. this.d = d;
  2050. }
  2051. Plane.prototype.asArray = function () {
  2052. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2053. };
  2054. // Methods
  2055. Plane.prototype.clone = function () {
  2056. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2057. };
  2058. Plane.prototype.normalize = function () {
  2059. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2060. var magnitude = 0;
  2061. if (norm !== 0) {
  2062. magnitude = 1.0 / norm;
  2063. }
  2064. this.normal.x *= magnitude;
  2065. this.normal.y *= magnitude;
  2066. this.normal.z *= magnitude;
  2067. this.d *= magnitude;
  2068. return this;
  2069. };
  2070. Plane.prototype.transform = function (transformation) {
  2071. var transposedMatrix = Matrix.Transpose(transformation);
  2072. var x = this.normal.x;
  2073. var y = this.normal.y;
  2074. var z = this.normal.z;
  2075. var d = this.d;
  2076. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2077. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2078. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2079. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2080. return new Plane(normalX, normalY, normalZ, finalD);
  2081. };
  2082. Plane.prototype.dotCoordinate = function (point) {
  2083. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2084. };
  2085. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2086. var x1 = point2.x - point1.x;
  2087. var y1 = point2.y - point1.y;
  2088. var z1 = point2.z - point1.z;
  2089. var x2 = point3.x - point1.x;
  2090. var y2 = point3.y - point1.y;
  2091. var z2 = point3.z - point1.z;
  2092. var yz = (y1 * z2) - (z1 * y2);
  2093. var xz = (z1 * x2) - (x1 * z2);
  2094. var xy = (x1 * y2) - (y1 * x2);
  2095. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2096. var invPyth;
  2097. if (pyth !== 0) {
  2098. invPyth = 1.0 / pyth;
  2099. }
  2100. else {
  2101. invPyth = 0;
  2102. }
  2103. this.normal.x = yz * invPyth;
  2104. this.normal.y = xz * invPyth;
  2105. this.normal.z = xy * invPyth;
  2106. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2107. return this;
  2108. };
  2109. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2110. var dot = Vector3.Dot(this.normal, direction);
  2111. return (dot <= epsilon);
  2112. };
  2113. Plane.prototype.signedDistanceTo = function (point) {
  2114. return Vector3.Dot(point, this.normal) + this.d;
  2115. };
  2116. // Statics
  2117. Plane.FromArray = function (array) {
  2118. return new Plane(array[0], array[1], array[2], array[3]);
  2119. };
  2120. Plane.FromPoints = function (point1, point2, point3) {
  2121. var result = new Plane(0, 0, 0, 0);
  2122. result.copyFromPoints(point1, point2, point3);
  2123. return result;
  2124. };
  2125. Plane.FromPositionAndNormal = function (origin, normal) {
  2126. var result = new Plane(0, 0, 0, 0);
  2127. normal.normalize();
  2128. result.normal = normal;
  2129. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2130. return result;
  2131. };
  2132. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2133. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2134. return Vector3.Dot(point, normal) + d;
  2135. };
  2136. return Plane;
  2137. })();
  2138. BABYLON.Plane = Plane;
  2139. var Viewport = (function () {
  2140. function Viewport(x, y, width, height) {
  2141. this.x = x;
  2142. this.y = y;
  2143. this.width = width;
  2144. this.height = height;
  2145. }
  2146. Viewport.prototype.toGlobal = function (engine) {
  2147. var width = engine.getRenderWidth();
  2148. var height = engine.getRenderHeight();
  2149. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2150. };
  2151. return Viewport;
  2152. })();
  2153. BABYLON.Viewport = Viewport;
  2154. var Frustum = (function () {
  2155. function Frustum() {
  2156. }
  2157. Frustum.GetPlanes = function (transform) {
  2158. var frustumPlanes = [];
  2159. for (var index = 0; index < 6; index++) {
  2160. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2161. }
  2162. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2163. return frustumPlanes;
  2164. };
  2165. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2166. // Near
  2167. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2168. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2169. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2170. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2171. frustumPlanes[0].normalize();
  2172. // Far
  2173. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2174. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2175. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2176. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2177. frustumPlanes[1].normalize();
  2178. // Left
  2179. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2180. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2181. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2182. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2183. frustumPlanes[2].normalize();
  2184. // Right
  2185. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2186. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2187. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2188. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2189. frustumPlanes[3].normalize();
  2190. // Top
  2191. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2192. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2193. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2194. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2195. frustumPlanes[4].normalize();
  2196. // Bottom
  2197. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2198. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2199. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2200. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2201. frustumPlanes[5].normalize();
  2202. };
  2203. return Frustum;
  2204. })();
  2205. BABYLON.Frustum = Frustum;
  2206. var Ray = (function () {
  2207. function Ray(origin, direction, length) {
  2208. if (length === void 0) { length = Number.MAX_VALUE; }
  2209. this.origin = origin;
  2210. this.direction = direction;
  2211. this.length = length;
  2212. }
  2213. // Methods
  2214. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2215. var d = 0.0;
  2216. var maxValue = Number.MAX_VALUE;
  2217. if (Math.abs(this.direction.x) < 0.0000001) {
  2218. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2219. return false;
  2220. }
  2221. }
  2222. else {
  2223. var inv = 1.0 / this.direction.x;
  2224. var min = (minimum.x - this.origin.x) * inv;
  2225. var max = (maximum.x - this.origin.x) * inv;
  2226. if (max === -Infinity) {
  2227. max = Infinity;
  2228. }
  2229. if (min > max) {
  2230. var temp = min;
  2231. min = max;
  2232. max = temp;
  2233. }
  2234. d = Math.max(min, d);
  2235. maxValue = Math.min(max, maxValue);
  2236. if (d > maxValue) {
  2237. return false;
  2238. }
  2239. }
  2240. if (Math.abs(this.direction.y) < 0.0000001) {
  2241. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2242. return false;
  2243. }
  2244. }
  2245. else {
  2246. inv = 1.0 / this.direction.y;
  2247. min = (minimum.y - this.origin.y) * inv;
  2248. max = (maximum.y - this.origin.y) * inv;
  2249. if (max === -Infinity) {
  2250. max = Infinity;
  2251. }
  2252. if (min > max) {
  2253. temp = min;
  2254. min = max;
  2255. max = temp;
  2256. }
  2257. d = Math.max(min, d);
  2258. maxValue = Math.min(max, maxValue);
  2259. if (d > maxValue) {
  2260. return false;
  2261. }
  2262. }
  2263. if (Math.abs(this.direction.z) < 0.0000001) {
  2264. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2265. return false;
  2266. }
  2267. }
  2268. else {
  2269. inv = 1.0 / this.direction.z;
  2270. min = (minimum.z - this.origin.z) * inv;
  2271. max = (maximum.z - this.origin.z) * inv;
  2272. if (max === -Infinity) {
  2273. max = Infinity;
  2274. }
  2275. if (min > max) {
  2276. temp = min;
  2277. min = max;
  2278. max = temp;
  2279. }
  2280. d = Math.max(min, d);
  2281. maxValue = Math.min(max, maxValue);
  2282. if (d > maxValue) {
  2283. return false;
  2284. }
  2285. }
  2286. return true;
  2287. };
  2288. Ray.prototype.intersectsBox = function (box) {
  2289. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2290. };
  2291. Ray.prototype.intersectsSphere = function (sphere) {
  2292. var x = sphere.center.x - this.origin.x;
  2293. var y = sphere.center.y - this.origin.y;
  2294. var z = sphere.center.z - this.origin.z;
  2295. var pyth = (x * x) + (y * y) + (z * z);
  2296. var rr = sphere.radius * sphere.radius;
  2297. if (pyth <= rr) {
  2298. return true;
  2299. }
  2300. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2301. if (dot < 0.0) {
  2302. return false;
  2303. }
  2304. var temp = pyth - (dot * dot);
  2305. return temp <= rr;
  2306. };
  2307. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2308. if (!this._edge1) {
  2309. this._edge1 = Vector3.Zero();
  2310. this._edge2 = Vector3.Zero();
  2311. this._pvec = Vector3.Zero();
  2312. this._tvec = Vector3.Zero();
  2313. this._qvec = Vector3.Zero();
  2314. }
  2315. vertex1.subtractToRef(vertex0, this._edge1);
  2316. vertex2.subtractToRef(vertex0, this._edge2);
  2317. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2318. var det = Vector3.Dot(this._edge1, this._pvec);
  2319. if (det === 0) {
  2320. return null;
  2321. }
  2322. var invdet = 1 / det;
  2323. this.origin.subtractToRef(vertex0, this._tvec);
  2324. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2325. if (bu < 0 || bu > 1.0) {
  2326. return null;
  2327. }
  2328. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2329. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2330. if (bv < 0 || bu + bv > 1.0) {
  2331. return null;
  2332. }
  2333. //check if the distance is longer than the predefined length.
  2334. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2335. if (distance > this.length) {
  2336. return null;
  2337. }
  2338. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2339. };
  2340. // Statics
  2341. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2342. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2343. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2344. var direction = end.subtract(start);
  2345. direction.normalize();
  2346. return new Ray(start, direction);
  2347. };
  2348. /**
  2349. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2350. * transformed to the given world matrix.
  2351. * @param origin The origin point
  2352. * @param end The end point
  2353. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2354. */
  2355. Ray.CreateNewFromTo = function (origin, end, world) {
  2356. if (world === void 0) { world = Matrix.Identity(); }
  2357. var direction = end.subtract(origin);
  2358. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2359. direction.normalize();
  2360. return Ray.Transform(new Ray(origin, direction, length), world);
  2361. };
  2362. Ray.Transform = function (ray, matrix) {
  2363. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2364. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2365. return new Ray(newOrigin, newDirection, ray.length);
  2366. };
  2367. return Ray;
  2368. })();
  2369. BABYLON.Ray = Ray;
  2370. (function (Space) {
  2371. Space[Space["LOCAL"] = 0] = "LOCAL";
  2372. Space[Space["WORLD"] = 1] = "WORLD";
  2373. })(BABYLON.Space || (BABYLON.Space = {}));
  2374. var Space = BABYLON.Space;
  2375. var Axis = (function () {
  2376. function Axis() {
  2377. }
  2378. Axis.X = new Vector3(1, 0, 0);
  2379. Axis.Y = new Vector3(0, 1, 0);
  2380. Axis.Z = new Vector3(0, 0, 1);
  2381. return Axis;
  2382. })();
  2383. BABYLON.Axis = Axis;
  2384. ;
  2385. var BezierCurve = (function () {
  2386. function BezierCurve() {
  2387. }
  2388. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2389. // Extract X (which is equal to time here)
  2390. var f0 = 1 - 3 * x2 + 3 * x1;
  2391. var f1 = 3 * x2 - 6 * x1;
  2392. var f2 = 3 * x1;
  2393. var refinedT = t;
  2394. for (var i = 0; i < 5; i++) {
  2395. var refinedT2 = refinedT * refinedT;
  2396. var refinedT3 = refinedT2 * refinedT;
  2397. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2398. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2399. refinedT -= (x - t) * slope;
  2400. refinedT = Math.min(1, Math.max(0, refinedT));
  2401. }
  2402. // Resolve cubic bezier for the given x
  2403. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2404. };
  2405. return BezierCurve;
  2406. })();
  2407. BABYLON.BezierCurve = BezierCurve;
  2408. (function (Orientation) {
  2409. Orientation[Orientation["CW"] = 0] = "CW";
  2410. Orientation[Orientation["CCW"] = 1] = "CCW";
  2411. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2412. var Orientation = BABYLON.Orientation;
  2413. var Angle = (function () {
  2414. function Angle(radians) {
  2415. var _this = this;
  2416. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2417. this.radians = function () { return _this._radians; };
  2418. this._radians = radians;
  2419. if (this._radians < 0)
  2420. this._radians += (2 * Math.PI);
  2421. }
  2422. Angle.BetweenTwoPoints = function (a, b) {
  2423. var delta = b.subtract(a);
  2424. var theta = Math.atan2(delta.y, delta.x);
  2425. return new Angle(theta);
  2426. };
  2427. Angle.FromRadians = function (radians) {
  2428. return new Angle(radians);
  2429. };
  2430. Angle.FromDegrees = function (degrees) {
  2431. return new Angle(degrees * Math.PI / 180);
  2432. };
  2433. return Angle;
  2434. })();
  2435. BABYLON.Angle = Angle;
  2436. var Arc2 = (function () {
  2437. function Arc2(startPoint, midPoint, endPoint) {
  2438. this.startPoint = startPoint;
  2439. this.midPoint = midPoint;
  2440. this.endPoint = endPoint;
  2441. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2442. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2443. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2444. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2445. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2446. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2447. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2448. var a1 = this.startAngle.degrees();
  2449. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2450. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2451. // angles correction
  2452. if (a2 - a1 > +180.0)
  2453. a2 -= 360.0;
  2454. if (a2 - a1 < -180.0)
  2455. a2 += 360.0;
  2456. if (a3 - a2 > +180.0)
  2457. a3 -= 360.0;
  2458. if (a3 - a2 < -180.0)
  2459. a3 += 360.0;
  2460. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2461. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2462. }
  2463. return Arc2;
  2464. })();
  2465. BABYLON.Arc2 = Arc2;
  2466. var PathCursor = (function () {
  2467. function PathCursor(path) {
  2468. this.path = path;
  2469. this._onchange = new Array();
  2470. this.value = 0;
  2471. this.animations = new Array();
  2472. }
  2473. PathCursor.prototype.getPoint = function () {
  2474. var point = this.path.getPointAtLengthPosition(this.value);
  2475. return new Vector3(point.x, 0, point.y);
  2476. };
  2477. PathCursor.prototype.moveAhead = function (step) {
  2478. if (step === void 0) { step = 0.002; }
  2479. this.move(step);
  2480. return this;
  2481. };
  2482. PathCursor.prototype.moveBack = function (step) {
  2483. if (step === void 0) { step = 0.002; }
  2484. this.move(-step);
  2485. return this;
  2486. };
  2487. PathCursor.prototype.move = function (step) {
  2488. if (Math.abs(step) > 1) {
  2489. throw "step size should be less than 1.";
  2490. }
  2491. this.value += step;
  2492. this.ensureLimits();
  2493. this.raiseOnChange();
  2494. return this;
  2495. };
  2496. PathCursor.prototype.ensureLimits = function () {
  2497. while (this.value > 1) {
  2498. this.value -= 1;
  2499. }
  2500. while (this.value < 0) {
  2501. this.value += 1;
  2502. }
  2503. return this;
  2504. };
  2505. // used by animation engine
  2506. PathCursor.prototype.markAsDirty = function (propertyName) {
  2507. this.ensureLimits();
  2508. this.raiseOnChange();
  2509. return this;
  2510. };
  2511. PathCursor.prototype.raiseOnChange = function () {
  2512. var _this = this;
  2513. this._onchange.forEach(function (f) { return f(_this); });
  2514. return this;
  2515. };
  2516. PathCursor.prototype.onchange = function (f) {
  2517. this._onchange.push(f);
  2518. return this;
  2519. };
  2520. return PathCursor;
  2521. })();
  2522. BABYLON.PathCursor = PathCursor;
  2523. var Path2 = (function () {
  2524. function Path2(x, y) {
  2525. this._points = new Array();
  2526. this._length = 0;
  2527. this.closed = false;
  2528. this._points.push(new Vector2(x, y));
  2529. }
  2530. Path2.prototype.addLineTo = function (x, y) {
  2531. if (closed) {
  2532. BABYLON.Tools.Error("cannot add lines to closed paths");
  2533. return this;
  2534. }
  2535. var newPoint = new Vector2(x, y);
  2536. var previousPoint = this._points[this._points.length - 1];
  2537. this._points.push(newPoint);
  2538. this._length += newPoint.subtract(previousPoint).length();
  2539. return this;
  2540. };
  2541. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2542. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2543. if (closed) {
  2544. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2545. return this;
  2546. }
  2547. var startPoint = this._points[this._points.length - 1];
  2548. var midPoint = new Vector2(midX, midY);
  2549. var endPoint = new Vector2(endX, endY);
  2550. var arc = new Arc2(startPoint, midPoint, endPoint);
  2551. var increment = arc.angle.radians() / numberOfSegments;
  2552. if (arc.orientation === 0 /* CW */)
  2553. increment *= -1;
  2554. var currentAngle = arc.startAngle.radians() + increment;
  2555. for (var i = 0; i < numberOfSegments; i++) {
  2556. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2557. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2558. this.addLineTo(x, y);
  2559. currentAngle += increment;
  2560. }
  2561. return this;
  2562. };
  2563. Path2.prototype.close = function () {
  2564. this.closed = true;
  2565. return this;
  2566. };
  2567. Path2.prototype.length = function () {
  2568. var result = this._length;
  2569. if (!this.closed) {
  2570. var lastPoint = this._points[this._points.length - 1];
  2571. var firstPoint = this._points[0];
  2572. result += (firstPoint.subtract(lastPoint).length());
  2573. }
  2574. return result;
  2575. };
  2576. Path2.prototype.getPoints = function () {
  2577. return this._points;
  2578. };
  2579. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2580. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2581. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2582. return Vector2.Zero();
  2583. }
  2584. var lengthPosition = normalizedLengthPosition * this.length();
  2585. var previousOffset = 0;
  2586. for (var i = 0; i < this._points.length; i++) {
  2587. var j = (i + 1) % this._points.length;
  2588. var a = this._points[i];
  2589. var b = this._points[j];
  2590. var bToA = b.subtract(a);
  2591. var nextOffset = (bToA.length() + previousOffset);
  2592. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2593. var dir = bToA.normalize();
  2594. var localOffset = lengthPosition - previousOffset;
  2595. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2596. }
  2597. previousOffset = nextOffset;
  2598. }
  2599. BABYLON.Tools.Error("internal error");
  2600. return Vector2.Zero();
  2601. };
  2602. Path2.StartingAt = function (x, y) {
  2603. return new Path2(x, y);
  2604. };
  2605. return Path2;
  2606. })();
  2607. BABYLON.Path2 = Path2;
  2608. var Path3D = (function () {
  2609. function Path3D(path, firstNormal) {
  2610. this.path = path;
  2611. this._curve = new Array();
  2612. this._distances = new Array();
  2613. this._tangents = new Array();
  2614. this._normals = new Array();
  2615. this._binormals = new Array();
  2616. for (var p = 0; p < path.length; p++) {
  2617. this._curve[p] = path[p].clone(); // hard copy
  2618. }
  2619. this._compute(firstNormal);
  2620. }
  2621. Path3D.prototype.getCurve = function () {
  2622. return this._curve;
  2623. };
  2624. Path3D.prototype.getTangents = function () {
  2625. return this._tangents;
  2626. };
  2627. Path3D.prototype.getNormals = function () {
  2628. return this._normals;
  2629. };
  2630. Path3D.prototype.getBinormals = function () {
  2631. return this._binormals;
  2632. };
  2633. Path3D.prototype.getDistances = function () {
  2634. return this._distances;
  2635. };
  2636. Path3D.prototype.update = function (path, firstNormal) {
  2637. for (var p = 0; p < path.length; p++) {
  2638. this._curve[p].x = path[p].x;
  2639. this._curve[p].y = path[p].y;
  2640. this._curve[p].z = path[p].z;
  2641. }
  2642. this._compute(firstNormal);
  2643. return this;
  2644. };
  2645. // private function compute() : computes tangents, normals and binormals
  2646. Path3D.prototype._compute = function (firstNormal) {
  2647. var l = this._curve.length;
  2648. // first and last tangents
  2649. this._tangents[0] = this._getFirstNonNullVector(0);
  2650. this._tangents[0].normalize();
  2651. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2652. this._tangents[l - 1].normalize();
  2653. // normals and binormals at first point : arbitrary vector with _normalVector()
  2654. var tg0 = this._tangents[0];
  2655. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2656. this._normals[0] = pp0;
  2657. this._normals[0].normalize();
  2658. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2659. this._binormals[0].normalize();
  2660. this._distances[0] = 0;
  2661. // normals and binormals : next points
  2662. var prev; // previous vector (segment)
  2663. var cur; // current vector (segment)
  2664. var curTang; // current tangent
  2665. var prevNorm; // previous normal
  2666. var prevBinor; // previous binormal
  2667. for (var i = 1; i < l; i++) {
  2668. // tangents
  2669. prev = this._getLastNonNullVector(i);
  2670. if (i < l - 1) {
  2671. cur = this._getFirstNonNullVector(i);
  2672. this._tangents[i] = prev.add(cur);
  2673. this._tangents[i].normalize();
  2674. }
  2675. this._distances[i] = this._distances[i - 1] + prev.length();
  2676. // normals and binormals
  2677. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2678. curTang = this._tangents[i];
  2679. prevNorm = this._normals[i - 1];
  2680. prevBinor = this._binormals[i - 1];
  2681. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2682. this._normals[i].normalize();
  2683. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2684. this._binormals[i].normalize();
  2685. }
  2686. };
  2687. // private function getFirstNonNullVector(index)
  2688. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2689. Path3D.prototype._getFirstNonNullVector = function (index) {
  2690. var i = 1;
  2691. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2692. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2693. i++;
  2694. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2695. }
  2696. return nNVector;
  2697. };
  2698. // private function getLastNonNullVector(index)
  2699. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2700. Path3D.prototype._getLastNonNullVector = function (index) {
  2701. var i = 1;
  2702. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2703. while (nLVector.length() == 0 && index > i + 1) {
  2704. i++;
  2705. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2706. }
  2707. return nLVector;
  2708. };
  2709. // private function normalVector(v0, vt, va) :
  2710. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2711. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2712. Path3D.prototype._normalVector = function (v0, vt, va) {
  2713. var normal0;
  2714. if (va === undefined || va === null) {
  2715. var point;
  2716. if (vt.x !== 1) {
  2717. point = new Vector3(1, 0, 0);
  2718. }
  2719. else if (vt.y !== 1) {
  2720. point = new Vector3(0, 1, 0);
  2721. }
  2722. else if (vt.z !== 1) {
  2723. point = new Vector3(0, 0, 1);
  2724. }
  2725. normal0 = Vector3.Cross(vt, point);
  2726. }
  2727. else {
  2728. normal0 = Vector3.Cross(vt, va);
  2729. Vector3.CrossToRef(normal0, vt, normal0);
  2730. }
  2731. normal0.normalize();
  2732. return normal0;
  2733. };
  2734. return Path3D;
  2735. })();
  2736. BABYLON.Path3D = Path3D;
  2737. var Curve3 = (function () {
  2738. function Curve3(points) {
  2739. this._length = 0;
  2740. this._points = points;
  2741. this._length = this._computeLength(points);
  2742. }
  2743. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2744. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2745. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2746. var bez = new Array();
  2747. var equation = function (t, val0, val1, val2) {
  2748. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2749. return res;
  2750. };
  2751. for (var i = 0; i <= nbPoints; i++) {
  2752. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2753. }
  2754. return new Curve3(bez);
  2755. };
  2756. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2757. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2758. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2759. var bez = new Array();
  2760. var equation = function (t, val0, val1, val2, val3) {
  2761. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2762. return res;
  2763. };
  2764. for (var i = 0; i <= nbPoints; i++) {
  2765. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2766. }
  2767. return new Curve3(bez);
  2768. };
  2769. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2770. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2771. var hermite = new Array();
  2772. var step = 1 / nbPoints;
  2773. for (var i = 0; i <= nbPoints; i++) {
  2774. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2775. }
  2776. return new Curve3(hermite);
  2777. };
  2778. Curve3.prototype.getPoints = function () {
  2779. return this._points;
  2780. };
  2781. Curve3.prototype.length = function () {
  2782. return this._length;
  2783. };
  2784. Curve3.prototype.continue = function (curve) {
  2785. var lastPoint = this._points[this._points.length - 1];
  2786. var continuedPoints = this._points.slice();
  2787. var curvePoints = curve.getPoints();
  2788. for (var i = 1; i < curvePoints.length; i++) {
  2789. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2790. }
  2791. var continuedCurve = new Curve3(continuedPoints);
  2792. return continuedCurve;
  2793. };
  2794. Curve3.prototype._computeLength = function (path) {
  2795. var l = 0;
  2796. for (var i = 1; i < path.length; i++) {
  2797. l += (path[i].subtract(path[i - 1])).length();
  2798. }
  2799. return l;
  2800. };
  2801. return Curve3;
  2802. })();
  2803. BABYLON.Curve3 = Curve3;
  2804. // Vertex formats
  2805. var PositionNormalVertex = (function () {
  2806. function PositionNormalVertex(position, normal) {
  2807. if (position === void 0) { position = Vector3.Zero(); }
  2808. if (normal === void 0) { normal = Vector3.Up(); }
  2809. this.position = position;
  2810. this.normal = normal;
  2811. }
  2812. PositionNormalVertex.prototype.clone = function () {
  2813. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2814. };
  2815. return PositionNormalVertex;
  2816. })();
  2817. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2818. var PositionNormalTextureVertex = (function () {
  2819. function PositionNormalTextureVertex(position, normal, uv) {
  2820. if (position === void 0) { position = Vector3.Zero(); }
  2821. if (normal === void 0) { normal = Vector3.Up(); }
  2822. if (uv === void 0) { uv = Vector2.Zero(); }
  2823. this.position = position;
  2824. this.normal = normal;
  2825. this.uv = uv;
  2826. }
  2827. PositionNormalTextureVertex.prototype.clone = function () {
  2828. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2829. };
  2830. return PositionNormalTextureVertex;
  2831. })();
  2832. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2833. // SIMD
  2834. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2835. var previousInvertToRef = Matrix.prototype.invertToRef;
  2836. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2837. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2838. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2839. var SIMDHelper = (function () {
  2840. function SIMDHelper() {
  2841. }
  2842. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2843. get: function () {
  2844. return SIMDHelper._isEnabled;
  2845. },
  2846. enumerable: true,
  2847. configurable: true
  2848. });
  2849. SIMDHelper.DisableSIMD = function () {
  2850. // Replace functions
  2851. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2852. Matrix.prototype.invertToRef = previousInvertToRef;
  2853. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2854. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2855. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2856. SIMDHelper._isEnabled = false;
  2857. };
  2858. SIMDHelper.EnableSIMD = function () {
  2859. if (window.SIMD === undefined) {
  2860. return;
  2861. }
  2862. // Replace functions
  2863. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2864. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2865. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2866. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2867. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2868. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2869. get: function () {
  2870. return this._data[0];
  2871. },
  2872. set: function (value) {
  2873. if (!this._data) {
  2874. this._data = new Float32Array(3);
  2875. }
  2876. this._data[0] = value;
  2877. }
  2878. });
  2879. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2880. get: function () {
  2881. return this._data[1];
  2882. },
  2883. set: function (value) {
  2884. this._data[1] = value;
  2885. }
  2886. });
  2887. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2888. get: function () {
  2889. return this._data[2];
  2890. },
  2891. set: function (value) {
  2892. this._data[2] = value;
  2893. }
  2894. });
  2895. SIMDHelper._isEnabled = true;
  2896. };
  2897. SIMDHelper._isEnabled = false;
  2898. return SIMDHelper;
  2899. })();
  2900. BABYLON.SIMDHelper = SIMDHelper;
  2901. if (window.SIMD !== undefined && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  2902. SIMDHelper.EnableSIMD();
  2903. }
  2904. })(BABYLON || (BABYLON = {}));
  2905. //# sourceMappingURL=babylon.math.js.map
  2906. var BABYLON;
  2907. (function (BABYLON) {
  2908. var Database = (function () {
  2909. function Database(urlToScene, callbackManifestChecked) {
  2910. // Handling various flavors of prefixed version of IndexedDB
  2911. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2912. this.callbackManifestChecked = callbackManifestChecked;
  2913. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  2914. this.db = null;
  2915. this.enableSceneOffline = false;
  2916. this.enableTexturesOffline = false;
  2917. this.manifestVersionFound = 0;
  2918. this.mustUpdateRessources = false;
  2919. this.hasReachedQuota = false;
  2920. this.checkManifestFile();
  2921. }
  2922. Database.prototype.checkManifestFile = function () {
  2923. var _this = this;
  2924. function noManifestFile() {
  2925. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  2926. that.enableSceneOffline = false;
  2927. that.enableTexturesOffline = false;
  2928. that.callbackManifestChecked(false);
  2929. }
  2930. var that = this;
  2931. var manifestURL = this.currentSceneUrl + ".manifest";
  2932. var xhr = new XMLHttpRequest();
  2933. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2934. xhr.open("GET", manifestURLTimeStamped, true);
  2935. xhr.addEventListener("load", function () {
  2936. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2937. try {
  2938. var manifestFile = JSON.parse(xhr.response);
  2939. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2940. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2941. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2942. _this.manifestVersionFound = manifestFile.version;
  2943. }
  2944. if (_this.callbackManifestChecked) {
  2945. _this.callbackManifestChecked(true);
  2946. }
  2947. }
  2948. catch (ex) {
  2949. noManifestFile();
  2950. }
  2951. }
  2952. else {
  2953. noManifestFile();
  2954. }
  2955. }, false);
  2956. xhr.addEventListener("error", function (event) {
  2957. noManifestFile();
  2958. }, false);
  2959. try {
  2960. xhr.send();
  2961. }
  2962. catch (ex) {
  2963. BABYLON.Tools.Error("Error on XHR send request.");
  2964. that.callbackManifestChecked(false);
  2965. }
  2966. };
  2967. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2968. var _this = this;
  2969. function handleError() {
  2970. that.isSupported = false;
  2971. if (errorCallback)
  2972. errorCallback();
  2973. }
  2974. var that = this;
  2975. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2976. // Your browser doesn't support IndexedDB
  2977. this.isSupported = false;
  2978. if (errorCallback)
  2979. errorCallback();
  2980. }
  2981. else {
  2982. // If the DB hasn't been opened or created yet
  2983. if (!this.db) {
  2984. this.hasReachedQuota = false;
  2985. this.isSupported = true;
  2986. var request = this.idbFactory.open("babylonjs", 1);
  2987. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  2988. request.onerror = function (event) {
  2989. handleError();
  2990. };
  2991. // executes when a version change transaction cannot complete due to other active transactions
  2992. request.onblocked = function (event) {
  2993. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  2994. handleError();
  2995. };
  2996. // DB has been opened successfully
  2997. request.onsuccess = function (event) {
  2998. _this.db = request.result;
  2999. successCallback();
  3000. };
  3001. // Initialization of the DB. Creating Scenes & Textures stores
  3002. request.onupgradeneeded = function (event) {
  3003. _this.db = (event.target).result;
  3004. try {
  3005. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3006. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3007. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3008. }
  3009. catch (ex) {
  3010. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3011. handleError();
  3012. }
  3013. };
  3014. }
  3015. else {
  3016. if (successCallback)
  3017. successCallback();
  3018. }
  3019. }
  3020. };
  3021. Database.prototype.loadImageFromDB = function (url, image) {
  3022. var _this = this;
  3023. var completeURL = Database.ReturnFullUrlLocation(url);
  3024. var saveAndLoadImage = function () {
  3025. if (!_this.hasReachedQuota && _this.db !== null) {
  3026. // the texture is not yet in the DB, let's try to save it
  3027. _this._saveImageIntoDBAsync(completeURL, image);
  3028. }
  3029. else {
  3030. image.src = url;
  3031. }
  3032. };
  3033. if (!this.mustUpdateRessources) {
  3034. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3035. }
  3036. else {
  3037. saveAndLoadImage();
  3038. }
  3039. };
  3040. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3041. if (this.isSupported && this.db !== null) {
  3042. var texture;
  3043. var transaction = this.db.transaction(["textures"]);
  3044. transaction.onabort = function (event) {
  3045. image.src = url;
  3046. };
  3047. transaction.oncomplete = function (event) {
  3048. var blobTextureURL;
  3049. if (texture) {
  3050. var URL = window.URL || window.webkitURL;
  3051. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3052. image.onerror = function () {
  3053. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3054. image.src = url;
  3055. };
  3056. image.src = blobTextureURL;
  3057. }
  3058. else {
  3059. notInDBCallback();
  3060. }
  3061. };
  3062. var getRequest = transaction.objectStore("textures").get(url);
  3063. getRequest.onsuccess = function (event) {
  3064. texture = (event.target).result;
  3065. };
  3066. getRequest.onerror = function (event) {
  3067. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3068. image.src = url;
  3069. };
  3070. }
  3071. else {
  3072. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3073. image.src = url;
  3074. }
  3075. };
  3076. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3077. var _this = this;
  3078. if (this.isSupported) {
  3079. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3080. var generateBlobUrl = function () {
  3081. var blobTextureURL;
  3082. if (blob) {
  3083. var URL = window.URL || window.webkitURL;
  3084. try {
  3085. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3086. }
  3087. catch (ex) {
  3088. blobTextureURL = URL.createObjectURL(blob);
  3089. }
  3090. }
  3091. image.src = blobTextureURL;
  3092. };
  3093. if (Database.isUASupportingBlobStorage) {
  3094. var xhr = new XMLHttpRequest(), blob;
  3095. xhr.open("GET", url, true);
  3096. xhr.responseType = "blob";
  3097. xhr.addEventListener("load", function () {
  3098. if (xhr.status === 200) {
  3099. // Blob as response (XHR2)
  3100. blob = xhr.response;
  3101. var transaction = _this.db.transaction(["textures"], "readwrite");
  3102. // the transaction could abort because of a QuotaExceededError error
  3103. transaction.onabort = function (event) {
  3104. try {
  3105. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3106. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3107. this.hasReachedQuota = true;
  3108. }
  3109. }
  3110. catch (ex) {
  3111. }
  3112. generateBlobUrl();
  3113. };
  3114. transaction.oncomplete = function (event) {
  3115. generateBlobUrl();
  3116. };
  3117. var newTexture = { textureUrl: url, data: blob };
  3118. try {
  3119. // Put the blob into the dabase
  3120. var addRequest = transaction.objectStore("textures").put(newTexture);
  3121. addRequest.onsuccess = function (event) {
  3122. };
  3123. addRequest.onerror = function (event) {
  3124. generateBlobUrl();
  3125. };
  3126. }
  3127. catch (ex) {
  3128. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3129. if (ex.code === 25) {
  3130. Database.isUASupportingBlobStorage = false;
  3131. }
  3132. image.src = url;
  3133. }
  3134. }
  3135. else {
  3136. image.src = url;
  3137. }
  3138. }, false);
  3139. xhr.addEventListener("error", function (event) {
  3140. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3141. image.src = url;
  3142. }, false);
  3143. xhr.send();
  3144. }
  3145. else {
  3146. image.src = url;
  3147. }
  3148. }
  3149. else {
  3150. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3151. image.src = url;
  3152. }
  3153. };
  3154. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3155. var _this = this;
  3156. var updateVersion = function (event) {
  3157. // the version is not yet in the DB or we need to update it
  3158. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3159. };
  3160. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3161. };
  3162. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3163. var _this = this;
  3164. if (this.isSupported) {
  3165. var version;
  3166. try {
  3167. var transaction = this.db.transaction(["versions"]);
  3168. transaction.oncomplete = function (event) {
  3169. if (version) {
  3170. // If the version in the JSON file is > than the version in DB
  3171. if (_this.manifestVersionFound > version.data) {
  3172. _this.mustUpdateRessources = true;
  3173. updateInDBCallback();
  3174. }
  3175. else {
  3176. callback(version.data);
  3177. }
  3178. }
  3179. else {
  3180. _this.mustUpdateRessources = true;
  3181. updateInDBCallback();
  3182. }
  3183. };
  3184. transaction.onabort = function (event) {
  3185. callback(-1);
  3186. };
  3187. var getRequest = transaction.objectStore("versions").get(url);
  3188. getRequest.onsuccess = function (event) {
  3189. version = (event.target).result;
  3190. };
  3191. getRequest.onerror = function (event) {
  3192. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3193. callback(-1);
  3194. };
  3195. }
  3196. catch (ex) {
  3197. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3198. callback(-1);
  3199. }
  3200. }
  3201. else {
  3202. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3203. callback(-1);
  3204. }
  3205. };
  3206. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3207. var _this = this;
  3208. if (this.isSupported && !this.hasReachedQuota) {
  3209. try {
  3210. // Open a transaction to the database
  3211. var transaction = this.db.transaction(["versions"], "readwrite");
  3212. // the transaction could abort because of a QuotaExceededError error
  3213. transaction.onabort = function (event) {
  3214. try {
  3215. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3216. _this.hasReachedQuota = true;
  3217. }
  3218. }
  3219. catch (ex) {
  3220. }
  3221. callback(-1);
  3222. };
  3223. transaction.oncomplete = function (event) {
  3224. callback(_this.manifestVersionFound);
  3225. };
  3226. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3227. // Put the scene into the database
  3228. var addRequest = transaction.objectStore("versions").put(newVersion);
  3229. addRequest.onsuccess = function (event) {
  3230. };
  3231. addRequest.onerror = function (event) {
  3232. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3233. };
  3234. }
  3235. catch (ex) {
  3236. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3237. callback(-1);
  3238. }
  3239. }
  3240. else {
  3241. callback(-1);
  3242. }
  3243. };
  3244. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3245. var _this = this;
  3246. var completeUrl = Database.ReturnFullUrlLocation(url);
  3247. var saveAndLoadFile = function (event) {
  3248. // the scene is not yet in the DB, let's try to save it
  3249. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3250. };
  3251. this._checkVersionFromDB(completeUrl, function (version) {
  3252. if (version !== -1) {
  3253. if (!_this.mustUpdateRessources) {
  3254. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3255. }
  3256. else {
  3257. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3258. }
  3259. }
  3260. else {
  3261. errorCallback();
  3262. }
  3263. });
  3264. };
  3265. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3266. if (this.isSupported) {
  3267. var targetStore;
  3268. if (url.indexOf(".babylon") !== -1) {
  3269. targetStore = "scenes";
  3270. }
  3271. else {
  3272. targetStore = "textures";
  3273. }
  3274. var file;
  3275. var transaction = this.db.transaction([targetStore]);
  3276. transaction.oncomplete = function (event) {
  3277. if (file) {
  3278. callback(file.data);
  3279. }
  3280. else {
  3281. notInDBCallback();
  3282. }
  3283. };
  3284. transaction.onabort = function (event) {
  3285. notInDBCallback();
  3286. };
  3287. var getRequest = transaction.objectStore(targetStore).get(url);
  3288. getRequest.onsuccess = function (event) {
  3289. file = (event.target).result;
  3290. };
  3291. getRequest.onerror = function (event) {
  3292. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3293. notInDBCallback();
  3294. };
  3295. }
  3296. else {
  3297. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3298. callback();
  3299. }
  3300. };
  3301. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3302. var _this = this;
  3303. if (this.isSupported) {
  3304. var targetStore;
  3305. if (url.indexOf(".babylon") !== -1) {
  3306. targetStore = "scenes";
  3307. }
  3308. else {
  3309. targetStore = "textures";
  3310. }
  3311. // Create XHR
  3312. var xhr = new XMLHttpRequest(), fileData;
  3313. xhr.open("GET", url, true);
  3314. if (useArrayBuffer) {
  3315. xhr.responseType = "arraybuffer";
  3316. }
  3317. xhr.onprogress = progressCallback;
  3318. xhr.addEventListener("load", function () {
  3319. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3320. // Blob as response (XHR2)
  3321. //fileData = xhr.responseText;
  3322. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3323. if (!_this.hasReachedQuota) {
  3324. // Open a transaction to the database
  3325. var transaction = _this.db.transaction([targetStore], "readwrite");
  3326. // the transaction could abort because of a QuotaExceededError error
  3327. transaction.onabort = function (event) {
  3328. try {
  3329. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3330. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3331. this.hasReachedQuota = true;
  3332. }
  3333. }
  3334. catch (ex) {
  3335. }
  3336. callback(fileData);
  3337. };
  3338. transaction.oncomplete = function (event) {
  3339. callback(fileData);
  3340. };
  3341. var newFile;
  3342. if (targetStore === "scenes") {
  3343. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3344. }
  3345. else {
  3346. newFile = { textureUrl: url, data: fileData };
  3347. }
  3348. try {
  3349. // Put the scene into the database
  3350. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3351. addRequest.onsuccess = function (event) {
  3352. };
  3353. addRequest.onerror = function (event) {
  3354. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3355. };
  3356. }
  3357. catch (ex) {
  3358. callback(fileData);
  3359. }
  3360. }
  3361. else {
  3362. callback(fileData);
  3363. }
  3364. }
  3365. else {
  3366. callback();
  3367. }
  3368. }, false);
  3369. xhr.addEventListener("error", function (event) {
  3370. BABYLON.Tools.Error("error on XHR request.");
  3371. callback();
  3372. }, false);
  3373. xhr.send();
  3374. }
  3375. else {
  3376. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3377. callback();
  3378. }
  3379. };
  3380. Database.isUASupportingBlobStorage = true;
  3381. Database.parseURL = function (url) {
  3382. var a = document.createElement('a');
  3383. a.href = url;
  3384. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3385. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3386. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3387. return absLocation;
  3388. };
  3389. Database.ReturnFullUrlLocation = function (url) {
  3390. if (url.indexOf("http:/") === -1) {
  3391. return (BABYLON.Database.parseURL(window.location.href) + url);
  3392. }
  3393. else {
  3394. return url;
  3395. }
  3396. };
  3397. return Database;
  3398. })();
  3399. BABYLON.Database = Database;
  3400. })(BABYLON || (BABYLON = {}));
  3401. //# sourceMappingURL=babylon.database.js.map
  3402. var BABYLON;
  3403. (function (BABYLON) {
  3404. var Internals;
  3405. (function (Internals) {
  3406. /*
  3407. * Based on jsTGALoader - Javascript loader for TGA file
  3408. * By Vincent Thibault
  3409. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3410. */
  3411. var TGATools = (function () {
  3412. function TGATools() {
  3413. }
  3414. TGATools.GetTGAHeader = function (data) {
  3415. var offset = 0;
  3416. var header = {
  3417. id_length: data[offset++],
  3418. colormap_type: data[offset++],
  3419. image_type: data[offset++],
  3420. colormap_index: data[offset++] | data[offset++] << 8,
  3421. colormap_length: data[offset++] | data[offset++] << 8,
  3422. colormap_size: data[offset++],
  3423. origin: [
  3424. data[offset++] | data[offset++] << 8,
  3425. data[offset++] | data[offset++] << 8
  3426. ],
  3427. width: data[offset++] | data[offset++] << 8,
  3428. height: data[offset++] | data[offset++] << 8,
  3429. pixel_size: data[offset++],
  3430. flags: data[offset++]
  3431. };
  3432. return header;
  3433. };
  3434. TGATools.UploadContent = function (gl, data) {
  3435. // Not enough data to contain header ?
  3436. if (data.length < 19) {
  3437. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3438. return;
  3439. }
  3440. // Read Header
  3441. var offset = 18;
  3442. var header = TGATools.GetTGAHeader(data);
  3443. // Assume it's a valid Targa file.
  3444. if (header.id_length + offset > data.length) {
  3445. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3446. return;
  3447. }
  3448. // Skip not needed data
  3449. offset += header.id_length;
  3450. var use_rle = false;
  3451. var use_pal = false;
  3452. var use_rgb = false;
  3453. var use_grey = false;
  3454. switch (header.image_type) {
  3455. case TGATools._TYPE_RLE_INDEXED:
  3456. use_rle = true;
  3457. case TGATools._TYPE_INDEXED:
  3458. use_pal = true;
  3459. break;
  3460. case TGATools._TYPE_RLE_RGB:
  3461. use_rle = true;
  3462. case TGATools._TYPE_RGB:
  3463. use_rgb = true;
  3464. break;
  3465. case TGATools._TYPE_RLE_GREY:
  3466. use_rle = true;
  3467. case TGATools._TYPE_GREY:
  3468. use_grey = true;
  3469. break;
  3470. }
  3471. var pixel_data;
  3472. var numAlphaBits = header.flags & 0xf;
  3473. var pixel_size = header.pixel_size >> 3;
  3474. var pixel_total = header.width * header.height * pixel_size;
  3475. // Read palettes
  3476. var palettes;
  3477. if (use_pal) {
  3478. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3479. }
  3480. // Read LRE
  3481. if (use_rle) {
  3482. pixel_data = new Uint8Array(pixel_total);
  3483. var c, count, i;
  3484. var localOffset = 0;
  3485. var pixels = new Uint8Array(pixel_size);
  3486. while (offset < pixel_total && localOffset < pixel_total) {
  3487. c = data[offset++];
  3488. count = (c & 0x7f) + 1;
  3489. // RLE pixels
  3490. if (c & 0x80) {
  3491. for (i = 0; i < pixel_size; ++i) {
  3492. pixels[i] = data[offset++];
  3493. }
  3494. for (i = 0; i < count; ++i) {
  3495. pixel_data.set(pixels, localOffset + i * pixel_size);
  3496. }
  3497. localOffset += pixel_size * count;
  3498. }
  3499. else {
  3500. count *= pixel_size;
  3501. for (i = 0; i < count; ++i) {
  3502. pixel_data[localOffset + i] = data[offset++];
  3503. }
  3504. localOffset += count;
  3505. }
  3506. }
  3507. }
  3508. else {
  3509. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3510. }
  3511. // Load to texture
  3512. var x_start, y_start, x_step, y_step, y_end, x_end;
  3513. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3514. default:
  3515. case TGATools._ORIGIN_UL:
  3516. x_start = 0;
  3517. x_step = 1;
  3518. x_end = header.width;
  3519. y_start = 0;
  3520. y_step = 1;
  3521. y_end = header.height;
  3522. break;
  3523. case TGATools._ORIGIN_BL:
  3524. x_start = 0;
  3525. x_step = 1;
  3526. x_end = header.width;
  3527. y_start = header.height - 1;
  3528. y_step = -1;
  3529. y_end = -1;
  3530. break;
  3531. case TGATools._ORIGIN_UR:
  3532. x_start = header.width - 1;
  3533. x_step = -1;
  3534. x_end = -1;
  3535. y_start = 0;
  3536. y_step = 1;
  3537. y_end = header.height;
  3538. break;
  3539. case TGATools._ORIGIN_BR:
  3540. x_start = header.width - 1;
  3541. x_step = -1;
  3542. x_end = -1;
  3543. y_start = header.height - 1;
  3544. y_step = -1;
  3545. y_end = -1;
  3546. break;
  3547. }
  3548. // Load the specify method
  3549. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3550. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3551. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3552. };
  3553. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3554. var image = pixel_data, colormap = palettes;
  3555. var width = header.width, height = header.height;
  3556. var color, i = 0, x, y;
  3557. var imageData = new Uint8Array(width * height * 4);
  3558. for (y = y_start; y !== y_end; y += y_step) {
  3559. for (x = x_start; x !== x_end; x += x_step, i++) {
  3560. color = image[i];
  3561. imageData[(x + width * y) * 4 + 3] = 255;
  3562. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3563. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3564. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3565. }
  3566. }
  3567. return imageData;
  3568. };
  3569. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3570. var image = pixel_data;
  3571. var width = header.width, height = header.height;
  3572. var color, i = 0, x, y;
  3573. var imageData = new Uint8Array(width * height * 4);
  3574. for (y = y_start; y !== y_end; y += y_step) {
  3575. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3576. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3577. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3578. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3579. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3580. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3581. }
  3582. }
  3583. return imageData;
  3584. };
  3585. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3586. var image = pixel_data;
  3587. var width = header.width, height = header.height;
  3588. var i = 0, x, y;
  3589. var imageData = new Uint8Array(width * height * 4);
  3590. for (y = y_start; y !== y_end; y += y_step) {
  3591. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3592. imageData[(x + width * y) * 4 + 3] = 255;
  3593. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3594. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3595. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3596. }
  3597. }
  3598. return imageData;
  3599. };
  3600. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3601. var image = pixel_data;
  3602. var width = header.width, height = header.height;
  3603. var i = 0, x, y;
  3604. var imageData = new Uint8Array(width * height * 4);
  3605. for (y = y_start; y !== y_end; y += y_step) {
  3606. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3607. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3608. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3609. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3610. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3611. }
  3612. }
  3613. return imageData;
  3614. };
  3615. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3616. var image = pixel_data;
  3617. var width = header.width, height = header.height;
  3618. var color, i = 0, x, y;
  3619. var imageData = new Uint8Array(width * height * 4);
  3620. for (y = y_start; y !== y_end; y += y_step) {
  3621. for (x = x_start; x !== x_end; x += x_step, i++) {
  3622. color = image[i];
  3623. imageData[(x + width * y) * 4 + 0] = color;
  3624. imageData[(x + width * y) * 4 + 1] = color;
  3625. imageData[(x + width * y) * 4 + 2] = color;
  3626. imageData[(x + width * y) * 4 + 3] = 255;
  3627. }
  3628. }
  3629. return imageData;
  3630. };
  3631. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3632. var image = pixel_data;
  3633. var width = header.width, height = header.height;
  3634. var i = 0, x, y;
  3635. var imageData = new Uint8Array(width * height * 4);
  3636. for (y = y_start; y !== y_end; y += y_step) {
  3637. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3638. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3639. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3640. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3641. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3642. }
  3643. }
  3644. return imageData;
  3645. };
  3646. TGATools._TYPE_NO_DATA = 0;
  3647. TGATools._TYPE_INDEXED = 1;
  3648. TGATools._TYPE_RGB = 2;
  3649. TGATools._TYPE_GREY = 3;
  3650. TGATools._TYPE_RLE_INDEXED = 9;
  3651. TGATools._TYPE_RLE_RGB = 10;
  3652. TGATools._TYPE_RLE_GREY = 11;
  3653. TGATools._ORIGIN_MASK = 0x30;
  3654. TGATools._ORIGIN_SHIFT = 0x04;
  3655. TGATools._ORIGIN_BL = 0x00;
  3656. TGATools._ORIGIN_BR = 0x01;
  3657. TGATools._ORIGIN_UL = 0x02;
  3658. TGATools._ORIGIN_UR = 0x03;
  3659. return TGATools;
  3660. })();
  3661. Internals.TGATools = TGATools;
  3662. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3663. })(BABYLON || (BABYLON = {}));
  3664. //# sourceMappingURL=babylon.tools.tga.js.map
  3665. var BABYLON;
  3666. (function (BABYLON) {
  3667. var Internals;
  3668. (function (Internals) {
  3669. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3670. // All values and structures referenced from:
  3671. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3672. var DDS_MAGIC = 0x20534444;
  3673. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  3674. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3675. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  3676. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3677. function FourCCToInt32(value) {
  3678. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  3679. }
  3680. function Int32ToFourCC(value) {
  3681. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3682. }
  3683. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3684. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3685. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3686. var headerLengthInt = 31; // The header length in 32 bit ints
  3687. // Offsets into the header array
  3688. var off_magic = 0;
  3689. var off_size = 1;
  3690. var off_flags = 2;
  3691. var off_height = 3;
  3692. var off_width = 4;
  3693. var off_mipmapCount = 7;
  3694. var off_pfFlags = 20;
  3695. var off_pfFourCC = 21;
  3696. var off_RGBbpp = 22;
  3697. var off_RMask = 23;
  3698. var off_GMask = 24;
  3699. var off_BMask = 25;
  3700. var off_AMask = 26;
  3701. var off_caps1 = 27;
  3702. var off_caps2 = 28;
  3703. ;
  3704. var DDSTools = (function () {
  3705. function DDSTools() {
  3706. }
  3707. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3708. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3709. var mipmapCount = 1;
  3710. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3711. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3712. }
  3713. return {
  3714. width: header[off_width],
  3715. height: header[off_height],
  3716. mipmapCount: mipmapCount,
  3717. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3718. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3719. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3720. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3721. };
  3722. };
  3723. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3724. var byteArray = new Uint8Array(dataLength);
  3725. var srcData = new Uint8Array(arrayBuffer);
  3726. var index = 0;
  3727. for (var y = height - 1; y >= 0; y--) {
  3728. for (var x = 0; x < width; x++) {
  3729. var srcPos = dataOffset + (x + y * width) * 4;
  3730. byteArray[index + 2] = srcData[srcPos];
  3731. byteArray[index + 1] = srcData[srcPos + 1];
  3732. byteArray[index] = srcData[srcPos + 2];
  3733. byteArray[index + 3] = srcData[srcPos + 3];
  3734. index += 4;
  3735. }
  3736. }
  3737. return byteArray;
  3738. };
  3739. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3740. var byteArray = new Uint8Array(dataLength);
  3741. var srcData = new Uint8Array(arrayBuffer);
  3742. var index = 0;
  3743. for (var y = height - 1; y >= 0; y--) {
  3744. for (var x = 0; x < width; x++) {
  3745. var srcPos = dataOffset + (x + y * width) * 3;
  3746. byteArray[index + 2] = srcData[srcPos];
  3747. byteArray[index + 1] = srcData[srcPos + 1];
  3748. byteArray[index] = srcData[srcPos + 2];
  3749. index += 3;
  3750. }
  3751. }
  3752. return byteArray;
  3753. };
  3754. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3755. var byteArray = new Uint8Array(dataLength);
  3756. var srcData = new Uint8Array(arrayBuffer);
  3757. var index = 0;
  3758. for (var y = height - 1; y >= 0; y--) {
  3759. for (var x = 0; x < width; x++) {
  3760. var srcPos = dataOffset + (x + y * width);
  3761. byteArray[index] = srcData[srcPos];
  3762. index++;
  3763. }
  3764. }
  3765. return byteArray;
  3766. };
  3767. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3768. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3769. if (header[off_magic] != DDS_MAGIC) {
  3770. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3771. return;
  3772. }
  3773. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3774. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3775. return;
  3776. }
  3777. if (info.isFourCC) {
  3778. fourCC = header[off_pfFourCC];
  3779. switch (fourCC) {
  3780. case FOURCC_DXT1:
  3781. blockBytes = 8;
  3782. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3783. break;
  3784. case FOURCC_DXT3:
  3785. blockBytes = 16;
  3786. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3787. break;
  3788. case FOURCC_DXT5:
  3789. blockBytes = 16;
  3790. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3791. break;
  3792. default:
  3793. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3794. return;
  3795. }
  3796. }
  3797. mipmapCount = 1;
  3798. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3799. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3800. }
  3801. var bpp = header[off_RGBbpp];
  3802. for (var face = 0; face < faces; face++) {
  3803. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3804. width = header[off_width];
  3805. height = header[off_height];
  3806. dataOffset = header[off_size] + 4;
  3807. for (i = 0; i < mipmapCount; ++i) {
  3808. if (info.isRGB) {
  3809. if (bpp == 24) {
  3810. dataLength = width * height * 3;
  3811. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3812. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3813. }
  3814. else {
  3815. dataLength = width * height * 4;
  3816. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3817. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3818. }
  3819. }
  3820. else if (info.isLuminance) {
  3821. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3822. var unpaddedRowSize = width;
  3823. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3824. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3825. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3826. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3827. }
  3828. else {
  3829. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3830. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3831. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3832. }
  3833. dataOffset += dataLength;
  3834. width *= 0.5;
  3835. height *= 0.5;
  3836. width = Math.max(1.0, width);
  3837. height = Math.max(1.0, height);
  3838. }
  3839. }
  3840. };
  3841. return DDSTools;
  3842. })();
  3843. Internals.DDSTools = DDSTools;
  3844. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3845. })(BABYLON || (BABYLON = {}));
  3846. //# sourceMappingURL=babylon.tools.dds.js.map
  3847. var BABYLON;
  3848. (function (BABYLON) {
  3849. var SmartArray = (function () {
  3850. function SmartArray(capacity) {
  3851. this.length = 0;
  3852. this._duplicateId = 0;
  3853. this.data = new Array(capacity);
  3854. this._id = SmartArray._GlobalId++;
  3855. }
  3856. SmartArray.prototype.push = function (value) {
  3857. this.data[this.length++] = value;
  3858. if (this.length > this.data.length) {
  3859. this.data.length *= 2;
  3860. }
  3861. if (!value.__smartArrayFlags) {
  3862. value.__smartArrayFlags = {};
  3863. }
  3864. value.__smartArrayFlags[this._id] = this._duplicateId;
  3865. };
  3866. SmartArray.prototype.pushNoDuplicate = function (value) {
  3867. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3868. return;
  3869. }
  3870. this.push(value);
  3871. };
  3872. SmartArray.prototype.sort = function (compareFn) {
  3873. this.data.sort(compareFn);
  3874. };
  3875. SmartArray.prototype.reset = function () {
  3876. this.length = 0;
  3877. this._duplicateId++;
  3878. };
  3879. SmartArray.prototype.concat = function (array) {
  3880. if (array.length === 0) {
  3881. return;
  3882. }
  3883. if (this.length + array.length > this.data.length) {
  3884. this.data.length = (this.length + array.length) * 2;
  3885. }
  3886. for (var index = 0; index < array.length; index++) {
  3887. this.data[this.length++] = (array.data || array)[index];
  3888. }
  3889. };
  3890. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3891. if (array.length === 0) {
  3892. return;
  3893. }
  3894. if (this.length + array.length > this.data.length) {
  3895. this.data.length = (this.length + array.length) * 2;
  3896. }
  3897. for (var index = 0; index < array.length; index++) {
  3898. var item = (array.data || array)[index];
  3899. this.pushNoDuplicate(item);
  3900. }
  3901. };
  3902. SmartArray.prototype.indexOf = function (value) {
  3903. var position = this.data.indexOf(value);
  3904. if (position >= this.length) {
  3905. return -1;
  3906. }
  3907. return position;
  3908. };
  3909. // Statics
  3910. SmartArray._GlobalId = 0;
  3911. return SmartArray;
  3912. })();
  3913. BABYLON.SmartArray = SmartArray;
  3914. })(BABYLON || (BABYLON = {}));
  3915. //# sourceMappingURL=babylon.smartArray.js.map
  3916. var BABYLON;
  3917. (function (BABYLON) {
  3918. var SmartCollection = (function () {
  3919. function SmartCollection(capacity) {
  3920. if (capacity === void 0) { capacity = 10; }
  3921. this.count = 0;
  3922. this._initialCapacity = capacity;
  3923. this.items = {};
  3924. this._keys = new Array(this._initialCapacity);
  3925. }
  3926. SmartCollection.prototype.add = function (key, item) {
  3927. if (this.items[key] != undefined) {
  3928. return -1;
  3929. }
  3930. this.items[key] = item;
  3931. //literal keys are always strings, but we keep source type of key in _keys array
  3932. this._keys[this.count++] = key;
  3933. if (this.count > this._keys.length) {
  3934. this._keys.length *= 2;
  3935. }
  3936. return this.count;
  3937. };
  3938. SmartCollection.prototype.remove = function (key) {
  3939. if (this.items[key] == undefined) {
  3940. return -1;
  3941. }
  3942. return this.removeItemOfIndex(this.indexOf(key));
  3943. };
  3944. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3945. if (index < this.count && index > -1) {
  3946. delete this.items[this._keys[index]];
  3947. while (index < this.count) {
  3948. this._keys[index] = this._keys[index + 1];
  3949. index++;
  3950. }
  3951. }
  3952. else {
  3953. return -1;
  3954. }
  3955. return --this.count;
  3956. };
  3957. SmartCollection.prototype.indexOf = function (key) {
  3958. for (var i = 0; i !== this.count; i++) {
  3959. if (this._keys[i] === key) {
  3960. return i;
  3961. }
  3962. }
  3963. return -1;
  3964. };
  3965. SmartCollection.prototype.item = function (key) {
  3966. return this.items[key];
  3967. };
  3968. SmartCollection.prototype.getAllKeys = function () {
  3969. if (this.count > 0) {
  3970. var keys = new Array(this.count);
  3971. for (var i = 0; i < this.count; i++) {
  3972. keys[i] = this._keys[i];
  3973. }
  3974. return keys;
  3975. }
  3976. else {
  3977. return undefined;
  3978. }
  3979. };
  3980. SmartCollection.prototype.getKeyByIndex = function (index) {
  3981. if (index < this.count && index > -1) {
  3982. return this._keys[index];
  3983. }
  3984. else {
  3985. return undefined;
  3986. }
  3987. };
  3988. SmartCollection.prototype.getItemByIndex = function (index) {
  3989. if (index < this.count && index > -1) {
  3990. return this.items[this._keys[index]];
  3991. }
  3992. else {
  3993. return undefined;
  3994. }
  3995. };
  3996. SmartCollection.prototype.empty = function () {
  3997. if (this.count > 0) {
  3998. this.count = 0;
  3999. this.items = {};
  4000. this._keys = new Array(this._initialCapacity);
  4001. }
  4002. };
  4003. SmartCollection.prototype.forEach = function (block) {
  4004. var key;
  4005. for (key in this.items) {
  4006. if (this.items.hasOwnProperty(key)) {
  4007. block(this.items[key]);
  4008. }
  4009. }
  4010. };
  4011. return SmartCollection;
  4012. })();
  4013. BABYLON.SmartCollection = SmartCollection;
  4014. })(BABYLON || (BABYLON = {}));
  4015. //# sourceMappingURL=babylon.smartCollection.js.map
  4016. var BABYLON;
  4017. (function (BABYLON) {
  4018. // Screenshots
  4019. var screenshotCanvas;
  4020. var cloneValue = function (source, destinationObject) {
  4021. if (!source)
  4022. return null;
  4023. if (source instanceof BABYLON.Mesh) {
  4024. return null;
  4025. }
  4026. if (source instanceof BABYLON.SubMesh) {
  4027. return source.clone(destinationObject);
  4028. }
  4029. else if (source.clone) {
  4030. return source.clone();
  4031. }
  4032. return null;
  4033. };
  4034. var Tools = (function () {
  4035. function Tools() {
  4036. }
  4037. Tools.GetFilename = function (path) {
  4038. var index = path.lastIndexOf("/");
  4039. if (index < 0)
  4040. return path;
  4041. return path.substring(index + 1);
  4042. };
  4043. Tools.GetDOMTextContent = function (element) {
  4044. var result = "";
  4045. var child = element.firstChild;
  4046. while (child) {
  4047. if (child.nodeType === 3) {
  4048. result += child.textContent;
  4049. }
  4050. child = child.nextSibling;
  4051. }
  4052. return result;
  4053. };
  4054. Tools.ToDegrees = function (angle) {
  4055. return angle * 180 / Math.PI;
  4056. };
  4057. Tools.ToRadians = function (angle) {
  4058. return angle * Math.PI / 180;
  4059. };
  4060. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4061. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4062. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4063. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4064. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4065. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4066. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4067. }
  4068. return {
  4069. minimum: minimum,
  4070. maximum: maximum
  4071. };
  4072. };
  4073. Tools.ExtractMinAndMax = function (positions, start, count) {
  4074. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4075. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4076. for (var index = start; index < start + count; index++) {
  4077. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4078. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4079. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4080. }
  4081. return {
  4082. minimum: minimum,
  4083. maximum: maximum
  4084. };
  4085. };
  4086. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4087. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4088. return undefined;
  4089. return Array.isArray(obj) ? obj : [obj];
  4090. };
  4091. // Misc.
  4092. Tools.GetPointerPrefix = function () {
  4093. var eventPrefix = "pointer";
  4094. // Check if hand.js is referenced or if the browser natively supports pointer events
  4095. if (!navigator.pointerEnabled) {
  4096. eventPrefix = "mouse";
  4097. }
  4098. return eventPrefix;
  4099. };
  4100. Tools.QueueNewFrame = function (func) {
  4101. if (window.requestAnimationFrame)
  4102. window.requestAnimationFrame(func);
  4103. else if (window.msRequestAnimationFrame)
  4104. window.msRequestAnimationFrame(func);
  4105. else if (window.webkitRequestAnimationFrame)
  4106. window.webkitRequestAnimationFrame(func);
  4107. else if (window.mozRequestAnimationFrame)
  4108. window.mozRequestAnimationFrame(func);
  4109. else if (window.oRequestAnimationFrame)
  4110. window.oRequestAnimationFrame(func);
  4111. else {
  4112. window.setTimeout(func, 16);
  4113. }
  4114. };
  4115. Tools.RequestFullscreen = function (element) {
  4116. if (element.requestFullscreen)
  4117. element.requestFullscreen();
  4118. else if (element.msRequestFullscreen)
  4119. element.msRequestFullscreen();
  4120. else if (element.webkitRequestFullscreen)
  4121. element.webkitRequestFullscreen();
  4122. else if (element.mozRequestFullScreen)
  4123. element.mozRequestFullScreen();
  4124. };
  4125. Tools.ExitFullscreen = function () {
  4126. if (document.exitFullscreen) {
  4127. document.exitFullscreen();
  4128. }
  4129. else if (document.mozCancelFullScreen) {
  4130. document.mozCancelFullScreen();
  4131. }
  4132. else if (document.webkitCancelFullScreen) {
  4133. document.webkitCancelFullScreen();
  4134. }
  4135. else if (document.msCancelFullScreen) {
  4136. document.msCancelFullScreen();
  4137. }
  4138. };
  4139. // External files
  4140. Tools.CleanUrl = function (url) {
  4141. url = url.replace(/#/mg, "%23");
  4142. return url;
  4143. };
  4144. Tools.LoadImage = function (url, onload, onerror, database) {
  4145. url = Tools.CleanUrl(url);
  4146. var img = new Image();
  4147. if (url.substr(0, 5) !== "data:")
  4148. img.crossOrigin = 'anonymous';
  4149. img.onload = function () {
  4150. onload(img);
  4151. };
  4152. img.onerror = function (err) {
  4153. onerror(img, err);
  4154. };
  4155. var noIndexedDB = function () {
  4156. img.src = url;
  4157. };
  4158. var loadFromIndexedDB = function () {
  4159. database.loadImageFromDB(url, img);
  4160. };
  4161. //ANY database to do!
  4162. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4163. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4164. }
  4165. else {
  4166. if (url.indexOf("file:") === -1) {
  4167. noIndexedDB();
  4168. }
  4169. else {
  4170. try {
  4171. var textureName = url.substring(5);
  4172. var blobURL;
  4173. try {
  4174. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4175. }
  4176. catch (ex) {
  4177. // Chrome doesn't support oneTimeOnly parameter
  4178. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4179. }
  4180. img.src = blobURL;
  4181. }
  4182. catch (e) {
  4183. Tools.Log("Error while trying to load texture: " + textureName);
  4184. img.src = null;
  4185. }
  4186. }
  4187. }
  4188. return img;
  4189. };
  4190. //ANY
  4191. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4192. url = Tools.CleanUrl(url);
  4193. var noIndexedDB = function () {
  4194. var request = new XMLHttpRequest();
  4195. var loadUrl = Tools.BaseUrl + url;
  4196. request.open('GET', loadUrl, true);
  4197. if (useArrayBuffer) {
  4198. request.responseType = "arraybuffer";
  4199. }
  4200. request.onprogress = progressCallBack;
  4201. request.onreadystatechange = function () {
  4202. if (request.readyState === 4) {
  4203. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4204. callback(!useArrayBuffer ? request.responseText : request.response);
  4205. }
  4206. else {
  4207. if (onError) {
  4208. onError();
  4209. }
  4210. else {
  4211. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4212. }
  4213. }
  4214. }
  4215. };
  4216. request.send(null);
  4217. };
  4218. var loadFromIndexedDB = function () {
  4219. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4220. };
  4221. if (url.indexOf("file:") !== -1) {
  4222. var fileName = url.substring(5);
  4223. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4224. }
  4225. else {
  4226. // Caching all files
  4227. if (database && database.enableSceneOffline) {
  4228. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4229. }
  4230. else {
  4231. noIndexedDB();
  4232. }
  4233. }
  4234. };
  4235. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4236. var reader = new FileReader();
  4237. reader.onload = function (e) {
  4238. //target doesn't have result from ts 1.3
  4239. callback(e.target['result']);
  4240. };
  4241. reader.onprogress = progressCallback;
  4242. reader.readAsDataURL(fileToLoad);
  4243. };
  4244. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4245. var reader = new FileReader();
  4246. reader.onerror = function (e) {
  4247. Tools.Log("Error while reading file: " + fileToLoad.name);
  4248. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4249. };
  4250. reader.onload = function (e) {
  4251. //target doesn't have result from ts 1.3
  4252. callback(e.target['result']);
  4253. };
  4254. reader.onprogress = progressCallBack;
  4255. if (!useArrayBuffer) {
  4256. // Asynchronous read
  4257. reader.readAsText(fileToLoad);
  4258. }
  4259. else {
  4260. reader.readAsArrayBuffer(fileToLoad);
  4261. }
  4262. };
  4263. // Misc.
  4264. Tools.Clamp = function (value, min, max) {
  4265. if (min === void 0) { min = 0; }
  4266. if (max === void 0) { max = 1; }
  4267. return Math.min(max, Math.max(min, value));
  4268. };
  4269. // Returns -1 when value is a negative number and
  4270. // +1 when value is a positive number.
  4271. Tools.Sign = function (value) {
  4272. value = +value; // convert to a number
  4273. if (value === 0 || isNaN(value))
  4274. return value;
  4275. return value > 0 ? 1 : -1;
  4276. };
  4277. Tools.Format = function (value, decimals) {
  4278. if (decimals === void 0) { decimals = 2; }
  4279. return value.toFixed(decimals);
  4280. };
  4281. Tools.CheckExtends = function (v, min, max) {
  4282. if (v.x < min.x)
  4283. min.x = v.x;
  4284. if (v.y < min.y)
  4285. min.y = v.y;
  4286. if (v.z < min.z)
  4287. min.z = v.z;
  4288. if (v.x > max.x)
  4289. max.x = v.x;
  4290. if (v.y > max.y)
  4291. max.y = v.y;
  4292. if (v.z > max.z)
  4293. max.z = v.z;
  4294. };
  4295. Tools.WithinEpsilon = function (a, b, epsilon) {
  4296. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4297. var num = a - b;
  4298. return -epsilon <= num && num <= epsilon;
  4299. };
  4300. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4301. for (var prop in source) {
  4302. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4303. continue;
  4304. }
  4305. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4306. continue;
  4307. }
  4308. var sourceValue = source[prop];
  4309. var typeOfSourceValue = typeof sourceValue;
  4310. if (typeOfSourceValue === "function") {
  4311. continue;
  4312. }
  4313. if (typeOfSourceValue === "object") {
  4314. if (sourceValue instanceof Array) {
  4315. destination[prop] = [];
  4316. if (sourceValue.length > 0) {
  4317. if (typeof sourceValue[0] == "object") {
  4318. for (var index = 0; index < sourceValue.length; index++) {
  4319. var clonedValue = cloneValue(sourceValue[index], destination);
  4320. if (destination[prop].indexOf(clonedValue) === -1) {
  4321. destination[prop].push(clonedValue);
  4322. }
  4323. }
  4324. }
  4325. else {
  4326. destination[prop] = sourceValue.slice(0);
  4327. }
  4328. }
  4329. }
  4330. else {
  4331. destination[prop] = cloneValue(sourceValue, destination);
  4332. }
  4333. }
  4334. else {
  4335. destination[prop] = sourceValue;
  4336. }
  4337. }
  4338. };
  4339. Tools.IsEmpty = function (obj) {
  4340. for (var i in obj) {
  4341. return false;
  4342. }
  4343. return true;
  4344. };
  4345. Tools.RegisterTopRootEvents = function (events) {
  4346. for (var index = 0; index < events.length; index++) {
  4347. var event = events[index];
  4348. window.addEventListener(event.name, event.handler, false);
  4349. try {
  4350. if (window.parent) {
  4351. window.parent.addEventListener(event.name, event.handler, false);
  4352. }
  4353. }
  4354. catch (e) {
  4355. }
  4356. }
  4357. };
  4358. Tools.UnregisterTopRootEvents = function (events) {
  4359. for (var index = 0; index < events.length; index++) {
  4360. var event = events[index];
  4361. window.removeEventListener(event.name, event.handler);
  4362. try {
  4363. if (window.parent) {
  4364. window.parent.removeEventListener(event.name, event.handler);
  4365. }
  4366. }
  4367. catch (e) {
  4368. }
  4369. }
  4370. };
  4371. Tools.DumpFramebuffer = function (width, height, engine) {
  4372. // Read the contents of the framebuffer
  4373. var numberOfChannelsByLine = width * 4;
  4374. var halfHeight = height / 2;
  4375. //Reading datas from WebGL
  4376. var data = engine.readPixels(0, 0, width, height);
  4377. for (var i = 0; i < halfHeight; i++) {
  4378. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4379. var currentCell = j + i * numberOfChannelsByLine;
  4380. var targetLine = height - i - 1;
  4381. var targetCell = j + targetLine * numberOfChannelsByLine;
  4382. var temp = data[currentCell];
  4383. data[currentCell] = data[targetCell];
  4384. data[targetCell] = temp;
  4385. }
  4386. }
  4387. // Create a 2D canvas to store the result
  4388. if (!screenshotCanvas) {
  4389. screenshotCanvas = document.createElement('canvas');
  4390. }
  4391. screenshotCanvas.width = width;
  4392. screenshotCanvas.height = height;
  4393. var context = screenshotCanvas.getContext('2d');
  4394. // Copy the pixels to a 2D canvas
  4395. var imageData = context.createImageData(width, height);
  4396. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4397. var castData = imageData.data;
  4398. castData.set(data);
  4399. context.putImageData(imageData, 0, 0);
  4400. var base64Image = screenshotCanvas.toDataURL();
  4401. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4402. if (("download" in document.createElement("a"))) {
  4403. var a = window.document.createElement("a");
  4404. a.href = base64Image;
  4405. var date = new Date();
  4406. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4407. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4408. window.document.body.appendChild(a);
  4409. a.addEventListener("click", function () {
  4410. a.parentElement.removeChild(a);
  4411. });
  4412. a.click();
  4413. }
  4414. else {
  4415. var newWindow = window.open("");
  4416. var img = newWindow.document.createElement("img");
  4417. img.src = base64Image;
  4418. newWindow.document.body.appendChild(img);
  4419. }
  4420. };
  4421. Tools.CreateScreenshot = function (engine, camera, size) {
  4422. var width;
  4423. var height;
  4424. var scene = camera.getScene();
  4425. var previousCamera = null;
  4426. if (scene.activeCamera !== camera) {
  4427. previousCamera = scene.activeCamera;
  4428. scene.activeCamera = camera;
  4429. }
  4430. //If a precision value is specified
  4431. if (size.precision) {
  4432. width = Math.round(engine.getRenderWidth() * size.precision);
  4433. height = Math.round(width / engine.getAspectRatio(camera));
  4434. size = { width: width, height: height };
  4435. }
  4436. else if (size.width && size.height) {
  4437. width = size.width;
  4438. height = size.height;
  4439. }
  4440. else if (size.width && !size.height) {
  4441. width = size.width;
  4442. height = Math.round(width / engine.getAspectRatio(camera));
  4443. size = { width: width, height: height };
  4444. }
  4445. else if (size.height && !size.width) {
  4446. height = size.height;
  4447. width = Math.round(height * engine.getAspectRatio(camera));
  4448. size = { width: width, height: height };
  4449. }
  4450. else if (!isNaN(size)) {
  4451. height = size;
  4452. width = size;
  4453. }
  4454. else {
  4455. Tools.Error("Invalid 'size' parameter !");
  4456. return;
  4457. }
  4458. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4459. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4460. texture.renderList = scene.meshes;
  4461. texture.onAfterRender = function () {
  4462. Tools.DumpFramebuffer(width, height, engine);
  4463. };
  4464. scene.incrementRenderId();
  4465. texture.render(true);
  4466. texture.dispose();
  4467. if (previousCamera) {
  4468. scene.activeCamera = previousCamera;
  4469. }
  4470. };
  4471. // XHR response validator for local file scenario
  4472. Tools.ValidateXHRData = function (xhr, dataType) {
  4473. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4474. if (dataType === void 0) { dataType = 7; }
  4475. try {
  4476. if (dataType & 1) {
  4477. if (xhr.responseText && xhr.responseText.length > 0) {
  4478. return true;
  4479. }
  4480. else if (dataType === 1) {
  4481. return false;
  4482. }
  4483. }
  4484. if (dataType & 2) {
  4485. // Check header width and height since there is no "TGA" magic number
  4486. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4487. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4488. return true;
  4489. }
  4490. else if (dataType === 2) {
  4491. return false;
  4492. }
  4493. }
  4494. if (dataType & 4) {
  4495. // Check for the "DDS" magic number
  4496. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4497. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4498. return true;
  4499. }
  4500. else {
  4501. return false;
  4502. }
  4503. }
  4504. }
  4505. catch (e) {
  4506. }
  4507. return false;
  4508. };
  4509. Object.defineProperty(Tools, "NoneLogLevel", {
  4510. get: function () {
  4511. return Tools._NoneLogLevel;
  4512. },
  4513. enumerable: true,
  4514. configurable: true
  4515. });
  4516. Object.defineProperty(Tools, "MessageLogLevel", {
  4517. get: function () {
  4518. return Tools._MessageLogLevel;
  4519. },
  4520. enumerable: true,
  4521. configurable: true
  4522. });
  4523. Object.defineProperty(Tools, "WarningLogLevel", {
  4524. get: function () {
  4525. return Tools._WarningLogLevel;
  4526. },
  4527. enumerable: true,
  4528. configurable: true
  4529. });
  4530. Object.defineProperty(Tools, "ErrorLogLevel", {
  4531. get: function () {
  4532. return Tools._ErrorLogLevel;
  4533. },
  4534. enumerable: true,
  4535. configurable: true
  4536. });
  4537. Object.defineProperty(Tools, "AllLogLevel", {
  4538. get: function () {
  4539. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4540. },
  4541. enumerable: true,
  4542. configurable: true
  4543. });
  4544. Tools._AddLogEntry = function (entry) {
  4545. Tools._LogCache = entry + Tools._LogCache;
  4546. if (Tools.OnNewCacheEntry) {
  4547. Tools.OnNewCacheEntry(entry);
  4548. }
  4549. };
  4550. Tools._FormatMessage = function (message) {
  4551. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4552. var date = new Date();
  4553. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4554. };
  4555. Tools._LogDisabled = function (message) {
  4556. // nothing to do
  4557. };
  4558. Tools._LogEnabled = function (message) {
  4559. var formattedMessage = Tools._FormatMessage(message);
  4560. console.log("BJS - " + formattedMessage);
  4561. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4562. Tools._AddLogEntry(entry);
  4563. };
  4564. Tools._WarnDisabled = function (message) {
  4565. // nothing to do
  4566. };
  4567. Tools._WarnEnabled = function (message) {
  4568. var formattedMessage = Tools._FormatMessage(message);
  4569. console.warn("BJS - " + formattedMessage);
  4570. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4571. Tools._AddLogEntry(entry);
  4572. };
  4573. Tools._ErrorDisabled = function (message) {
  4574. // nothing to do
  4575. };
  4576. Tools._ErrorEnabled = function (message) {
  4577. var formattedMessage = Tools._FormatMessage(message);
  4578. console.error("BJS - " + formattedMessage);
  4579. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4580. Tools._AddLogEntry(entry);
  4581. };
  4582. Object.defineProperty(Tools, "LogCache", {
  4583. get: function () {
  4584. return Tools._LogCache;
  4585. },
  4586. enumerable: true,
  4587. configurable: true
  4588. });
  4589. Object.defineProperty(Tools, "LogLevels", {
  4590. set: function (level) {
  4591. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4592. Tools.Log = Tools._LogEnabled;
  4593. }
  4594. else {
  4595. Tools.Log = Tools._LogDisabled;
  4596. }
  4597. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4598. Tools.Warn = Tools._WarnEnabled;
  4599. }
  4600. else {
  4601. Tools.Warn = Tools._WarnDisabled;
  4602. }
  4603. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4604. Tools.Error = Tools._ErrorEnabled;
  4605. }
  4606. else {
  4607. Tools.Error = Tools._ErrorDisabled;
  4608. }
  4609. },
  4610. enumerable: true,
  4611. configurable: true
  4612. });
  4613. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4614. get: function () {
  4615. return Tools._PerformanceNoneLogLevel;
  4616. },
  4617. enumerable: true,
  4618. configurable: true
  4619. });
  4620. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4621. get: function () {
  4622. return Tools._PerformanceUserMarkLogLevel;
  4623. },
  4624. enumerable: true,
  4625. configurable: true
  4626. });
  4627. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4628. get: function () {
  4629. return Tools._PerformanceConsoleLogLevel;
  4630. },
  4631. enumerable: true,
  4632. configurable: true
  4633. });
  4634. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4635. set: function (level) {
  4636. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4637. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4638. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4639. return;
  4640. }
  4641. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4642. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4643. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4644. return;
  4645. }
  4646. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4647. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4648. },
  4649. enumerable: true,
  4650. configurable: true
  4651. });
  4652. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4653. };
  4654. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4655. };
  4656. Tools._StartUserMark = function (counterName, condition) {
  4657. if (condition === void 0) { condition = true; }
  4658. if (!condition || !Tools._performance.mark) {
  4659. return;
  4660. }
  4661. Tools._performance.mark(counterName + "-Begin");
  4662. };
  4663. Tools._EndUserMark = function (counterName, condition) {
  4664. if (condition === void 0) { condition = true; }
  4665. if (!condition || !Tools._performance.mark) {
  4666. return;
  4667. }
  4668. Tools._performance.mark(counterName + "-End");
  4669. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4670. };
  4671. Tools._StartPerformanceConsole = function (counterName, condition) {
  4672. if (condition === void 0) { condition = true; }
  4673. if (!condition) {
  4674. return;
  4675. }
  4676. Tools._StartUserMark(counterName, condition);
  4677. if (console.time) {
  4678. console.time(counterName);
  4679. }
  4680. };
  4681. Tools._EndPerformanceConsole = function (counterName, condition) {
  4682. if (condition === void 0) { condition = true; }
  4683. if (!condition) {
  4684. return;
  4685. }
  4686. Tools._EndUserMark(counterName, condition);
  4687. if (console.time) {
  4688. console.timeEnd(counterName);
  4689. }
  4690. };
  4691. Object.defineProperty(Tools, "Now", {
  4692. get: function () {
  4693. if (window.performance && window.performance.now) {
  4694. return window.performance.now();
  4695. }
  4696. return new Date().getTime();
  4697. },
  4698. enumerable: true,
  4699. configurable: true
  4700. });
  4701. // Deprecated
  4702. Tools.GetFps = function () {
  4703. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4704. return 0;
  4705. };
  4706. Tools.BaseUrl = "";
  4707. Tools.GetExponantOfTwo = function (value, max) {
  4708. var count = 1;
  4709. do {
  4710. count *= 2;
  4711. } while (count < value);
  4712. if (count > max)
  4713. count = max;
  4714. return count;
  4715. };
  4716. // Logs
  4717. Tools._NoneLogLevel = 0;
  4718. Tools._MessageLogLevel = 1;
  4719. Tools._WarningLogLevel = 2;
  4720. Tools._ErrorLogLevel = 4;
  4721. Tools._LogCache = "";
  4722. Tools.Log = Tools._LogEnabled;
  4723. Tools.Warn = Tools._WarnEnabled;
  4724. Tools.Error = Tools._ErrorEnabled;
  4725. // Performances
  4726. Tools._PerformanceNoneLogLevel = 0;
  4727. Tools._PerformanceUserMarkLogLevel = 1;
  4728. Tools._PerformanceConsoleLogLevel = 2;
  4729. Tools._performance = window.performance;
  4730. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4731. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4732. return Tools;
  4733. })();
  4734. BABYLON.Tools = Tools;
  4735. /**
  4736. * An implementation of a loop for asynchronous functions.
  4737. */
  4738. var AsyncLoop = (function () {
  4739. /**
  4740. * Constroctor.
  4741. * @param iterations the number of iterations.
  4742. * @param _fn the function to run each iteration
  4743. * @param _successCallback the callback that will be called upon succesful execution
  4744. * @param offset starting offset.
  4745. */
  4746. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4747. if (offset === void 0) { offset = 0; }
  4748. this.iterations = iterations;
  4749. this._fn = _fn;
  4750. this._successCallback = _successCallback;
  4751. this.index = offset - 1;
  4752. this._done = false;
  4753. }
  4754. /**
  4755. * Execute the next iteration. Must be called after the last iteration was finished.
  4756. */
  4757. AsyncLoop.prototype.executeNext = function () {
  4758. if (!this._done) {
  4759. if (this.index + 1 < this.iterations) {
  4760. ++this.index;
  4761. this._fn(this);
  4762. }
  4763. else {
  4764. this.breakLoop();
  4765. }
  4766. }
  4767. };
  4768. /**
  4769. * Break the loop and run the success callback.
  4770. */
  4771. AsyncLoop.prototype.breakLoop = function () {
  4772. this._done = true;
  4773. this._successCallback();
  4774. };
  4775. /**
  4776. * Helper function
  4777. */
  4778. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4779. if (offset === void 0) { offset = 0; }
  4780. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4781. loop.executeNext();
  4782. return loop;
  4783. };
  4784. /**
  4785. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4786. * @param iterations total number of iterations
  4787. * @param syncedIterations number of synchronous iterations in each async iteration.
  4788. * @param fn the function to call each iteration.
  4789. * @param callback a success call back that will be called when iterating stops.
  4790. * @param breakFunction a break condition (optional)
  4791. * @param timeout timeout settings for the setTimeout function. default - 0.
  4792. * @constructor
  4793. */
  4794. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4795. if (timeout === void 0) { timeout = 0; }
  4796. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4797. if (breakFunction && breakFunction())
  4798. loop.breakLoop();
  4799. else {
  4800. setTimeout(function () {
  4801. for (var i = 0; i < syncedIterations; ++i) {
  4802. var iteration = (loop.index * syncedIterations) + i;
  4803. if (iteration >= iterations)
  4804. break;
  4805. fn(iteration);
  4806. if (breakFunction && breakFunction()) {
  4807. loop.breakLoop();
  4808. break;
  4809. }
  4810. }
  4811. loop.executeNext();
  4812. }, timeout);
  4813. }
  4814. }, callback);
  4815. };
  4816. return AsyncLoop;
  4817. })();
  4818. BABYLON.AsyncLoop = AsyncLoop;
  4819. })(BABYLON || (BABYLON = {}));
  4820. //# sourceMappingURL=babylon.tools.js.map
  4821. var BABYLON;
  4822. (function (BABYLON) {
  4823. var _DepthCullingState = (function () {
  4824. function _DepthCullingState() {
  4825. this._isDepthTestDirty = false;
  4826. this._isDepthMaskDirty = false;
  4827. this._isDepthFuncDirty = false;
  4828. this._isCullFaceDirty = false;
  4829. this._isCullDirty = false;
  4830. this._isZOffsetDirty = false;
  4831. }
  4832. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4833. get: function () {
  4834. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4835. },
  4836. enumerable: true,
  4837. configurable: true
  4838. });
  4839. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4840. get: function () {
  4841. return this._zOffset;
  4842. },
  4843. set: function (value) {
  4844. if (this._zOffset === value) {
  4845. return;
  4846. }
  4847. this._zOffset = value;
  4848. this._isZOffsetDirty = true;
  4849. },
  4850. enumerable: true,
  4851. configurable: true
  4852. });
  4853. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4854. get: function () {
  4855. return this._cullFace;
  4856. },
  4857. set: function (value) {
  4858. if (this._cullFace === value) {
  4859. return;
  4860. }
  4861. this._cullFace = value;
  4862. this._isCullFaceDirty = true;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4868. get: function () {
  4869. return this._cull;
  4870. },
  4871. set: function (value) {
  4872. if (this._cull === value) {
  4873. return;
  4874. }
  4875. this._cull = value;
  4876. this._isCullDirty = true;
  4877. },
  4878. enumerable: true,
  4879. configurable: true
  4880. });
  4881. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4882. get: function () {
  4883. return this._depthFunc;
  4884. },
  4885. set: function (value) {
  4886. if (this._depthFunc === value) {
  4887. return;
  4888. }
  4889. this._depthFunc = value;
  4890. this._isDepthFuncDirty = true;
  4891. },
  4892. enumerable: true,
  4893. configurable: true
  4894. });
  4895. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4896. get: function () {
  4897. return this._depthMask;
  4898. },
  4899. set: function (value) {
  4900. if (this._depthMask === value) {
  4901. return;
  4902. }
  4903. this._depthMask = value;
  4904. this._isDepthMaskDirty = true;
  4905. },
  4906. enumerable: true,
  4907. configurable: true
  4908. });
  4909. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4910. get: function () {
  4911. return this._depthTest;
  4912. },
  4913. set: function (value) {
  4914. if (this._depthTest === value) {
  4915. return;
  4916. }
  4917. this._depthTest = value;
  4918. this._isDepthTestDirty = true;
  4919. },
  4920. enumerable: true,
  4921. configurable: true
  4922. });
  4923. _DepthCullingState.prototype.reset = function () {
  4924. this._depthMask = true;
  4925. this._depthTest = true;
  4926. this._depthFunc = null;
  4927. this._cull = null;
  4928. this._cullFace = null;
  4929. this._zOffset = 0;
  4930. this._isDepthTestDirty = true;
  4931. this._isDepthMaskDirty = true;
  4932. this._isDepthFuncDirty = false;
  4933. this._isCullFaceDirty = false;
  4934. this._isCullDirty = false;
  4935. this._isZOffsetDirty = false;
  4936. };
  4937. _DepthCullingState.prototype.apply = function (gl) {
  4938. if (!this.isDirty) {
  4939. return;
  4940. }
  4941. // Cull
  4942. if (this._isCullDirty) {
  4943. if (this.cull) {
  4944. gl.enable(gl.CULL_FACE);
  4945. }
  4946. else {
  4947. gl.disable(gl.CULL_FACE);
  4948. }
  4949. this._isCullDirty = false;
  4950. }
  4951. // Cull face
  4952. if (this._isCullFaceDirty) {
  4953. gl.cullFace(this.cullFace);
  4954. this._isCullFaceDirty = false;
  4955. }
  4956. // Depth mask
  4957. if (this._isDepthMaskDirty) {
  4958. gl.depthMask(this.depthMask);
  4959. this._isDepthMaskDirty = false;
  4960. }
  4961. // Depth test
  4962. if (this._isDepthTestDirty) {
  4963. if (this.depthTest) {
  4964. gl.enable(gl.DEPTH_TEST);
  4965. }
  4966. else {
  4967. gl.disable(gl.DEPTH_TEST);
  4968. }
  4969. this._isDepthTestDirty = false;
  4970. }
  4971. // Depth func
  4972. if (this._isDepthFuncDirty) {
  4973. gl.depthFunc(this.depthFunc);
  4974. this._isDepthFuncDirty = false;
  4975. }
  4976. // zOffset
  4977. if (this._isZOffsetDirty) {
  4978. if (this.zOffset) {
  4979. gl.enable(gl.POLYGON_OFFSET_FILL);
  4980. gl.polygonOffset(this.zOffset, 0);
  4981. }
  4982. else {
  4983. gl.disable(gl.POLYGON_OFFSET_FILL);
  4984. }
  4985. this._isZOffsetDirty = false;
  4986. }
  4987. };
  4988. return _DepthCullingState;
  4989. })();
  4990. BABYLON._DepthCullingState = _DepthCullingState;
  4991. var _AlphaState = (function () {
  4992. function _AlphaState() {
  4993. this._isAlphaBlendDirty = false;
  4994. this._isBlendFunctionParametersDirty = false;
  4995. this._alphaBlend = false;
  4996. this._blendFunctionParameters = new Array(4);
  4997. }
  4998. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4999. get: function () {
  5000. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5001. },
  5002. enumerable: true,
  5003. configurable: true
  5004. });
  5005. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5006. get: function () {
  5007. return this._alphaBlend;
  5008. },
  5009. set: function (value) {
  5010. if (this._alphaBlend === value) {
  5011. return;
  5012. }
  5013. this._alphaBlend = value;
  5014. this._isAlphaBlendDirty = true;
  5015. },
  5016. enumerable: true,
  5017. configurable: true
  5018. });
  5019. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5020. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  5021. return;
  5022. }
  5023. this._blendFunctionParameters[0] = value0;
  5024. this._blendFunctionParameters[1] = value1;
  5025. this._blendFunctionParameters[2] = value2;
  5026. this._blendFunctionParameters[3] = value3;
  5027. this._isBlendFunctionParametersDirty = true;
  5028. };
  5029. _AlphaState.prototype.reset = function () {
  5030. this._alphaBlend = false;
  5031. this._blendFunctionParameters[0] = null;
  5032. this._blendFunctionParameters[1] = null;
  5033. this._blendFunctionParameters[2] = null;
  5034. this._blendFunctionParameters[3] = null;
  5035. this._isAlphaBlendDirty = true;
  5036. this._isBlendFunctionParametersDirty = false;
  5037. };
  5038. _AlphaState.prototype.apply = function (gl) {
  5039. if (!this.isDirty) {
  5040. return;
  5041. }
  5042. // Alpha blend
  5043. if (this._isAlphaBlendDirty) {
  5044. if (this._alphaBlend) {
  5045. gl.enable(gl.BLEND);
  5046. }
  5047. else {
  5048. gl.disable(gl.BLEND);
  5049. }
  5050. this._isAlphaBlendDirty = false;
  5051. }
  5052. // Alpha function
  5053. if (this._isBlendFunctionParametersDirty) {
  5054. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5055. this._isBlendFunctionParametersDirty = false;
  5056. }
  5057. };
  5058. return _AlphaState;
  5059. })();
  5060. BABYLON._AlphaState = _AlphaState;
  5061. var compileShader = function (gl, source, type, defines) {
  5062. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5063. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5064. gl.compileShader(shader);
  5065. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5066. throw new Error(gl.getShaderInfoLog(shader));
  5067. }
  5068. return shader;
  5069. };
  5070. var getWebGLTextureType = function (gl, type) {
  5071. var textureType = gl.UNSIGNED_BYTE;
  5072. if (type === Engine.TEXTURETYPE_FLOAT)
  5073. textureType = gl.FLOAT;
  5074. return textureType;
  5075. };
  5076. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5077. var magFilter = gl.NEAREST;
  5078. var minFilter = gl.NEAREST;
  5079. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5080. magFilter = gl.LINEAR;
  5081. if (generateMipMaps) {
  5082. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5083. }
  5084. else {
  5085. minFilter = gl.LINEAR;
  5086. }
  5087. }
  5088. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5089. magFilter = gl.LINEAR;
  5090. if (generateMipMaps) {
  5091. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5092. }
  5093. else {
  5094. minFilter = gl.LINEAR;
  5095. }
  5096. }
  5097. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5098. magFilter = gl.NEAREST;
  5099. if (generateMipMaps) {
  5100. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5101. }
  5102. else {
  5103. minFilter = gl.NEAREST;
  5104. }
  5105. }
  5106. return {
  5107. min: minFilter,
  5108. mag: magFilter
  5109. };
  5110. };
  5111. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5113. var engine = scene.getEngine();
  5114. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5115. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5116. gl.bindTexture(gl.TEXTURE_2D, texture);
  5117. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5118. texture._baseWidth = width;
  5119. texture._baseHeight = height;
  5120. texture._width = potWidth;
  5121. texture._height = potHeight;
  5122. texture.isReady = true;
  5123. processFunction(potWidth, potHeight);
  5124. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5127. if (!noMipmap && !isCompressed) {
  5128. gl.generateMipmap(gl.TEXTURE_2D);
  5129. }
  5130. gl.bindTexture(gl.TEXTURE_2D, null);
  5131. engine._activeTexturesCache = [];
  5132. scene._removePendingData(texture);
  5133. };
  5134. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5135. var onload = function () {
  5136. loadedImages[index] = img;
  5137. loadedImages._internalCount++;
  5138. scene._removePendingData(img);
  5139. if (loadedImages._internalCount === 6) {
  5140. onfinish(loadedImages);
  5141. }
  5142. };
  5143. var onerror = function () {
  5144. scene._removePendingData(img);
  5145. };
  5146. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5147. scene._addPendingData(img);
  5148. };
  5149. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5150. var loadedImages = [];
  5151. loadedImages._internalCount = 0;
  5152. for (var index = 0; index < 6; index++) {
  5153. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5154. }
  5155. };
  5156. var EngineCapabilities = (function () {
  5157. function EngineCapabilities() {
  5158. }
  5159. return EngineCapabilities;
  5160. })();
  5161. BABYLON.EngineCapabilities = EngineCapabilities;
  5162. /**
  5163. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5164. */
  5165. var Engine = (function () {
  5166. /**
  5167. * @constructor
  5168. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5169. * @param {boolean} [antialias] - enable antialias
  5170. * @param options - further options to be sent to the getContext function
  5171. */
  5172. function Engine(canvas, antialias, options) {
  5173. var _this = this;
  5174. // Public members
  5175. this.isFullscreen = false;
  5176. this.isPointerLock = false;
  5177. this.cullBackFaces = true;
  5178. this.renderEvenInBackground = true;
  5179. this.scenes = new Array();
  5180. this._windowIsBackground = false;
  5181. this._loadingDivBackgroundColor = "black";
  5182. this._drawCalls = 0;
  5183. this._renderingQueueLaunched = false;
  5184. this._activeRenderLoops = [];
  5185. // FPS
  5186. this.fpsRange = 60;
  5187. this.previousFramesDuration = [];
  5188. this.fps = 60;
  5189. this.deltaTime = 0;
  5190. // States
  5191. this._depthCullingState = new _DepthCullingState();
  5192. this._alphaState = new _AlphaState();
  5193. this._alphaMode = Engine.ALPHA_DISABLE;
  5194. // Cache
  5195. this._loadedTexturesCache = new Array();
  5196. this._activeTexturesCache = new Array();
  5197. this._compiledEffects = {};
  5198. this._uintIndicesCurrentlySet = false;
  5199. this._renderingCanvas = canvas;
  5200. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5201. options = options || {};
  5202. options.antialias = antialias;
  5203. try {
  5204. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5205. }
  5206. catch (e) {
  5207. throw new Error("WebGL not supported");
  5208. }
  5209. if (!this._gl) {
  5210. throw new Error("WebGL not supported");
  5211. }
  5212. this._onBlur = function () {
  5213. _this._windowIsBackground = true;
  5214. };
  5215. this._onFocus = function () {
  5216. _this._windowIsBackground = false;
  5217. };
  5218. window.addEventListener("blur", this._onBlur);
  5219. window.addEventListener("focus", this._onFocus);
  5220. // Viewport
  5221. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5222. this.resize();
  5223. // Caps
  5224. this._caps = new EngineCapabilities();
  5225. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5226. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5227. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5228. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5229. // Infos
  5230. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5231. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5232. if (rendererInfo != null) {
  5233. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5234. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5235. }
  5236. if (!this._glVendor) {
  5237. this._glVendor = "Unknown vendor";
  5238. }
  5239. if (!this._glRenderer) {
  5240. this._glRenderer = "Unknown renderer";
  5241. }
  5242. // Extensions
  5243. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5244. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5245. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5246. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  5247. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5248. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5249. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5250. this._caps.highPrecisionShaderSupported = true;
  5251. if (this._gl.getShaderPrecisionFormat) {
  5252. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5253. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5254. }
  5255. // Depth buffer
  5256. this.setDepthBuffer(true);
  5257. this.setDepthFunctionToLessOrEqual();
  5258. this.setDepthWrite(true);
  5259. // Fullscreen
  5260. this._onFullscreenChange = function () {
  5261. if (document.fullscreen !== undefined) {
  5262. _this.isFullscreen = document.fullscreen;
  5263. }
  5264. else if (document.mozFullScreen !== undefined) {
  5265. _this.isFullscreen = document.mozFullScreen;
  5266. }
  5267. else if (document.webkitIsFullScreen !== undefined) {
  5268. _this.isFullscreen = document.webkitIsFullScreen;
  5269. }
  5270. else if (document.msIsFullScreen !== undefined) {
  5271. _this.isFullscreen = document.msIsFullScreen;
  5272. }
  5273. // Pointer lock
  5274. if (_this.isFullscreen && _this._pointerLockRequested) {
  5275. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  5276. if (canvas.requestPointerLock) {
  5277. canvas.requestPointerLock();
  5278. }
  5279. }
  5280. };
  5281. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5282. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5283. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5284. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5285. // Pointer lock
  5286. this._onPointerLockChange = function () {
  5287. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  5288. };
  5289. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5290. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5291. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5292. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5293. if (!Engine.audioEngine) {
  5294. Engine.audioEngine = new BABYLON.AudioEngine();
  5295. }
  5296. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5297. }
  5298. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5299. get: function () {
  5300. return Engine._ALPHA_DISABLE;
  5301. },
  5302. enumerable: true,
  5303. configurable: true
  5304. });
  5305. Object.defineProperty(Engine, "ALPHA_ADD", {
  5306. get: function () {
  5307. return Engine._ALPHA_ADD;
  5308. },
  5309. enumerable: true,
  5310. configurable: true
  5311. });
  5312. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5313. get: function () {
  5314. return Engine._ALPHA_COMBINE;
  5315. },
  5316. enumerable: true,
  5317. configurable: true
  5318. });
  5319. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5320. get: function () {
  5321. return Engine._DELAYLOADSTATE_NONE;
  5322. },
  5323. enumerable: true,
  5324. configurable: true
  5325. });
  5326. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5327. get: function () {
  5328. return Engine._DELAYLOADSTATE_LOADED;
  5329. },
  5330. enumerable: true,
  5331. configurable: true
  5332. });
  5333. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5334. get: function () {
  5335. return Engine._DELAYLOADSTATE_LOADING;
  5336. },
  5337. enumerable: true,
  5338. configurable: true
  5339. });
  5340. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5341. get: function () {
  5342. return Engine._DELAYLOADSTATE_NOTLOADED;
  5343. },
  5344. enumerable: true,
  5345. configurable: true
  5346. });
  5347. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5348. get: function () {
  5349. return Engine._TEXTUREFORMAT_ALPHA;
  5350. },
  5351. enumerable: true,
  5352. configurable: true
  5353. });
  5354. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5355. get: function () {
  5356. return Engine._TEXTUREFORMAT_LUMINANCE;
  5357. },
  5358. enumerable: true,
  5359. configurable: true
  5360. });
  5361. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5362. get: function () {
  5363. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5364. },
  5365. enumerable: true,
  5366. configurable: true
  5367. });
  5368. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5369. get: function () {
  5370. return Engine._TEXTUREFORMAT_RGB;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5376. get: function () {
  5377. return Engine._TEXTUREFORMAT_RGBA;
  5378. },
  5379. enumerable: true,
  5380. configurable: true
  5381. });
  5382. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5383. get: function () {
  5384. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5390. get: function () {
  5391. return Engine._TEXTURETYPE_FLOAT;
  5392. },
  5393. enumerable: true,
  5394. configurable: true
  5395. });
  5396. Object.defineProperty(Engine, "Version", {
  5397. get: function () {
  5398. return "2.1.0 beta";
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. Engine.prototype._prepareWorkingCanvas = function () {
  5404. if (this._workingCanvas) {
  5405. return;
  5406. }
  5407. this._workingCanvas = document.createElement("canvas");
  5408. this._workingContext = this._workingCanvas.getContext("2d");
  5409. };
  5410. Engine.prototype.getGlInfo = function () {
  5411. return {
  5412. vendor: this._glVendor,
  5413. renderer: this._glRenderer,
  5414. version: this._glVersion
  5415. };
  5416. };
  5417. Engine.prototype.getAspectRatio = function (camera) {
  5418. var viewport = camera.viewport;
  5419. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5420. };
  5421. Engine.prototype.getRenderWidth = function () {
  5422. if (this._currentRenderTarget) {
  5423. return this._currentRenderTarget._width;
  5424. }
  5425. return this._renderingCanvas.width;
  5426. };
  5427. Engine.prototype.getRenderHeight = function () {
  5428. if (this._currentRenderTarget) {
  5429. return this._currentRenderTarget._height;
  5430. }
  5431. return this._renderingCanvas.height;
  5432. };
  5433. Engine.prototype.getRenderingCanvas = function () {
  5434. return this._renderingCanvas;
  5435. };
  5436. Engine.prototype.getRenderingCanvasClientRect = function () {
  5437. return this._renderingCanvas.getBoundingClientRect();
  5438. };
  5439. Engine.prototype.setHardwareScalingLevel = function (level) {
  5440. this._hardwareScalingLevel = level;
  5441. this.resize();
  5442. };
  5443. Engine.prototype.getHardwareScalingLevel = function () {
  5444. return this._hardwareScalingLevel;
  5445. };
  5446. Engine.prototype.getLoadedTexturesCache = function () {
  5447. return this._loadedTexturesCache;
  5448. };
  5449. Engine.prototype.getCaps = function () {
  5450. return this._caps;
  5451. };
  5452. Object.defineProperty(Engine.prototype, "drawCalls", {
  5453. get: function () {
  5454. return this._drawCalls;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. // Methods
  5460. Engine.prototype.resetDrawCalls = function () {
  5461. this._drawCalls = 0;
  5462. };
  5463. Engine.prototype.setDepthFunctionToGreater = function () {
  5464. this._depthCullingState.depthFunc = this._gl.GREATER;
  5465. };
  5466. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5467. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5468. };
  5469. Engine.prototype.setDepthFunctionToLess = function () {
  5470. this._depthCullingState.depthFunc = this._gl.LESS;
  5471. };
  5472. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5473. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5474. };
  5475. /**
  5476. * stop executing a render loop function and remove it from the execution array
  5477. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5478. */
  5479. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5480. if (!renderFunction) {
  5481. this._activeRenderLoops = [];
  5482. return;
  5483. }
  5484. var index = this._activeRenderLoops.indexOf(renderFunction);
  5485. if (index >= 0) {
  5486. this._activeRenderLoops.splice(index, 1);
  5487. }
  5488. };
  5489. Engine.prototype._renderLoop = function () {
  5490. var _this = this;
  5491. var shouldRender = true;
  5492. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5493. shouldRender = false;
  5494. }
  5495. if (shouldRender) {
  5496. // Start new frame
  5497. this.beginFrame();
  5498. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5499. var renderFunction = this._activeRenderLoops[index];
  5500. renderFunction();
  5501. }
  5502. // Present
  5503. this.endFrame();
  5504. }
  5505. if (this._activeRenderLoops.length > 0) {
  5506. // Register new frame
  5507. BABYLON.Tools.QueueNewFrame(function () {
  5508. _this._renderLoop();
  5509. });
  5510. }
  5511. else {
  5512. this._renderingQueueLaunched = false;
  5513. }
  5514. };
  5515. /**
  5516. * Register and execute a render loop. The engine can have more than one render function.
  5517. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5518. * @example
  5519. * engine.runRenderLoop(function () {
  5520. * scene.render()
  5521. * })
  5522. */
  5523. Engine.prototype.runRenderLoop = function (renderFunction) {
  5524. var _this = this;
  5525. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5526. return;
  5527. }
  5528. this._activeRenderLoops.push(renderFunction);
  5529. if (!this._renderingQueueLaunched) {
  5530. this._renderingQueueLaunched = true;
  5531. BABYLON.Tools.QueueNewFrame(function () {
  5532. _this._renderLoop();
  5533. });
  5534. }
  5535. };
  5536. /**
  5537. * Toggle full screen mode.
  5538. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5539. */
  5540. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5541. if (this.isFullscreen) {
  5542. BABYLON.Tools.ExitFullscreen();
  5543. }
  5544. else {
  5545. this._pointerLockRequested = requestPointerLock;
  5546. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5547. }
  5548. };
  5549. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5550. this.applyStates();
  5551. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5552. if (this._depthCullingState.depthMask) {
  5553. this._gl.clearDepth(1.0);
  5554. }
  5555. var mode = 0;
  5556. if (backBuffer)
  5557. mode |= this._gl.COLOR_BUFFER_BIT;
  5558. if (depthStencil && this._depthCullingState.depthMask)
  5559. mode |= this._gl.DEPTH_BUFFER_BIT;
  5560. this._gl.clear(mode);
  5561. };
  5562. /**
  5563. * Set the WebGL's viewport
  5564. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5565. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5566. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5567. */
  5568. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5569. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5570. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5571. var x = viewport.x || 0;
  5572. var y = viewport.y || 0;
  5573. this._cachedViewport = viewport;
  5574. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5575. };
  5576. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5577. this._cachedViewport = null;
  5578. this._gl.viewport(x, y, width, height);
  5579. };
  5580. Engine.prototype.beginFrame = function () {
  5581. this._measureFps();
  5582. };
  5583. Engine.prototype.endFrame = function () {
  5584. //this.flushFramebuffer();
  5585. };
  5586. /**
  5587. * resize the view according to the canvas' size.
  5588. * @example
  5589. * window.addEventListener("resize", function () {
  5590. * engine.resize();
  5591. * });
  5592. */
  5593. Engine.prototype.resize = function () {
  5594. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5595. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5596. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5597. };
  5598. /**
  5599. * force a specific size of the canvas
  5600. * @param {number} width - the new canvas' width
  5601. * @param {number} height - the new canvas' height
  5602. */
  5603. Engine.prototype.setSize = function (width, height) {
  5604. this._renderingCanvas.width = width;
  5605. this._renderingCanvas.height = height;
  5606. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5607. for (var index = 0; index < this.scenes.length; index++) {
  5608. var scene = this.scenes[index];
  5609. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5610. var cam = scene.cameras[camIndex];
  5611. cam._currentRenderId = 0;
  5612. }
  5613. }
  5614. };
  5615. Engine.prototype.bindFramebuffer = function (texture) {
  5616. this._currentRenderTarget = texture;
  5617. var gl = this._gl;
  5618. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5619. this._gl.viewport(0, 0, texture._width, texture._height);
  5620. this.wipeCaches();
  5621. };
  5622. Engine.prototype.unBindFramebuffer = function (texture) {
  5623. this._currentRenderTarget = null;
  5624. if (texture.generateMipMaps) {
  5625. var gl = this._gl;
  5626. gl.bindTexture(gl.TEXTURE_2D, texture);
  5627. gl.generateMipmap(gl.TEXTURE_2D);
  5628. gl.bindTexture(gl.TEXTURE_2D, null);
  5629. }
  5630. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5631. };
  5632. Engine.prototype.flushFramebuffer = function () {
  5633. this._gl.flush();
  5634. };
  5635. Engine.prototype.restoreDefaultFramebuffer = function () {
  5636. this._currentRenderTarget = null;
  5637. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5638. this.setViewport(this._cachedViewport);
  5639. this.wipeCaches();
  5640. };
  5641. // VBOs
  5642. Engine.prototype._resetVertexBufferBinding = function () {
  5643. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5644. this._cachedVertexBuffers = null;
  5645. };
  5646. Engine.prototype.createVertexBuffer = function (vertices) {
  5647. var vbo = this._gl.createBuffer();
  5648. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5649. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5650. this._resetVertexBufferBinding();
  5651. vbo.references = 1;
  5652. return vbo;
  5653. };
  5654. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5655. var vbo = this._gl.createBuffer();
  5656. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5657. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5658. this._resetVertexBufferBinding();
  5659. vbo.references = 1;
  5660. return vbo;
  5661. };
  5662. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5663. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5664. if (offset === undefined) {
  5665. offset = 0;
  5666. }
  5667. if (vertices instanceof Float32Array) {
  5668. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5669. }
  5670. else {
  5671. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5672. }
  5673. this._resetVertexBufferBinding();
  5674. };
  5675. Engine.prototype._resetIndexBufferBinding = function () {
  5676. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5677. this._cachedIndexBuffer = null;
  5678. };
  5679. Engine.prototype.createIndexBuffer = function (indices) {
  5680. var vbo = this._gl.createBuffer();
  5681. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5682. // Check for 32 bits indices
  5683. var arrayBuffer;
  5684. var need32Bits = false;
  5685. if (this._caps.uintIndices) {
  5686. for (var index = 0; index < indices.length; index++) {
  5687. if (indices[index] > 65535) {
  5688. need32Bits = true;
  5689. break;
  5690. }
  5691. }
  5692. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5693. }
  5694. else {
  5695. arrayBuffer = new Uint16Array(indices);
  5696. }
  5697. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5698. this._resetIndexBufferBinding();
  5699. vbo.references = 1;
  5700. vbo.is32Bits = need32Bits;
  5701. return vbo;
  5702. };
  5703. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5704. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5705. this._cachedVertexBuffers = vertexBuffer;
  5706. this._cachedEffectForVertexBuffers = effect;
  5707. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5708. var offset = 0;
  5709. for (var index = 0; index < vertexDeclaration.length; index++) {
  5710. var order = effect.getAttributeLocation(index);
  5711. if (order >= 0) {
  5712. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5713. }
  5714. offset += vertexDeclaration[index] * 4;
  5715. }
  5716. }
  5717. if (this._cachedIndexBuffer !== indexBuffer) {
  5718. this._cachedIndexBuffer = indexBuffer;
  5719. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5720. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5721. }
  5722. };
  5723. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5724. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5725. this._cachedVertexBuffers = vertexBuffers;
  5726. this._cachedEffectForVertexBuffers = effect;
  5727. var attributes = effect.getAttributesNames();
  5728. for (var index = 0; index < attributes.length; index++) {
  5729. var order = effect.getAttributeLocation(index);
  5730. if (order >= 0) {
  5731. var vertexBuffer = vertexBuffers[attributes[index]];
  5732. if (!vertexBuffer) {
  5733. continue;
  5734. }
  5735. var stride = vertexBuffer.getStrideSize();
  5736. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5737. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5738. }
  5739. }
  5740. }
  5741. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5742. this._cachedIndexBuffer = indexBuffer;
  5743. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5744. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5745. }
  5746. };
  5747. Engine.prototype._releaseBuffer = function (buffer) {
  5748. buffer.references--;
  5749. if (buffer.references === 0) {
  5750. this._gl.deleteBuffer(buffer);
  5751. return true;
  5752. }
  5753. return false;
  5754. };
  5755. Engine.prototype.createInstancesBuffer = function (capacity) {
  5756. var buffer = this._gl.createBuffer();
  5757. buffer.capacity = capacity;
  5758. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5759. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5760. return buffer;
  5761. };
  5762. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5763. this._gl.deleteBuffer(buffer);
  5764. };
  5765. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5766. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5767. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5768. for (var index = 0; index < 4; index++) {
  5769. var offsetLocation = offsetLocations[index];
  5770. this._gl.enableVertexAttribArray(offsetLocation);
  5771. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5772. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5773. }
  5774. };
  5775. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5776. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5777. for (var index = 0; index < 4; index++) {
  5778. var offsetLocation = offsetLocations[index];
  5779. this._gl.disableVertexAttribArray(offsetLocation);
  5780. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5781. }
  5782. };
  5783. Engine.prototype.applyStates = function () {
  5784. this._depthCullingState.apply(this._gl);
  5785. this._alphaState.apply(this._gl);
  5786. };
  5787. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5788. // Apply states
  5789. this.applyStates();
  5790. this._drawCalls++;
  5791. // Render
  5792. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5793. if (instancesCount) {
  5794. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  5795. return;
  5796. }
  5797. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  5798. };
  5799. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5800. // Apply states
  5801. this.applyStates();
  5802. this._drawCalls++;
  5803. if (instancesCount) {
  5804. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5805. return;
  5806. }
  5807. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5808. };
  5809. // Shaders
  5810. Engine.prototype._releaseEffect = function (effect) {
  5811. if (this._compiledEffects[effect._key]) {
  5812. delete this._compiledEffects[effect._key];
  5813. if (effect.getProgram()) {
  5814. this._gl.deleteProgram(effect.getProgram());
  5815. }
  5816. }
  5817. };
  5818. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5819. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5820. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5821. var name = vertex + "+" + fragment + "@" + defines;
  5822. if (this._compiledEffects[name]) {
  5823. return this._compiledEffects[name];
  5824. }
  5825. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5826. effect._key = name;
  5827. this._compiledEffects[name] = effect;
  5828. return effect;
  5829. };
  5830. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5831. if (uniformsNames === void 0) { uniformsNames = []; }
  5832. if (samplers === void 0) { samplers = []; }
  5833. if (defines === void 0) { defines = ""; }
  5834. return this.createEffect({
  5835. vertex: "particles",
  5836. fragmentElement: fragmentName
  5837. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5838. };
  5839. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5840. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5841. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5842. var shaderProgram = this._gl.createProgram();
  5843. this._gl.attachShader(shaderProgram, vertexShader);
  5844. this._gl.attachShader(shaderProgram, fragmentShader);
  5845. this._gl.linkProgram(shaderProgram);
  5846. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5847. if (!linked) {
  5848. var error = this._gl.getProgramInfoLog(shaderProgram);
  5849. if (error) {
  5850. throw new Error(error);
  5851. }
  5852. }
  5853. this._gl.deleteShader(vertexShader);
  5854. this._gl.deleteShader(fragmentShader);
  5855. return shaderProgram;
  5856. };
  5857. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5858. var results = [];
  5859. for (var index = 0; index < uniformsNames.length; index++) {
  5860. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5861. }
  5862. return results;
  5863. };
  5864. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5865. var results = [];
  5866. for (var index = 0; index < attributesNames.length; index++) {
  5867. try {
  5868. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5869. }
  5870. catch (e) {
  5871. results.push(-1);
  5872. }
  5873. }
  5874. return results;
  5875. };
  5876. Engine.prototype.enableEffect = function (effect) {
  5877. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5878. if (effect && effect.onBind) {
  5879. effect.onBind(effect);
  5880. }
  5881. return;
  5882. }
  5883. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5884. // Use program
  5885. this._gl.useProgram(effect.getProgram());
  5886. for (var i in this._vertexAttribArrays) {
  5887. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5888. continue;
  5889. }
  5890. this._vertexAttribArrays[i] = false;
  5891. this._gl.disableVertexAttribArray(i);
  5892. }
  5893. var attributesCount = effect.getAttributesCount();
  5894. for (var index = 0; index < attributesCount; index++) {
  5895. // Attributes
  5896. var order = effect.getAttributeLocation(index);
  5897. if (order >= 0) {
  5898. this._vertexAttribArrays[order] = true;
  5899. this._gl.enableVertexAttribArray(order);
  5900. }
  5901. }
  5902. this._currentEffect = effect;
  5903. if (effect.onBind) {
  5904. effect.onBind(effect);
  5905. }
  5906. };
  5907. Engine.prototype.setArray = function (uniform, array) {
  5908. if (!uniform)
  5909. return;
  5910. this._gl.uniform1fv(uniform, array);
  5911. };
  5912. Engine.prototype.setArray2 = function (uniform, array) {
  5913. if (!uniform || array.length % 2 !== 0)
  5914. return;
  5915. this._gl.uniform2fv(uniform, array);
  5916. };
  5917. Engine.prototype.setArray3 = function (uniform, array) {
  5918. if (!uniform || array.length % 3 !== 0)
  5919. return;
  5920. this._gl.uniform3fv(uniform, array);
  5921. };
  5922. Engine.prototype.setArray4 = function (uniform, array) {
  5923. if (!uniform || array.length % 4 !== 0)
  5924. return;
  5925. this._gl.uniform4fv(uniform, array);
  5926. };
  5927. Engine.prototype.setMatrices = function (uniform, matrices) {
  5928. if (!uniform)
  5929. return;
  5930. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5931. };
  5932. Engine.prototype.setMatrix = function (uniform, matrix) {
  5933. if (!uniform)
  5934. return;
  5935. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5936. };
  5937. Engine.prototype.setFloat = function (uniform, value) {
  5938. if (!uniform)
  5939. return;
  5940. this._gl.uniform1f(uniform, value);
  5941. };
  5942. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5943. if (!uniform)
  5944. return;
  5945. this._gl.uniform2f(uniform, x, y);
  5946. };
  5947. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5948. if (!uniform)
  5949. return;
  5950. this._gl.uniform3f(uniform, x, y, z);
  5951. };
  5952. Engine.prototype.setBool = function (uniform, bool) {
  5953. if (!uniform)
  5954. return;
  5955. this._gl.uniform1i(uniform, bool);
  5956. };
  5957. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5958. if (!uniform)
  5959. return;
  5960. this._gl.uniform4f(uniform, x, y, z, w);
  5961. };
  5962. Engine.prototype.setColor3 = function (uniform, color3) {
  5963. if (!uniform)
  5964. return;
  5965. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5966. };
  5967. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5968. if (!uniform)
  5969. return;
  5970. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5971. };
  5972. // States
  5973. Engine.prototype.setState = function (culling, zOffset, force) {
  5974. if (zOffset === void 0) { zOffset = 0; }
  5975. // Culling
  5976. if (this._depthCullingState.cull !== culling || force) {
  5977. if (culling) {
  5978. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  5979. this._depthCullingState.cull = true;
  5980. }
  5981. else {
  5982. this._depthCullingState.cull = false;
  5983. }
  5984. }
  5985. // Z offset
  5986. this._depthCullingState.zOffset = zOffset;
  5987. };
  5988. Engine.prototype.setDepthBuffer = function (enable) {
  5989. this._depthCullingState.depthTest = enable;
  5990. };
  5991. Engine.prototype.getDepthWrite = function () {
  5992. return this._depthCullingState.depthMask;
  5993. };
  5994. Engine.prototype.setDepthWrite = function (enable) {
  5995. this._depthCullingState.depthMask = enable;
  5996. };
  5997. Engine.prototype.setColorWrite = function (enable) {
  5998. this._gl.colorMask(enable, enable, enable, enable);
  5999. };
  6000. Engine.prototype.setAlphaMode = function (mode) {
  6001. switch (mode) {
  6002. case Engine.ALPHA_DISABLE:
  6003. this.setDepthWrite(true);
  6004. this._alphaState.alphaBlend = false;
  6005. break;
  6006. case Engine.ALPHA_COMBINE:
  6007. this.setDepthWrite(false);
  6008. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6009. this._alphaState.alphaBlend = true;
  6010. break;
  6011. case Engine.ALPHA_ADD:
  6012. this.setDepthWrite(false);
  6013. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6014. this._alphaState.alphaBlend = true;
  6015. break;
  6016. }
  6017. this._alphaMode = mode;
  6018. };
  6019. Engine.prototype.getAlphaMode = function () {
  6020. return this._alphaMode;
  6021. };
  6022. Engine.prototype.setAlphaTesting = function (enable) {
  6023. this._alphaTest = enable;
  6024. };
  6025. Engine.prototype.getAlphaTesting = function () {
  6026. return this._alphaTest;
  6027. };
  6028. // Textures
  6029. Engine.prototype.wipeCaches = function () {
  6030. this._activeTexturesCache = [];
  6031. this._currentEffect = null;
  6032. this._depthCullingState.reset();
  6033. this._alphaState.reset();
  6034. this._cachedVertexBuffers = null;
  6035. this._cachedIndexBuffer = null;
  6036. this._cachedEffectForVertexBuffers = null;
  6037. };
  6038. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6039. var gl = this._gl;
  6040. gl.bindTexture(gl.TEXTURE_2D, texture);
  6041. var magFilter = gl.NEAREST;
  6042. var minFilter = gl.NEAREST;
  6043. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6044. magFilter = gl.LINEAR;
  6045. minFilter = gl.LINEAR;
  6046. }
  6047. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6048. magFilter = gl.LINEAR;
  6049. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6050. }
  6051. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6052. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6053. gl.bindTexture(gl.TEXTURE_2D, null);
  6054. texture.samplingMode = samplingMode;
  6055. };
  6056. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6057. var _this = this;
  6058. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6059. if (onLoad === void 0) { onLoad = null; }
  6060. if (onError === void 0) { onError = null; }
  6061. if (buffer === void 0) { buffer = null; }
  6062. var texture = this._gl.createTexture();
  6063. var extension;
  6064. var fromData = false;
  6065. if (url.substr(0, 5) === "data:") {
  6066. fromData = true;
  6067. }
  6068. if (!fromData)
  6069. extension = url.substr(url.length - 4, 4).toLowerCase();
  6070. else {
  6071. var oldUrl = url;
  6072. fromData = oldUrl.split(':');
  6073. url = oldUrl;
  6074. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6075. }
  6076. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6077. var isTGA = (extension === ".tga");
  6078. scene._addPendingData(texture);
  6079. texture.url = url;
  6080. texture.noMipmap = noMipmap;
  6081. texture.references = 1;
  6082. texture.samplingMode = samplingMode;
  6083. this._loadedTexturesCache.push(texture);
  6084. var onerror = function () {
  6085. scene._removePendingData(texture);
  6086. if (onError) {
  6087. onError();
  6088. }
  6089. };
  6090. if (isTGA) {
  6091. var callback = function (arrayBuffer) {
  6092. var data = new Uint8Array(arrayBuffer);
  6093. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6094. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6095. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6096. if (onLoad) {
  6097. onLoad();
  6098. }
  6099. }, samplingMode);
  6100. };
  6101. if (!(fromData instanceof Array))
  6102. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6103. callback(arrayBuffer);
  6104. }, onerror, scene.database, true);
  6105. else
  6106. callback(buffer);
  6107. }
  6108. else if (isDDS) {
  6109. callback = function (data) {
  6110. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6111. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6112. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6113. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6114. if (onLoad) {
  6115. onLoad();
  6116. }
  6117. }, samplingMode);
  6118. };
  6119. if (!(fromData instanceof Array))
  6120. BABYLON.Tools.LoadFile(url, function (data) {
  6121. callback(data);
  6122. }, onerror, scene.database, true);
  6123. else
  6124. callback(buffer);
  6125. }
  6126. else {
  6127. var onload = function (img) {
  6128. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6129. var isPot = (img.width === potWidth && img.height === potHeight);
  6130. if (!isPot) {
  6131. _this._prepareWorkingCanvas();
  6132. _this._workingCanvas.width = potWidth;
  6133. _this._workingCanvas.height = potHeight;
  6134. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6135. _this._workingContext.imageSmoothingEnabled = false;
  6136. _this._workingContext.mozImageSmoothingEnabled = false;
  6137. _this._workingContext.oImageSmoothingEnabled = false;
  6138. _this._workingContext.webkitImageSmoothingEnabled = false;
  6139. _this._workingContext.msImageSmoothingEnabled = false;
  6140. }
  6141. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6142. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6143. _this._workingContext.imageSmoothingEnabled = true;
  6144. _this._workingContext.mozImageSmoothingEnabled = true;
  6145. _this._workingContext.oImageSmoothingEnabled = true;
  6146. _this._workingContext.webkitImageSmoothingEnabled = true;
  6147. _this._workingContext.msImageSmoothingEnabled = true;
  6148. }
  6149. }
  6150. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6151. if (onLoad) {
  6152. onLoad();
  6153. }
  6154. }, samplingMode);
  6155. };
  6156. if (!(fromData instanceof Array))
  6157. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6158. else
  6159. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6160. }
  6161. return texture;
  6162. };
  6163. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6164. var texture = this._gl.createTexture();
  6165. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6166. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6167. // Format
  6168. var internalFormat = this._gl.RGBA;
  6169. switch (format) {
  6170. case Engine.TEXTUREFORMAT_ALPHA:
  6171. internalFormat = this._gl.ALPHA;
  6172. break;
  6173. case Engine.TEXTUREFORMAT_LUMINANCE:
  6174. internalFormat = this._gl.LUMINANCE;
  6175. break;
  6176. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6177. internalFormat = this._gl.LUMINANCE_ALPHA;
  6178. break;
  6179. case Engine.TEXTUREFORMAT_RGB:
  6180. internalFormat = this._gl.RGB;
  6181. break;
  6182. case Engine.TEXTUREFORMAT_RGBA:
  6183. internalFormat = this._gl.RGBA;
  6184. break;
  6185. }
  6186. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6187. if (generateMipMaps) {
  6188. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6189. }
  6190. // Filters
  6191. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6193. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6194. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6195. this._activeTexturesCache = [];
  6196. texture._baseWidth = width;
  6197. texture._baseHeight = height;
  6198. texture._width = width;
  6199. texture._height = height;
  6200. texture.isReady = true;
  6201. texture.references = 1;
  6202. texture.samplingMode = samplingMode;
  6203. this._loadedTexturesCache.push(texture);
  6204. return texture;
  6205. };
  6206. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  6207. var texture = this._gl.createTexture();
  6208. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6209. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6210. this._activeTexturesCache = [];
  6211. texture._baseWidth = width;
  6212. texture._baseHeight = height;
  6213. texture._width = width;
  6214. texture._height = height;
  6215. texture.isReady = false;
  6216. texture.generateMipMaps = generateMipMaps;
  6217. texture.references = 1;
  6218. texture.samplingMode = samplingMode;
  6219. this.updateTextureSamplingMode(samplingMode, texture);
  6220. this._loadedTexturesCache.push(texture);
  6221. return texture;
  6222. };
  6223. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6224. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6225. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6226. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6227. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6228. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6229. };
  6230. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6231. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6232. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6233. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6234. if (texture.generateMipMaps) {
  6235. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6236. }
  6237. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6238. this._activeTexturesCache = [];
  6239. texture.isReady = true;
  6240. };
  6241. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6242. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6243. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6244. // Scale the video if it is a NPOT using the current working canvas
  6245. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  6246. if (!texture._workingCanvas) {
  6247. texture._workingCanvas = document.createElement("canvas");
  6248. texture._workingContext = texture._workingCanvas.getContext("2d");
  6249. texture._workingCanvas.width = texture._width;
  6250. texture._workingCanvas.height = texture._height;
  6251. }
  6252. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6253. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6254. }
  6255. else {
  6256. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6257. }
  6258. if (texture.generateMipMaps) {
  6259. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6260. }
  6261. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6262. this._activeTexturesCache = [];
  6263. texture.isReady = true;
  6264. };
  6265. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6266. // old version had a "generateMipMaps" arg instead of options.
  6267. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6268. // in the same way, generateDepthBuffer is defaulted to true
  6269. var generateMipMaps = false;
  6270. var generateDepthBuffer = true;
  6271. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6272. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6273. if (options !== undefined) {
  6274. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6275. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6276. type = options.type === undefined ? type : options.type;
  6277. if (options.samplingMode !== undefined) {
  6278. samplingMode = options.samplingMode;
  6279. }
  6280. if (type === Engine.TEXTURETYPE_FLOAT) {
  6281. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6282. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6283. }
  6284. }
  6285. var gl = this._gl;
  6286. var texture = gl.createTexture();
  6287. gl.bindTexture(gl.TEXTURE_2D, texture);
  6288. var width = size.width || size;
  6289. var height = size.height || size;
  6290. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6291. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6292. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6293. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6294. }
  6295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6297. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6299. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6300. var depthBuffer;
  6301. // Create the depth buffer
  6302. if (generateDepthBuffer) {
  6303. depthBuffer = gl.createRenderbuffer();
  6304. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6305. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6306. }
  6307. // Create the framebuffer
  6308. var framebuffer = gl.createFramebuffer();
  6309. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6310. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6311. if (generateDepthBuffer) {
  6312. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6313. }
  6314. // Unbind
  6315. gl.bindTexture(gl.TEXTURE_2D, null);
  6316. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6317. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6318. texture._framebuffer = framebuffer;
  6319. if (generateDepthBuffer) {
  6320. texture._depthBuffer = depthBuffer;
  6321. }
  6322. texture._width = width;
  6323. texture._height = height;
  6324. texture.isReady = true;
  6325. texture.generateMipMaps = generateMipMaps;
  6326. texture.references = 1;
  6327. texture.samplingMode = samplingMode;
  6328. this._activeTexturesCache = [];
  6329. this._loadedTexturesCache.push(texture);
  6330. return texture;
  6331. };
  6332. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6333. var _this = this;
  6334. var gl = this._gl;
  6335. var texture = gl.createTexture();
  6336. texture.isCube = true;
  6337. texture.url = rootUrl;
  6338. texture.references = 1;
  6339. this._loadedTexturesCache.push(texture);
  6340. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6341. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6342. if (isDDS) {
  6343. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6344. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6345. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6346. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6347. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6348. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6349. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6350. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6351. }
  6352. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6353. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6354. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6356. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6357. _this._activeTexturesCache = [];
  6358. texture._width = info.width;
  6359. texture._height = info.height;
  6360. texture.isReady = true;
  6361. }, null, null, true);
  6362. }
  6363. else {
  6364. cascadeLoad(rootUrl, scene, function (imgs) {
  6365. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6366. var height = width;
  6367. _this._prepareWorkingCanvas();
  6368. _this._workingCanvas.width = width;
  6369. _this._workingCanvas.height = height;
  6370. var faces = [
  6371. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  6372. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  6373. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6374. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  6375. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  6376. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6377. ];
  6378. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6379. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6380. for (var index = 0; index < faces.length; index++) {
  6381. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6382. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6383. }
  6384. if (!noMipmap) {
  6385. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6386. }
  6387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6391. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6392. _this._activeTexturesCache = [];
  6393. texture._width = width;
  6394. texture._height = height;
  6395. texture.isReady = true;
  6396. }, extensions);
  6397. }
  6398. return texture;
  6399. };
  6400. Engine.prototype._releaseTexture = function (texture) {
  6401. var gl = this._gl;
  6402. if (texture._framebuffer) {
  6403. gl.deleteFramebuffer(texture._framebuffer);
  6404. }
  6405. if (texture._depthBuffer) {
  6406. gl.deleteRenderbuffer(texture._depthBuffer);
  6407. }
  6408. gl.deleteTexture(texture);
  6409. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6410. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6411. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6412. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6413. this._activeTexturesCache[channel] = null;
  6414. }
  6415. var index = this._loadedTexturesCache.indexOf(texture);
  6416. if (index !== -1) {
  6417. this._loadedTexturesCache.splice(index, 1);
  6418. }
  6419. };
  6420. Engine.prototype.bindSamplers = function (effect) {
  6421. this._gl.useProgram(effect.getProgram());
  6422. var samplers = effect.getSamplers();
  6423. for (var index = 0; index < samplers.length; index++) {
  6424. var uniform = effect.getUniform(samplers[index]);
  6425. this._gl.uniform1i(uniform, index);
  6426. }
  6427. this._currentEffect = null;
  6428. };
  6429. Engine.prototype._bindTexture = function (channel, texture) {
  6430. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6431. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6432. this._activeTexturesCache[channel] = null;
  6433. };
  6434. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6435. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6436. };
  6437. Engine.prototype.setTexture = function (channel, texture) {
  6438. if (channel < 0) {
  6439. return;
  6440. }
  6441. // Not ready?
  6442. if (!texture || !texture.isReady()) {
  6443. if (this._activeTexturesCache[channel] != null) {
  6444. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6445. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6446. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6447. this._activeTexturesCache[channel] = null;
  6448. }
  6449. return;
  6450. }
  6451. // Video
  6452. if (texture instanceof BABYLON.VideoTexture) {
  6453. if (texture.update()) {
  6454. this._activeTexturesCache[channel] = null;
  6455. }
  6456. }
  6457. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6458. texture.delayLoad();
  6459. return;
  6460. }
  6461. if (this._activeTexturesCache[channel] === texture) {
  6462. return;
  6463. }
  6464. this._activeTexturesCache[channel] = texture;
  6465. var internalTexture = texture.getInternalTexture();
  6466. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6467. if (internalTexture.isCube) {
  6468. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6469. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6470. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6471. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6472. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6473. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6474. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6475. }
  6476. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6477. }
  6478. else {
  6479. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6480. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6481. internalTexture._cachedWrapU = texture.wrapU;
  6482. switch (texture.wrapU) {
  6483. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6484. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6485. break;
  6486. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6487. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6488. break;
  6489. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6490. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6491. break;
  6492. }
  6493. }
  6494. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6495. internalTexture._cachedWrapV = texture.wrapV;
  6496. switch (texture.wrapV) {
  6497. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6498. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6499. break;
  6500. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6501. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6502. break;
  6503. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6504. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6505. break;
  6506. }
  6507. }
  6508. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6509. }
  6510. };
  6511. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6512. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6513. var value = texture.anisotropicFilteringLevel;
  6514. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6515. value = 1;
  6516. }
  6517. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6518. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6519. texture._cachedAnisotropicFilteringLevel = value;
  6520. }
  6521. };
  6522. Engine.prototype.readPixels = function (x, y, width, height) {
  6523. var data = new Uint8Array(height * width * 4);
  6524. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6525. return data;
  6526. };
  6527. // Dispose
  6528. Engine.prototype.dispose = function () {
  6529. this.hideLoadingUI();
  6530. this.stopRenderLoop();
  6531. while (this.scenes.length) {
  6532. this.scenes[0].dispose();
  6533. }
  6534. // Release audio engine
  6535. Engine.audioEngine.dispose();
  6536. for (var name in this._compiledEffects) {
  6537. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6538. }
  6539. for (var i in this._vertexAttribArrays) {
  6540. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6541. continue;
  6542. }
  6543. this._gl.disableVertexAttribArray(i);
  6544. }
  6545. // Events
  6546. window.removeEventListener("blur", this._onBlur);
  6547. window.removeEventListener("focus", this._onFocus);
  6548. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6549. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6550. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6551. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6552. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6553. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6554. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6555. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6556. };
  6557. // Loading screen
  6558. Engine.prototype.displayLoadingUI = function () {
  6559. var _this = this;
  6560. this._loadingDiv = document.createElement("div");
  6561. this._loadingDiv.style.opacity = "0";
  6562. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6563. // Loading text
  6564. this._loadingTextDiv = document.createElement("div");
  6565. this._loadingTextDiv.style.position = "absolute";
  6566. this._loadingTextDiv.style.left = "0";
  6567. this._loadingTextDiv.style.top = "50%";
  6568. this._loadingTextDiv.style.marginTop = "80px";
  6569. this._loadingTextDiv.style.width = "100%";
  6570. this._loadingTextDiv.style.height = "20px";
  6571. this._loadingTextDiv.style.fontFamily = "Arial";
  6572. this._loadingTextDiv.style.fontSize = "14px";
  6573. this._loadingTextDiv.style.color = "white";
  6574. this._loadingTextDiv.style.textAlign = "center";
  6575. this._loadingTextDiv.innerHTML = "Loading";
  6576. this._loadingDiv.appendChild(this._loadingTextDiv);
  6577. // Loading img
  6578. var imgBack = new Image();
  6579. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  6580. imgBack.style.position = "absolute";
  6581. imgBack.style.left = "50%";
  6582. imgBack.style.top = "50%";
  6583. imgBack.style.marginLeft = "-50px";
  6584. imgBack.style.marginTop = "-50px";
  6585. imgBack.style.transition = "transform 1.0s ease";
  6586. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6587. var deg = 360;
  6588. var onTransitionEnd = function () {
  6589. deg += 360;
  6590. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6591. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6592. };
  6593. imgBack.addEventListener("transitionend", onTransitionEnd);
  6594. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6595. this._loadingDiv.appendChild(imgBack);
  6596. // front image
  6597. var imgFront = new Image();
  6598. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  6599. imgFront.style.position = "absolute";
  6600. imgFront.style.left = "50%";
  6601. imgFront.style.top = "50%";
  6602. imgFront.style.marginLeft = "-50px";
  6603. imgFront.style.marginTop = "-50px";
  6604. this._loadingDiv.appendChild(imgFront);
  6605. // Resize
  6606. this._resizeLoadingUI = function () {
  6607. var canvasRect = _this.getRenderingCanvasClientRect();
  6608. _this._loadingDiv.style.position = "absolute";
  6609. _this._loadingDiv.style.left = canvasRect.left + "px";
  6610. _this._loadingDiv.style.top = canvasRect.top + "px";
  6611. _this._loadingDiv.style.width = canvasRect.width + "px";
  6612. _this._loadingDiv.style.height = canvasRect.height + "px";
  6613. };
  6614. this._resizeLoadingUI();
  6615. window.addEventListener("resize", this._resizeLoadingUI);
  6616. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6617. document.body.appendChild(this._loadingDiv);
  6618. setTimeout(function () {
  6619. _this._loadingDiv.style.opacity = "1";
  6620. imgBack.style.transform = "rotateZ(360deg)";
  6621. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6622. }, 0);
  6623. };
  6624. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6625. set: function (text) {
  6626. if (!this._loadingDiv) {
  6627. return;
  6628. }
  6629. this._loadingTextDiv.innerHTML = text;
  6630. },
  6631. enumerable: true,
  6632. configurable: true
  6633. });
  6634. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6635. get: function () {
  6636. return this._loadingDivBackgroundColor;
  6637. },
  6638. set: function (color) {
  6639. this._loadingDivBackgroundColor = color;
  6640. if (!this._loadingDiv) {
  6641. return;
  6642. }
  6643. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6644. },
  6645. enumerable: true,
  6646. configurable: true
  6647. });
  6648. Engine.prototype.hideLoadingUI = function () {
  6649. var _this = this;
  6650. if (!this._loadingDiv) {
  6651. return;
  6652. }
  6653. var onTransitionEnd = function () {
  6654. if (!_this._loadingDiv) {
  6655. return;
  6656. }
  6657. document.body.removeChild(_this._loadingDiv);
  6658. window.removeEventListener("resize", _this._resizeLoadingUI);
  6659. _this._loadingDiv = null;
  6660. };
  6661. this._loadingDiv.style.opacity = "0";
  6662. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6663. };
  6664. // FPS
  6665. Engine.prototype.getFps = function () {
  6666. return this.fps;
  6667. };
  6668. Engine.prototype.getDeltaTime = function () {
  6669. return this.deltaTime;
  6670. };
  6671. Engine.prototype._measureFps = function () {
  6672. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6673. var length = this.previousFramesDuration.length;
  6674. if (length >= 2) {
  6675. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6676. }
  6677. if (length >= this.fpsRange) {
  6678. if (length > this.fpsRange) {
  6679. this.previousFramesDuration.splice(0, 1);
  6680. length = this.previousFramesDuration.length;
  6681. }
  6682. var sum = 0;
  6683. for (var id = 0; id < length - 1; id++) {
  6684. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6685. }
  6686. this.fps = 1000.0 / (sum / (length - 1));
  6687. }
  6688. };
  6689. // Statics
  6690. Engine.isSupported = function () {
  6691. try {
  6692. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6693. if (navigator.isCocoonJS) {
  6694. return true;
  6695. }
  6696. var tempcanvas = document.createElement("canvas");
  6697. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6698. return gl != null && !!window.WebGLRenderingContext;
  6699. }
  6700. catch (e) {
  6701. return false;
  6702. }
  6703. };
  6704. // Const statics
  6705. Engine._ALPHA_DISABLE = 0;
  6706. Engine._ALPHA_ADD = 1;
  6707. Engine._ALPHA_COMBINE = 2;
  6708. Engine._DELAYLOADSTATE_NONE = 0;
  6709. Engine._DELAYLOADSTATE_LOADED = 1;
  6710. Engine._DELAYLOADSTATE_LOADING = 2;
  6711. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6712. Engine._TEXTUREFORMAT_ALPHA = 0;
  6713. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6714. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6715. Engine._TEXTUREFORMAT_RGB = 4;
  6716. Engine._TEXTUREFORMAT_RGBA = 4;
  6717. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6718. Engine._TEXTURETYPE_FLOAT = 1;
  6719. // Updatable statics so stick with vars here
  6720. Engine.Epsilon = 0.001;
  6721. Engine.CollisionsEpsilon = 0.001;
  6722. Engine.CodeRepository = "Babylon/";
  6723. Engine.ShadersRepository = "Babylon/Shaders/";
  6724. return Engine;
  6725. })();
  6726. BABYLON.Engine = Engine;
  6727. })(BABYLON || (BABYLON = {}));
  6728. //# sourceMappingURL=babylon.engine.js.map
  6729. var BABYLON;
  6730. (function (BABYLON) {
  6731. /**
  6732. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6733. */
  6734. var Node = (function () {
  6735. /**
  6736. * @constructor
  6737. * @param {string} name - the name and id to be given to this node
  6738. * @param {BABYLON.Scene} the scene this node will be added to
  6739. */
  6740. function Node(name, scene) {
  6741. this.state = "";
  6742. this.animations = new Array();
  6743. this._childrenFlag = -1;
  6744. this._isEnabled = true;
  6745. this._isReady = true;
  6746. this._currentRenderId = -1;
  6747. this._parentRenderId = -1;
  6748. this.name = name;
  6749. this.id = name;
  6750. this._scene = scene;
  6751. this._initCache();
  6752. }
  6753. Node.prototype.getScene = function () {
  6754. return this._scene;
  6755. };
  6756. Node.prototype.getEngine = function () {
  6757. return this._scene.getEngine();
  6758. };
  6759. // override it in derived class
  6760. Node.prototype.getWorldMatrix = function () {
  6761. return BABYLON.Matrix.Identity();
  6762. };
  6763. // override it in derived class if you add new variables to the cache
  6764. // and call the parent class method
  6765. Node.prototype._initCache = function () {
  6766. this._cache = {};
  6767. this._cache.parent = undefined;
  6768. };
  6769. Node.prototype.updateCache = function (force) {
  6770. if (!force && this.isSynchronized())
  6771. return;
  6772. this._cache.parent = this.parent;
  6773. this._updateCache();
  6774. };
  6775. // override it in derived class if you add new variables to the cache
  6776. // and call the parent class method if !ignoreParentClass
  6777. Node.prototype._updateCache = function (ignoreParentClass) {
  6778. };
  6779. // override it in derived class if you add new variables to the cache
  6780. Node.prototype._isSynchronized = function () {
  6781. return true;
  6782. };
  6783. Node.prototype._markSyncedWithParent = function () {
  6784. this._parentRenderId = this.parent._currentRenderId;
  6785. };
  6786. Node.prototype.isSynchronizedWithParent = function () {
  6787. if (!this.parent) {
  6788. return true;
  6789. }
  6790. if (this._parentRenderId !== this.parent._currentRenderId) {
  6791. return false;
  6792. }
  6793. return this.parent.isSynchronized();
  6794. };
  6795. Node.prototype.isSynchronized = function (updateCache) {
  6796. var check = this.hasNewParent();
  6797. check = check || !this.isSynchronizedWithParent();
  6798. check = check || !this._isSynchronized();
  6799. if (updateCache)
  6800. this.updateCache(true);
  6801. return !check;
  6802. };
  6803. Node.prototype.hasNewParent = function (update) {
  6804. if (this._cache.parent === this.parent)
  6805. return false;
  6806. if (update)
  6807. this._cache.parent = this.parent;
  6808. return true;
  6809. };
  6810. /**
  6811. * Is this node ready to be used/rendered
  6812. * @return {boolean} is it ready
  6813. */
  6814. Node.prototype.isReady = function () {
  6815. return this._isReady;
  6816. };
  6817. /**
  6818. * Is this node enabled.
  6819. * If the node has a parent and is enabled, the parent will be inspected as well.
  6820. * @return {boolean} whether this node (and its parent) is enabled.
  6821. * @see setEnabled
  6822. */
  6823. Node.prototype.isEnabled = function () {
  6824. if (!this._isEnabled) {
  6825. return false;
  6826. }
  6827. if (this.parent) {
  6828. return this.parent.isEnabled();
  6829. }
  6830. return true;
  6831. };
  6832. /**
  6833. * Set the enabled state of this node.
  6834. * @param {boolean} value - the new enabled state
  6835. * @see isEnabled
  6836. */
  6837. Node.prototype.setEnabled = function (value) {
  6838. this._isEnabled = value;
  6839. };
  6840. /**
  6841. * Is this node a descendant of the given node.
  6842. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6843. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6844. * @see parent
  6845. */
  6846. Node.prototype.isDescendantOf = function (ancestor) {
  6847. if (this.parent) {
  6848. if (this.parent === ancestor) {
  6849. return true;
  6850. }
  6851. return this.parent.isDescendantOf(ancestor);
  6852. }
  6853. return false;
  6854. };
  6855. Node.prototype._getDescendants = function (list, results) {
  6856. for (var index = 0; index < list.length; index++) {
  6857. var item = list[index];
  6858. if (item.isDescendantOf(this)) {
  6859. results.push(item);
  6860. }
  6861. }
  6862. };
  6863. /**
  6864. * Will return all nodes that have this node as parent.
  6865. * @return {BABYLON.Node[]} all children nodes of all types.
  6866. */
  6867. Node.prototype.getDescendants = function () {
  6868. var results = [];
  6869. this._getDescendants(this._scene.meshes, results);
  6870. this._getDescendants(this._scene.lights, results);
  6871. this._getDescendants(this._scene.cameras, results);
  6872. return results;
  6873. };
  6874. Node.prototype._setReady = function (state) {
  6875. if (state == this._isReady) {
  6876. return;
  6877. }
  6878. if (!state) {
  6879. this._isReady = false;
  6880. return;
  6881. }
  6882. this._isReady = true;
  6883. if (this.onReady) {
  6884. this.onReady(this);
  6885. }
  6886. };
  6887. return Node;
  6888. })();
  6889. BABYLON.Node = Node;
  6890. })(BABYLON || (BABYLON = {}));
  6891. //# sourceMappingURL=babylon.node.js.map
  6892. var BABYLON;
  6893. (function (BABYLON) {
  6894. var FilesInput = (function () {
  6895. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6896. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6897. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6898. this._engine = p_engine;
  6899. this._canvas = p_canvas;
  6900. this._currentScene = p_scene;
  6901. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6902. this._progressCallback = p_progressCallback;
  6903. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6904. this._textureLoadingCallback = p_textureLoadingCallback;
  6905. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6906. }
  6907. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6908. var _this = this;
  6909. if (p_elementToMonitor) {
  6910. this._elementToMonitor = p_elementToMonitor;
  6911. this._elementToMonitor.addEventListener("dragenter", function (e) {
  6912. _this.drag(e);
  6913. }, false);
  6914. this._elementToMonitor.addEventListener("dragover", function (e) {
  6915. _this.drag(e);
  6916. }, false);
  6917. this._elementToMonitor.addEventListener("drop", function (e) {
  6918. _this.drop(e);
  6919. }, false);
  6920. }
  6921. };
  6922. FilesInput.prototype.renderFunction = function () {
  6923. if (this._additionnalRenderLoopLogicCallback) {
  6924. this._additionnalRenderLoopLogicCallback();
  6925. }
  6926. if (this._currentScene) {
  6927. if (this._textureLoadingCallback) {
  6928. var remaining = this._currentScene.getWaitingItemsCount();
  6929. if (remaining > 0) {
  6930. this._textureLoadingCallback(remaining);
  6931. }
  6932. }
  6933. this._currentScene.render();
  6934. }
  6935. };
  6936. FilesInput.prototype.drag = function (e) {
  6937. e.stopPropagation();
  6938. e.preventDefault();
  6939. };
  6940. FilesInput.prototype.drop = function (eventDrop) {
  6941. eventDrop.stopPropagation();
  6942. eventDrop.preventDefault();
  6943. this.loadFiles(eventDrop);
  6944. };
  6945. FilesInput.prototype.loadFiles = function (event) {
  6946. if (this._startingProcessingFilesCallback)
  6947. this._startingProcessingFilesCallback();
  6948. // Handling data transfer via drag'n'drop
  6949. if (event && event.dataTransfer && event.dataTransfer.files) {
  6950. this._filesToLoad = event.dataTransfer.files;
  6951. }
  6952. // Handling files from input files
  6953. if (event && event.target && event.target.files) {
  6954. this._filesToLoad = event.target.files;
  6955. }
  6956. if (this._filesToLoad && this._filesToLoad.length > 0) {
  6957. for (var i = 0; i < this._filesToLoad.length; i++) {
  6958. switch (this._filesToLoad[i].type) {
  6959. case "image/jpeg":
  6960. case "image/png":
  6961. case "image/bmp":
  6962. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  6963. break;
  6964. case "image/targa":
  6965. case "image/vnd.ms-dds":
  6966. case "audio/wav":
  6967. case "audio/x-wav":
  6968. case "audio/mp3":
  6969. case "audio/mpeg":
  6970. case "audio/mpeg3":
  6971. case "audio/x-mpeg-3":
  6972. case "audio/ogg":
  6973. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  6974. break;
  6975. default:
  6976. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  6977. this._sceneFileToLoad = this._filesToLoad[i];
  6978. }
  6979. break;
  6980. }
  6981. }
  6982. this.reload();
  6983. }
  6984. };
  6985. FilesInput.prototype.reload = function () {
  6986. var _this = this;
  6987. var that = this;
  6988. // If a ".babylon" file has been provided
  6989. if (this._sceneFileToLoad) {
  6990. if (this._currentScene) {
  6991. this._engine.stopRenderLoop();
  6992. this._currentScene.dispose();
  6993. }
  6994. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  6995. that._currentScene = newScene;
  6996. // Wait for textures and shaders to be ready
  6997. that._currentScene.executeWhenReady(function () {
  6998. // Attach camera to canvas inputs
  6999. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7000. that._currentScene.createDefaultCameraOrLight();
  7001. }
  7002. that._currentScene.activeCamera.attachControl(that._canvas);
  7003. if (that._sceneLoadedCallback) {
  7004. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7005. }
  7006. that._engine.runRenderLoop(function () {
  7007. that.renderFunction();
  7008. });
  7009. });
  7010. }, function (progress) {
  7011. if (_this._progressCallback) {
  7012. _this._progressCallback(progress);
  7013. }
  7014. });
  7015. }
  7016. else {
  7017. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7018. }
  7019. };
  7020. FilesInput.FilesTextures = new Array();
  7021. FilesInput.FilesToLoad = new Array();
  7022. return FilesInput;
  7023. })();
  7024. BABYLON.FilesInput = FilesInput;
  7025. })(BABYLON || (BABYLON = {}));
  7026. //# sourceMappingURL=babylon.filesInput.js.map
  7027. var BABYLON;
  7028. (function (BABYLON) {
  7029. var IntersectionInfo = (function () {
  7030. function IntersectionInfo(bu, bv, distance) {
  7031. this.bu = bu;
  7032. this.bv = bv;
  7033. this.distance = distance;
  7034. this.faceId = 0;
  7035. this.subMeshId = 0;
  7036. }
  7037. return IntersectionInfo;
  7038. })();
  7039. BABYLON.IntersectionInfo = IntersectionInfo;
  7040. var PickingInfo = (function () {
  7041. function PickingInfo() {
  7042. this.hit = false;
  7043. this.distance = 0;
  7044. this.pickedPoint = null;
  7045. this.pickedMesh = null;
  7046. this.bu = 0;
  7047. this.bv = 0;
  7048. this.faceId = -1;
  7049. this.subMeshId = 0;
  7050. }
  7051. // Methods
  7052. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7053. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7054. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7055. return null;
  7056. }
  7057. var indices = this.pickedMesh.getIndices();
  7058. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7059. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7060. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7061. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7062. normal0 = normal0.scale(this.bu);
  7063. normal1 = normal1.scale(this.bv);
  7064. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7065. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7066. if (useWorldCoordinates) {
  7067. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7068. }
  7069. return result;
  7070. };
  7071. PickingInfo.prototype.getTextureCoordinates = function () {
  7072. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7073. return null;
  7074. }
  7075. var indices = this.pickedMesh.getIndices();
  7076. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7077. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7078. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7079. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7080. uv0 = uv0.scale(this.bu);
  7081. uv1 = uv1.scale(this.bv);
  7082. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7083. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7084. };
  7085. return PickingInfo;
  7086. })();
  7087. BABYLON.PickingInfo = PickingInfo;
  7088. })(BABYLON || (BABYLON = {}));
  7089. //# sourceMappingURL=babylon.pickingInfo.js.map
  7090. var BABYLON;
  7091. (function (BABYLON) {
  7092. var BoundingSphere = (function () {
  7093. function BoundingSphere(minimum, maximum) {
  7094. this.minimum = minimum;
  7095. this.maximum = maximum;
  7096. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7097. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7098. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7099. this.radius = distance * 0.5;
  7100. this.centerWorld = BABYLON.Vector3.Zero();
  7101. this._update(BABYLON.Matrix.Identity());
  7102. }
  7103. // Methods
  7104. BoundingSphere.prototype._update = function (world) {
  7105. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7106. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7107. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7108. };
  7109. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7110. for (var i = 0; i < 6; i++) {
  7111. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7112. return false;
  7113. }
  7114. return true;
  7115. };
  7116. BoundingSphere.prototype.intersectsPoint = function (point) {
  7117. var x = this.centerWorld.x - point.x;
  7118. var y = this.centerWorld.y - point.y;
  7119. var z = this.centerWorld.z - point.z;
  7120. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7121. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7122. return false;
  7123. return true;
  7124. };
  7125. // Statics
  7126. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7127. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7128. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7129. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7130. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7131. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7132. return false;
  7133. return true;
  7134. };
  7135. return BoundingSphere;
  7136. })();
  7137. BABYLON.BoundingSphere = BoundingSphere;
  7138. })(BABYLON || (BABYLON = {}));
  7139. //# sourceMappingURL=babylon.boundingSphere.js.map
  7140. var BABYLON;
  7141. (function (BABYLON) {
  7142. var BoundingBox = (function () {
  7143. function BoundingBox(minimum, maximum) {
  7144. this.minimum = minimum;
  7145. this.maximum = maximum;
  7146. this.vectors = new Array();
  7147. this.vectorsWorld = new Array();
  7148. // Bounding vectors
  7149. this.vectors.push(this.minimum.clone());
  7150. this.vectors.push(this.maximum.clone());
  7151. this.vectors.push(this.minimum.clone());
  7152. this.vectors[2].x = this.maximum.x;
  7153. this.vectors.push(this.minimum.clone());
  7154. this.vectors[3].y = this.maximum.y;
  7155. this.vectors.push(this.minimum.clone());
  7156. this.vectors[4].z = this.maximum.z;
  7157. this.vectors.push(this.maximum.clone());
  7158. this.vectors[5].z = this.minimum.z;
  7159. this.vectors.push(this.maximum.clone());
  7160. this.vectors[6].x = this.minimum.x;
  7161. this.vectors.push(this.maximum.clone());
  7162. this.vectors[7].y = this.minimum.y;
  7163. // OBB
  7164. this.center = this.maximum.add(this.minimum).scale(0.5);
  7165. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7166. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7167. for (var index = 0; index < this.vectors.length; index++) {
  7168. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7169. }
  7170. this.minimumWorld = BABYLON.Vector3.Zero();
  7171. this.maximumWorld = BABYLON.Vector3.Zero();
  7172. this._update(BABYLON.Matrix.Identity());
  7173. }
  7174. // Methods
  7175. BoundingBox.prototype.getWorldMatrix = function () {
  7176. return this._worldMatrix;
  7177. };
  7178. BoundingBox.prototype._update = function (world) {
  7179. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7180. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7181. for (var index = 0; index < this.vectors.length; index++) {
  7182. var v = this.vectorsWorld[index];
  7183. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7184. if (v.x < this.minimumWorld.x)
  7185. this.minimumWorld.x = v.x;
  7186. if (v.y < this.minimumWorld.y)
  7187. this.minimumWorld.y = v.y;
  7188. if (v.z < this.minimumWorld.z)
  7189. this.minimumWorld.z = v.z;
  7190. if (v.x > this.maximumWorld.x)
  7191. this.maximumWorld.x = v.x;
  7192. if (v.y > this.maximumWorld.y)
  7193. this.maximumWorld.y = v.y;
  7194. if (v.z > this.maximumWorld.z)
  7195. this.maximumWorld.z = v.z;
  7196. }
  7197. // OBB
  7198. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7199. this.center.scaleInPlace(0.5);
  7200. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7201. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7202. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7203. this._worldMatrix = world;
  7204. };
  7205. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7206. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7207. };
  7208. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7209. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7210. };
  7211. BoundingBox.prototype.intersectsPoint = function (point) {
  7212. var delta = -BABYLON.Engine.Epsilon;
  7213. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7214. return false;
  7215. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7216. return false;
  7217. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7218. return false;
  7219. return true;
  7220. };
  7221. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7222. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7223. };
  7224. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7225. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7226. return false;
  7227. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7228. return false;
  7229. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7230. return false;
  7231. return true;
  7232. };
  7233. // Statics
  7234. BoundingBox.Intersects = function (box0, box1) {
  7235. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7236. return false;
  7237. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7238. return false;
  7239. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7240. return false;
  7241. return true;
  7242. };
  7243. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7244. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7245. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7246. return (num <= (sphereRadius * sphereRadius));
  7247. };
  7248. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7249. for (var p = 0; p < 6; p++) {
  7250. for (var i = 0; i < 8; i++) {
  7251. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7252. return false;
  7253. }
  7254. }
  7255. }
  7256. return true;
  7257. };
  7258. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7259. for (var p = 0; p < 6; p++) {
  7260. var inCount = 8;
  7261. for (var i = 0; i < 8; i++) {
  7262. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7263. --inCount;
  7264. }
  7265. else {
  7266. break;
  7267. }
  7268. }
  7269. if (inCount === 0)
  7270. return false;
  7271. }
  7272. return true;
  7273. };
  7274. return BoundingBox;
  7275. })();
  7276. BABYLON.BoundingBox = BoundingBox;
  7277. })(BABYLON || (BABYLON = {}));
  7278. //# sourceMappingURL=babylon.boundingBox.js.map
  7279. var BABYLON;
  7280. (function (BABYLON) {
  7281. var computeBoxExtents = function (axis, box) {
  7282. var p = BABYLON.Vector3.Dot(box.center, axis);
  7283. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7284. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7285. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7286. var r = r0 + r1 + r2;
  7287. return {
  7288. min: p - r,
  7289. max: p + r
  7290. };
  7291. };
  7292. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7293. var axisOverlap = function (axis, box0, box1) {
  7294. var result0 = computeBoxExtents(axis, box0);
  7295. var result1 = computeBoxExtents(axis, box1);
  7296. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7297. };
  7298. var BoundingInfo = (function () {
  7299. function BoundingInfo(minimum, maximum) {
  7300. this.minimum = minimum;
  7301. this.maximum = maximum;
  7302. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7303. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7304. }
  7305. // Methods
  7306. BoundingInfo.prototype._update = function (world) {
  7307. this.boundingBox._update(world);
  7308. this.boundingSphere._update(world);
  7309. };
  7310. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7311. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7312. return false;
  7313. return this.boundingBox.isInFrustum(frustumPlanes);
  7314. };
  7315. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7316. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7317. };
  7318. BoundingInfo.prototype._checkCollision = function (collider) {
  7319. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7320. };
  7321. BoundingInfo.prototype.intersectsPoint = function (point) {
  7322. if (!this.boundingSphere.centerWorld) {
  7323. return false;
  7324. }
  7325. if (!this.boundingSphere.intersectsPoint(point)) {
  7326. return false;
  7327. }
  7328. if (!this.boundingBox.intersectsPoint(point)) {
  7329. return false;
  7330. }
  7331. return true;
  7332. };
  7333. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7334. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7335. return false;
  7336. }
  7337. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7338. return false;
  7339. }
  7340. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7341. return false;
  7342. }
  7343. if (!precise) {
  7344. return true;
  7345. }
  7346. var box0 = this.boundingBox;
  7347. var box1 = boundingInfo.boundingBox;
  7348. if (!axisOverlap(box0.directions[0], box0, box1))
  7349. return false;
  7350. if (!axisOverlap(box0.directions[1], box0, box1))
  7351. return false;
  7352. if (!axisOverlap(box0.directions[2], box0, box1))
  7353. return false;
  7354. if (!axisOverlap(box1.directions[0], box0, box1))
  7355. return false;
  7356. if (!axisOverlap(box1.directions[1], box0, box1))
  7357. return false;
  7358. if (!axisOverlap(box1.directions[2], box0, box1))
  7359. return false;
  7360. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7361. return false;
  7362. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7363. return false;
  7364. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7365. return false;
  7366. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7367. return false;
  7368. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7369. return false;
  7370. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7371. return false;
  7372. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7373. return false;
  7374. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7375. return false;
  7376. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7377. return false;
  7378. return true;
  7379. };
  7380. return BoundingInfo;
  7381. })();
  7382. BABYLON.BoundingInfo = BoundingInfo;
  7383. })(BABYLON || (BABYLON = {}));
  7384. //# sourceMappingURL=babylon.boundingInfo.js.map
  7385. var __extends = this.__extends || function (d, b) {
  7386. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7387. function __() { this.constructor = d; }
  7388. __.prototype = b.prototype;
  7389. d.prototype = new __();
  7390. };
  7391. var BABYLON;
  7392. (function (BABYLON) {
  7393. var AbstractMesh = (function (_super) {
  7394. __extends(AbstractMesh, _super);
  7395. function AbstractMesh(name, scene) {
  7396. var _this = this;
  7397. _super.call(this, name, scene);
  7398. // Properties
  7399. this.definedFacingForward = true; // orientation for POV movement & rotation
  7400. this.position = new BABYLON.Vector3(0, 0, 0);
  7401. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7402. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7403. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7404. this.visibility = 1.0;
  7405. this.alphaIndex = Number.MAX_VALUE;
  7406. this.infiniteDistance = false;
  7407. this.isVisible = true;
  7408. this.isPickable = true;
  7409. this.showBoundingBox = false;
  7410. this.showSubMeshesBoundingBox = false;
  7411. this.onDispose = null;
  7412. this.checkCollisions = false;
  7413. this.isBlocker = false;
  7414. this.renderingGroupId = 0;
  7415. this.receiveShadows = false;
  7416. this.renderOutline = false;
  7417. this.outlineColor = BABYLON.Color3.Red();
  7418. this.outlineWidth = 0.02;
  7419. this.renderOverlay = false;
  7420. this.overlayColor = BABYLON.Color3.Red();
  7421. this.overlayAlpha = 0.5;
  7422. this.hasVertexAlpha = false;
  7423. this.useVertexColors = true;
  7424. this.applyFog = true;
  7425. this.useOctreeForRenderingSelection = true;
  7426. this.useOctreeForPicking = true;
  7427. this.useOctreeForCollisions = true;
  7428. this.layerMask = 0x0FFFFFFF;
  7429. this.alwaysSelectAsActiveMesh = false;
  7430. // Physics
  7431. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7432. // Collisions
  7433. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7434. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7435. this._collider = new BABYLON.Collider();
  7436. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7437. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7438. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7439. // Cache
  7440. this._localScaling = BABYLON.Matrix.Zero();
  7441. this._localRotation = BABYLON.Matrix.Zero();
  7442. this._localTranslation = BABYLON.Matrix.Zero();
  7443. this._localBillboard = BABYLON.Matrix.Zero();
  7444. this._localPivotScaling = BABYLON.Matrix.Zero();
  7445. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7446. this._localWorld = BABYLON.Matrix.Zero();
  7447. this._worldMatrix = BABYLON.Matrix.Zero();
  7448. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7449. this._absolutePosition = BABYLON.Vector3.Zero();
  7450. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7451. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7452. this._isDirty = false;
  7453. this._pivotMatrix = BABYLON.Matrix.Identity();
  7454. this._isDisposed = false;
  7455. this._renderId = 0;
  7456. this._intersectionsInProgress = new Array();
  7457. this._onAfterWorldMatrixUpdate = new Array();
  7458. this._isWorldMatrixFrozen = false;
  7459. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7460. if (collidedMesh === void 0) { collidedMesh = null; }
  7461. //TODO move this to the collision coordinator!
  7462. if (collisionId != null || collisionId != undefined)
  7463. newPosition.multiplyInPlace(_this._collider.radius);
  7464. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7465. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7466. _this.position.addInPlace(_this._diffPositionForCollisions);
  7467. }
  7468. };
  7469. scene.addMesh(this);
  7470. }
  7471. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7472. get: function () {
  7473. return AbstractMesh._BILLBOARDMODE_NONE;
  7474. },
  7475. enumerable: true,
  7476. configurable: true
  7477. });
  7478. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7479. get: function () {
  7480. return AbstractMesh._BILLBOARDMODE_X;
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7486. get: function () {
  7487. return AbstractMesh._BILLBOARDMODE_Y;
  7488. },
  7489. enumerable: true,
  7490. configurable: true
  7491. });
  7492. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7493. get: function () {
  7494. return AbstractMesh._BILLBOARDMODE_Z;
  7495. },
  7496. enumerable: true,
  7497. configurable: true
  7498. });
  7499. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7500. get: function () {
  7501. return AbstractMesh._BILLBOARDMODE_ALL;
  7502. },
  7503. enumerable: true,
  7504. configurable: true
  7505. });
  7506. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7507. // Methods
  7508. get: function () {
  7509. return false;
  7510. },
  7511. enumerable: true,
  7512. configurable: true
  7513. });
  7514. AbstractMesh.prototype.getLOD = function (camera) {
  7515. return this;
  7516. };
  7517. AbstractMesh.prototype.getTotalVertices = function () {
  7518. return 0;
  7519. };
  7520. AbstractMesh.prototype.getIndices = function () {
  7521. return null;
  7522. };
  7523. AbstractMesh.prototype.getVerticesData = function (kind) {
  7524. return null;
  7525. };
  7526. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7527. return false;
  7528. };
  7529. AbstractMesh.prototype.getBoundingInfo = function () {
  7530. if (this._masterMesh) {
  7531. return this._masterMesh.getBoundingInfo();
  7532. }
  7533. if (!this._boundingInfo) {
  7534. this._updateBoundingInfo();
  7535. }
  7536. return this._boundingInfo;
  7537. };
  7538. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7539. get: function () {
  7540. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. AbstractMesh.prototype._preActivate = function () {
  7546. };
  7547. AbstractMesh.prototype._activate = function (renderId) {
  7548. this._renderId = renderId;
  7549. };
  7550. AbstractMesh.prototype.getWorldMatrix = function () {
  7551. if (this._masterMesh) {
  7552. return this._masterMesh.getWorldMatrix();
  7553. }
  7554. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7555. this.computeWorldMatrix();
  7556. }
  7557. return this._worldMatrix;
  7558. };
  7559. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7560. get: function () {
  7561. return this._worldMatrix;
  7562. },
  7563. enumerable: true,
  7564. configurable: true
  7565. });
  7566. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7567. get: function () {
  7568. return this._absolutePosition;
  7569. },
  7570. enumerable: true,
  7571. configurable: true
  7572. });
  7573. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7574. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7575. this.computeWorldMatrix(true);
  7576. this._isWorldMatrixFrozen = true;
  7577. };
  7578. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7579. this._isWorldMatrixFrozen = false;
  7580. this.computeWorldMatrix(true);
  7581. };
  7582. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7583. get: function () {
  7584. return this._isWorldMatrixFrozen;
  7585. },
  7586. enumerable: true,
  7587. configurable: true
  7588. });
  7589. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7590. if (!this.rotationQuaternion) {
  7591. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7592. this.rotation = BABYLON.Vector3.Zero();
  7593. }
  7594. if (!space || space === 0 /* LOCAL */) {
  7595. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7596. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7597. }
  7598. else {
  7599. if (this.parent) {
  7600. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7601. invertParentWorldMatrix.invert();
  7602. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7603. }
  7604. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7605. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7606. }
  7607. };
  7608. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7609. var displacementVector = axis.scale(distance);
  7610. if (!space || space === 0 /* LOCAL */) {
  7611. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7612. this.setPositionWithLocalVector(tempV3);
  7613. }
  7614. else {
  7615. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7616. }
  7617. };
  7618. AbstractMesh.prototype.getAbsolutePosition = function () {
  7619. this.computeWorldMatrix();
  7620. return this._absolutePosition;
  7621. };
  7622. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7623. if (!absolutePosition) {
  7624. return;
  7625. }
  7626. var absolutePositionX;
  7627. var absolutePositionY;
  7628. var absolutePositionZ;
  7629. if (absolutePosition.x === undefined) {
  7630. if (arguments.length < 3) {
  7631. return;
  7632. }
  7633. absolutePositionX = arguments[0];
  7634. absolutePositionY = arguments[1];
  7635. absolutePositionZ = arguments[2];
  7636. }
  7637. else {
  7638. absolutePositionX = absolutePosition.x;
  7639. absolutePositionY = absolutePosition.y;
  7640. absolutePositionZ = absolutePosition.z;
  7641. }
  7642. if (this.parent) {
  7643. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7644. invertParentWorldMatrix.invert();
  7645. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7646. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7647. }
  7648. else {
  7649. this.position.x = absolutePositionX;
  7650. this.position.y = absolutePositionY;
  7651. this.position.z = absolutePositionZ;
  7652. }
  7653. };
  7654. // ================================== Point of View Movement =================================
  7655. /**
  7656. * Perform relative position change from the point of view of behind the front of the mesh.
  7657. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7658. * Supports definition of mesh facing forward or backward.
  7659. * @param {number} amountRight
  7660. * @param {number} amountUp
  7661. * @param {number} amountForward
  7662. */
  7663. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7664. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7665. };
  7666. /**
  7667. * Calculate relative position change from the point of view of behind the front of the mesh.
  7668. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7669. * Supports definition of mesh facing forward or backward.
  7670. * @param {number} amountRight
  7671. * @param {number} amountUp
  7672. * @param {number} amountForward
  7673. */
  7674. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7675. var rotMatrix = new BABYLON.Matrix();
  7676. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7677. rotQuaternion.toRotationMatrix(rotMatrix);
  7678. var translationDelta = BABYLON.Vector3.Zero();
  7679. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7680. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7681. return translationDelta;
  7682. };
  7683. // ================================== Point of View Rotation =================================
  7684. /**
  7685. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7686. * Supports definition of mesh facing forward or backward.
  7687. * @param {number} flipBack
  7688. * @param {number} twirlClockwise
  7689. * @param {number} tiltRight
  7690. */
  7691. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7692. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7693. };
  7694. /**
  7695. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7696. * Supports definition of mesh facing forward or backward.
  7697. * @param {number} flipBack
  7698. * @param {number} twirlClockwise
  7699. * @param {number} tiltRight
  7700. */
  7701. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7702. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7703. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7704. };
  7705. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7706. this._pivotMatrix = matrix;
  7707. this._cache.pivotMatrixUpdated = true;
  7708. };
  7709. AbstractMesh.prototype.getPivotMatrix = function () {
  7710. return this._pivotMatrix;
  7711. };
  7712. AbstractMesh.prototype._isSynchronized = function () {
  7713. if (this._isDirty) {
  7714. return false;
  7715. }
  7716. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7717. return false;
  7718. if (this._cache.pivotMatrixUpdated) {
  7719. return false;
  7720. }
  7721. if (this.infiniteDistance) {
  7722. return false;
  7723. }
  7724. if (!this._cache.position.equals(this.position))
  7725. return false;
  7726. if (this.rotationQuaternion) {
  7727. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7728. return false;
  7729. }
  7730. else {
  7731. if (!this._cache.rotation.equals(this.rotation))
  7732. return false;
  7733. }
  7734. if (!this._cache.scaling.equals(this.scaling))
  7735. return false;
  7736. return true;
  7737. };
  7738. AbstractMesh.prototype._initCache = function () {
  7739. _super.prototype._initCache.call(this);
  7740. this._cache.localMatrixUpdated = false;
  7741. this._cache.position = BABYLON.Vector3.Zero();
  7742. this._cache.scaling = BABYLON.Vector3.Zero();
  7743. this._cache.rotation = BABYLON.Vector3.Zero();
  7744. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7745. };
  7746. AbstractMesh.prototype.markAsDirty = function (property) {
  7747. if (property === "rotation") {
  7748. this.rotationQuaternion = null;
  7749. }
  7750. this._currentRenderId = Number.MAX_VALUE;
  7751. this._isDirty = true;
  7752. };
  7753. AbstractMesh.prototype._updateBoundingInfo = function () {
  7754. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7755. this._boundingInfo._update(this.worldMatrixFromCache);
  7756. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7757. };
  7758. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7759. if (!this.subMeshes) {
  7760. return;
  7761. }
  7762. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7763. var subMesh = this.subMeshes[subIndex];
  7764. subMesh.updateBoundingInfo(matrix);
  7765. }
  7766. };
  7767. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7768. if (this._isWorldMatrixFrozen) {
  7769. return this._worldMatrix;
  7770. }
  7771. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7772. return this._worldMatrix;
  7773. }
  7774. this._cache.position.copyFrom(this.position);
  7775. this._cache.scaling.copyFrom(this.scaling);
  7776. this._cache.pivotMatrixUpdated = false;
  7777. this._currentRenderId = this.getScene().getRenderId();
  7778. this._isDirty = false;
  7779. // Scaling
  7780. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7781. // Rotation
  7782. if (this.rotationQuaternion) {
  7783. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7784. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7785. }
  7786. else {
  7787. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7788. this._cache.rotation.copyFrom(this.rotation);
  7789. }
  7790. // Translation
  7791. if (this.infiniteDistance && !this.parent) {
  7792. var camera = this.getScene().activeCamera;
  7793. var cameraWorldMatrix = camera.getWorldMatrix();
  7794. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7795. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7796. }
  7797. else {
  7798. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7799. }
  7800. // Composing transformations
  7801. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7802. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7803. // Billboarding
  7804. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7805. var localPosition = this.position.clone();
  7806. var zero = this.getScene().activeCamera.globalPosition.clone();
  7807. if (this.parent && this.parent.position) {
  7808. localPosition.addInPlace(this.parent.position);
  7809. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7810. }
  7811. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7812. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7813. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7814. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7815. zero.y = localPosition.y + 0.001;
  7816. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7817. zero.z = localPosition.z + 0.001;
  7818. }
  7819. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7820. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7821. this._localBillboard.invert();
  7822. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7823. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7824. }
  7825. // Local world
  7826. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7827. // Parent
  7828. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7829. this._markSyncedWithParent();
  7830. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7831. }
  7832. else {
  7833. this._worldMatrix.copyFrom(this._localWorld);
  7834. }
  7835. // Bounding info
  7836. this._updateBoundingInfo();
  7837. // Absolute position
  7838. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7839. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7840. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7841. }
  7842. return this._worldMatrix;
  7843. };
  7844. /**
  7845. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7846. * @param func: callback function to add
  7847. */
  7848. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7849. this._onAfterWorldMatrixUpdate.push(func);
  7850. };
  7851. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7852. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7853. if (index > -1) {
  7854. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7855. }
  7856. };
  7857. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7858. this.computeWorldMatrix();
  7859. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7860. };
  7861. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7862. this.computeWorldMatrix();
  7863. var invLocalWorldMatrix = this._localWorld.clone();
  7864. invLocalWorldMatrix.invert();
  7865. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7866. };
  7867. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7868. this.computeWorldMatrix();
  7869. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7870. };
  7871. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7872. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7873. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7874. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7875. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7876. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7877. /// <returns>Mesh oriented towards targetMesh</returns>
  7878. yawCor = yawCor || 0; // default to zero if undefined
  7879. pitchCor = pitchCor || 0;
  7880. rollCor = rollCor || 0;
  7881. var dv = targetPoint.subtract(this.position);
  7882. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7883. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7884. var pitch = Math.atan2(dv.y, len);
  7885. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7886. };
  7887. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7888. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7889. return false;
  7890. }
  7891. return true;
  7892. };
  7893. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7894. if (!camera) {
  7895. camera = this.getScene().activeCamera;
  7896. }
  7897. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7898. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7899. return false;
  7900. }
  7901. return true;
  7902. };
  7903. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7904. if (!this._boundingInfo || !mesh._boundingInfo) {
  7905. return false;
  7906. }
  7907. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7908. };
  7909. AbstractMesh.prototype.intersectsPoint = function (point) {
  7910. if (!this._boundingInfo) {
  7911. return false;
  7912. }
  7913. return this._boundingInfo.intersectsPoint(point);
  7914. };
  7915. // Physics
  7916. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7917. var physicsEngine = this.getScene().getPhysicsEngine();
  7918. if (!physicsEngine) {
  7919. return;
  7920. }
  7921. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7922. if (impostor.impostor) {
  7923. // Old API
  7924. options = impostor;
  7925. impostor = impostor.impostor;
  7926. }
  7927. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7928. physicsEngine._unregisterMesh(this);
  7929. return;
  7930. }
  7931. if (!options) {
  7932. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  7933. }
  7934. else {
  7935. if (!options.mass && options.mass !== 0)
  7936. options.mass = 0;
  7937. if (!options.friction && options.friction !== 0)
  7938. options.friction = 0.2;
  7939. if (!options.restitution && options.restitution !== 0)
  7940. options.restitution = 0.2;
  7941. }
  7942. this._physicImpostor = impostor;
  7943. this._physicsMass = options.mass;
  7944. this._physicsFriction = options.friction;
  7945. this._physicRestitution = options.restitution;
  7946. return physicsEngine._registerMesh(this, impostor, options);
  7947. };
  7948. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7949. if (!this._physicImpostor) {
  7950. return BABYLON.PhysicsEngine.NoImpostor;
  7951. }
  7952. return this._physicImpostor;
  7953. };
  7954. AbstractMesh.prototype.getPhysicsMass = function () {
  7955. if (!this._physicsMass) {
  7956. return 0;
  7957. }
  7958. return this._physicsMass;
  7959. };
  7960. AbstractMesh.prototype.getPhysicsFriction = function () {
  7961. if (!this._physicsFriction) {
  7962. return 0;
  7963. }
  7964. return this._physicsFriction;
  7965. };
  7966. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7967. if (!this._physicRestitution) {
  7968. return 0;
  7969. }
  7970. return this._physicRestitution;
  7971. };
  7972. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  7973. if (!camera) {
  7974. camera = this.getScene().activeCamera;
  7975. }
  7976. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  7977. };
  7978. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  7979. if (!camera) {
  7980. camera = this.getScene().activeCamera;
  7981. }
  7982. return this.absolutePosition.subtract(camera.position).length();
  7983. };
  7984. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7985. if (!this._physicImpostor) {
  7986. return;
  7987. }
  7988. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7989. };
  7990. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7991. if (!this._physicImpostor) {
  7992. return;
  7993. }
  7994. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7995. };
  7996. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7997. if (!this._physicImpostor) {
  7998. return;
  7999. }
  8000. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8001. };
  8002. // Collisions
  8003. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8004. var globalPosition = this.getAbsolutePosition();
  8005. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8006. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8007. this._collider.radius = this.ellipsoid;
  8008. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8009. };
  8010. // Submeshes octree
  8011. /**
  8012. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8013. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8014. */
  8015. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8016. if (maxCapacity === void 0) { maxCapacity = 64; }
  8017. if (maxDepth === void 0) { maxDepth = 2; }
  8018. if (!this._submeshesOctree) {
  8019. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8020. }
  8021. this.computeWorldMatrix(true);
  8022. // Update octree
  8023. var bbox = this.getBoundingInfo().boundingBox;
  8024. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8025. return this._submeshesOctree;
  8026. };
  8027. // Collisions
  8028. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8029. this._generatePointsArray();
  8030. // Transformation
  8031. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8032. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8033. subMesh._lastColliderWorldVertices = [];
  8034. subMesh._trianglePlanes = [];
  8035. var start = subMesh.verticesStart;
  8036. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8037. for (var i = start; i < end; i++) {
  8038. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8039. }
  8040. }
  8041. // Collide
  8042. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8043. if (collider.collisionFound) {
  8044. collider.collidedMesh = this;
  8045. }
  8046. };
  8047. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8048. var subMeshes;
  8049. var len;
  8050. // Octrees
  8051. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8052. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8053. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8054. len = intersections.length;
  8055. subMeshes = intersections.data;
  8056. }
  8057. else {
  8058. subMeshes = this.subMeshes;
  8059. len = subMeshes.length;
  8060. }
  8061. for (var index = 0; index < len; index++) {
  8062. var subMesh = subMeshes[index];
  8063. // Bounding test
  8064. if (len > 1 && !subMesh._checkCollision(collider))
  8065. continue;
  8066. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8067. }
  8068. };
  8069. AbstractMesh.prototype._checkCollision = function (collider) {
  8070. // Bounding box test
  8071. if (!this._boundingInfo._checkCollision(collider))
  8072. return;
  8073. // Transformation matrix
  8074. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8075. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8076. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8077. };
  8078. // Picking
  8079. AbstractMesh.prototype._generatePointsArray = function () {
  8080. return false;
  8081. };
  8082. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8083. var pickingInfo = new BABYLON.PickingInfo();
  8084. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8085. return pickingInfo;
  8086. }
  8087. if (!this._generatePointsArray()) {
  8088. return pickingInfo;
  8089. }
  8090. var intersectInfo = null;
  8091. // Octrees
  8092. var subMeshes;
  8093. var len;
  8094. if (this._submeshesOctree && this.useOctreeForPicking) {
  8095. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8096. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8097. len = intersections.length;
  8098. subMeshes = intersections.data;
  8099. }
  8100. else {
  8101. subMeshes = this.subMeshes;
  8102. len = subMeshes.length;
  8103. }
  8104. for (var index = 0; index < len; index++) {
  8105. var subMesh = subMeshes[index];
  8106. // Bounding test
  8107. if (len > 1 && !subMesh.canIntersects(ray))
  8108. continue;
  8109. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8110. if (currentIntersectInfo) {
  8111. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8112. intersectInfo = currentIntersectInfo;
  8113. intersectInfo.subMeshId = index;
  8114. if (fastCheck) {
  8115. break;
  8116. }
  8117. }
  8118. }
  8119. }
  8120. if (intersectInfo) {
  8121. // Get picked point
  8122. var world = this.getWorldMatrix();
  8123. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8124. var direction = ray.direction.clone();
  8125. direction = direction.scale(intersectInfo.distance);
  8126. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8127. var pickedPoint = worldOrigin.add(worldDirection);
  8128. // Return result
  8129. pickingInfo.hit = true;
  8130. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8131. pickingInfo.pickedPoint = pickedPoint;
  8132. pickingInfo.pickedMesh = this;
  8133. pickingInfo.bu = intersectInfo.bu;
  8134. pickingInfo.bv = intersectInfo.bv;
  8135. pickingInfo.faceId = intersectInfo.faceId;
  8136. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8137. return pickingInfo;
  8138. }
  8139. return pickingInfo;
  8140. };
  8141. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8142. return null;
  8143. };
  8144. AbstractMesh.prototype.releaseSubMeshes = function () {
  8145. if (this.subMeshes) {
  8146. while (this.subMeshes.length) {
  8147. this.subMeshes[0].dispose();
  8148. }
  8149. }
  8150. else {
  8151. this.subMeshes = new Array();
  8152. }
  8153. };
  8154. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8155. var index;
  8156. // Physics
  8157. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8158. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8159. }
  8160. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8161. var other = this._intersectionsInProgress[index];
  8162. var pos = other._intersectionsInProgress.indexOf(this);
  8163. other._intersectionsInProgress.splice(pos, 1);
  8164. }
  8165. this._intersectionsInProgress = [];
  8166. // SubMeshes
  8167. this.releaseSubMeshes();
  8168. // Remove from scene
  8169. this.getScene().removeMesh(this);
  8170. if (!doNotRecurse) {
  8171. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8172. if (this.getScene().particleSystems[index].emitter === this) {
  8173. this.getScene().particleSystems[index].dispose();
  8174. index--;
  8175. }
  8176. }
  8177. // Children
  8178. var objects = this.getScene().meshes.slice(0);
  8179. for (index = 0; index < objects.length; index++) {
  8180. if (objects[index].parent === this) {
  8181. objects[index].dispose();
  8182. }
  8183. }
  8184. }
  8185. else {
  8186. for (index = 0; index < this.getScene().meshes.length; index++) {
  8187. var obj = this.getScene().meshes[index];
  8188. if (obj.parent === this) {
  8189. obj.parent = null;
  8190. obj.computeWorldMatrix(true);
  8191. }
  8192. }
  8193. }
  8194. this._onAfterWorldMatrixUpdate = [];
  8195. this._isDisposed = true;
  8196. // Callback
  8197. if (this.onDispose) {
  8198. this.onDispose();
  8199. }
  8200. };
  8201. // Statics
  8202. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8203. AbstractMesh._BILLBOARDMODE_X = 1;
  8204. AbstractMesh._BILLBOARDMODE_Y = 2;
  8205. AbstractMesh._BILLBOARDMODE_Z = 4;
  8206. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8207. return AbstractMesh;
  8208. })(BABYLON.Node);
  8209. BABYLON.AbstractMesh = AbstractMesh;
  8210. })(BABYLON || (BABYLON = {}));
  8211. //# sourceMappingURL=babylon.abstractMesh.js.map
  8212. var __extends = this.__extends || function (d, b) {
  8213. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8214. function __() { this.constructor = d; }
  8215. __.prototype = b.prototype;
  8216. d.prototype = new __();
  8217. };
  8218. var BABYLON;
  8219. (function (BABYLON) {
  8220. var Light = (function (_super) {
  8221. __extends(Light, _super);
  8222. function Light(name, scene) {
  8223. _super.call(this, name, scene);
  8224. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8225. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8226. this.intensity = 1.0;
  8227. this.range = Number.MAX_VALUE;
  8228. this.includeOnlyWithLayerMask = 0;
  8229. this.includedOnlyMeshes = new Array();
  8230. this.excludedMeshes = new Array();
  8231. this.excludeWithLayerMask = 0;
  8232. this._excludedMeshesIds = new Array();
  8233. this._includedOnlyMeshesIds = new Array();
  8234. scene.addLight(this);
  8235. }
  8236. Light.prototype.getShadowGenerator = function () {
  8237. return this._shadowGenerator;
  8238. };
  8239. Light.prototype.getAbsolutePosition = function () {
  8240. return BABYLON.Vector3.Zero();
  8241. };
  8242. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8243. };
  8244. Light.prototype._getWorldMatrix = function () {
  8245. return BABYLON.Matrix.Identity();
  8246. };
  8247. Light.prototype.canAffectMesh = function (mesh) {
  8248. if (!mesh) {
  8249. return true;
  8250. }
  8251. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8252. return false;
  8253. }
  8254. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8255. return false;
  8256. }
  8257. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8258. return false;
  8259. }
  8260. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8261. return false;
  8262. }
  8263. return true;
  8264. };
  8265. Light.prototype.getWorldMatrix = function () {
  8266. this._currentRenderId = this.getScene().getRenderId();
  8267. var worldMatrix = this._getWorldMatrix();
  8268. if (this.parent && this.parent.getWorldMatrix) {
  8269. if (!this._parentedWorldMatrix) {
  8270. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8271. }
  8272. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8273. this._markSyncedWithParent();
  8274. return this._parentedWorldMatrix;
  8275. }
  8276. return worldMatrix;
  8277. };
  8278. Light.prototype.dispose = function () {
  8279. if (this._shadowGenerator) {
  8280. this._shadowGenerator.dispose();
  8281. this._shadowGenerator = null;
  8282. }
  8283. // Remove from scene
  8284. this.getScene().removeLight(this);
  8285. };
  8286. return Light;
  8287. })(BABYLON.Node);
  8288. BABYLON.Light = Light;
  8289. })(BABYLON || (BABYLON = {}));
  8290. //# sourceMappingURL=babylon.light.js.map
  8291. var __extends = this.__extends || function (d, b) {
  8292. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8293. function __() { this.constructor = d; }
  8294. __.prototype = b.prototype;
  8295. d.prototype = new __();
  8296. };
  8297. var BABYLON;
  8298. (function (BABYLON) {
  8299. var PointLight = (function (_super) {
  8300. __extends(PointLight, _super);
  8301. function PointLight(name, position, scene) {
  8302. _super.call(this, name, scene);
  8303. this.position = position;
  8304. }
  8305. PointLight.prototype.getAbsolutePosition = function () {
  8306. return this._transformedPosition ? this._transformedPosition : this.position;
  8307. };
  8308. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8309. if (this.parent && this.parent.getWorldMatrix) {
  8310. if (!this._transformedPosition) {
  8311. this._transformedPosition = BABYLON.Vector3.Zero();
  8312. }
  8313. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8314. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8315. return;
  8316. }
  8317. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8318. };
  8319. PointLight.prototype.getShadowGenerator = function () {
  8320. return null;
  8321. };
  8322. PointLight.prototype._getWorldMatrix = function () {
  8323. if (!this._worldMatrix) {
  8324. this._worldMatrix = BABYLON.Matrix.Identity();
  8325. }
  8326. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8327. return this._worldMatrix;
  8328. };
  8329. return PointLight;
  8330. })(BABYLON.Light);
  8331. BABYLON.PointLight = PointLight;
  8332. })(BABYLON || (BABYLON = {}));
  8333. //# sourceMappingURL=babylon.pointLight.js.map
  8334. var __extends = this.__extends || function (d, b) {
  8335. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8336. function __() { this.constructor = d; }
  8337. __.prototype = b.prototype;
  8338. d.prototype = new __();
  8339. };
  8340. var BABYLON;
  8341. (function (BABYLON) {
  8342. var SpotLight = (function (_super) {
  8343. __extends(SpotLight, _super);
  8344. function SpotLight(name, position, direction, angle, exponent, scene) {
  8345. _super.call(this, name, scene);
  8346. this.position = position;
  8347. this.direction = direction;
  8348. this.angle = angle;
  8349. this.exponent = exponent;
  8350. }
  8351. SpotLight.prototype.getAbsolutePosition = function () {
  8352. return this.transformedPosition ? this.transformedPosition : this.position;
  8353. };
  8354. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8355. var activeCamera = this.getScene().activeCamera;
  8356. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8357. };
  8358. SpotLight.prototype.supportsVSM = function () {
  8359. return true;
  8360. };
  8361. SpotLight.prototype.needRefreshPerFrame = function () {
  8362. return false;
  8363. };
  8364. SpotLight.prototype.setDirectionToTarget = function (target) {
  8365. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8366. return this.direction;
  8367. };
  8368. SpotLight.prototype.computeTransformedPosition = function () {
  8369. if (this.parent && this.parent.getWorldMatrix) {
  8370. if (!this.transformedPosition) {
  8371. this.transformedPosition = BABYLON.Vector3.Zero();
  8372. }
  8373. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8374. return true;
  8375. }
  8376. return false;
  8377. };
  8378. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8379. var normalizeDirection;
  8380. if (this.parent && this.parent.getWorldMatrix) {
  8381. if (!this._transformedDirection) {
  8382. this._transformedDirection = BABYLON.Vector3.Zero();
  8383. }
  8384. this.computeTransformedPosition();
  8385. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8386. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8387. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8388. }
  8389. else {
  8390. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8391. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8392. }
  8393. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8394. };
  8395. SpotLight.prototype._getWorldMatrix = function () {
  8396. if (!this._worldMatrix) {
  8397. this._worldMatrix = BABYLON.Matrix.Identity();
  8398. }
  8399. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8400. return this._worldMatrix;
  8401. };
  8402. return SpotLight;
  8403. })(BABYLON.Light);
  8404. BABYLON.SpotLight = SpotLight;
  8405. })(BABYLON || (BABYLON = {}));
  8406. //# sourceMappingURL=babylon.spotLight.js.map
  8407. var __extends = this.__extends || function (d, b) {
  8408. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8409. function __() { this.constructor = d; }
  8410. __.prototype = b.prototype;
  8411. d.prototype = new __();
  8412. };
  8413. var BABYLON;
  8414. (function (BABYLON) {
  8415. var HemisphericLight = (function (_super) {
  8416. __extends(HemisphericLight, _super);
  8417. function HemisphericLight(name, direction, scene) {
  8418. _super.call(this, name, scene);
  8419. this.direction = direction;
  8420. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8421. }
  8422. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8423. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8424. return this.direction;
  8425. };
  8426. HemisphericLight.prototype.getShadowGenerator = function () {
  8427. return null;
  8428. };
  8429. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8430. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8431. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8432. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8433. };
  8434. HemisphericLight.prototype._getWorldMatrix = function () {
  8435. if (!this._worldMatrix) {
  8436. this._worldMatrix = BABYLON.Matrix.Identity();
  8437. }
  8438. return this._worldMatrix;
  8439. };
  8440. return HemisphericLight;
  8441. })(BABYLON.Light);
  8442. BABYLON.HemisphericLight = HemisphericLight;
  8443. })(BABYLON || (BABYLON = {}));
  8444. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8445. var __extends = this.__extends || function (d, b) {
  8446. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8447. function __() { this.constructor = d; }
  8448. __.prototype = b.prototype;
  8449. d.prototype = new __();
  8450. };
  8451. var BABYLON;
  8452. (function (BABYLON) {
  8453. var DirectionalLight = (function (_super) {
  8454. __extends(DirectionalLight, _super);
  8455. function DirectionalLight(name, direction, scene) {
  8456. _super.call(this, name, scene);
  8457. this.direction = direction;
  8458. this.shadowOrthoScale = 0.5;
  8459. this.position = direction.scale(-1);
  8460. }
  8461. DirectionalLight.prototype.getAbsolutePosition = function () {
  8462. return this.transformedPosition ? this.transformedPosition : this.position;
  8463. };
  8464. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8465. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8466. return this.direction;
  8467. };
  8468. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8469. var orthoLeft = Number.MAX_VALUE;
  8470. var orthoRight = Number.MIN_VALUE;
  8471. var orthoTop = Number.MIN_VALUE;
  8472. var orthoBottom = Number.MAX_VALUE;
  8473. var tempVector3 = BABYLON.Vector3.Zero();
  8474. var activeCamera = this.getScene().activeCamera;
  8475. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8476. var mesh = renderList[meshIndex];
  8477. if (!mesh) {
  8478. continue;
  8479. }
  8480. var boundingInfo = mesh.getBoundingInfo();
  8481. if (!boundingInfo) {
  8482. continue;
  8483. }
  8484. var boundingBox = boundingInfo.boundingBox;
  8485. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8486. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8487. if (tempVector3.x < orthoLeft)
  8488. orthoLeft = tempVector3.x;
  8489. if (tempVector3.y < orthoBottom)
  8490. orthoBottom = tempVector3.y;
  8491. if (tempVector3.x > orthoRight)
  8492. orthoRight = tempVector3.x;
  8493. if (tempVector3.y > orthoTop)
  8494. orthoTop = tempVector3.y;
  8495. }
  8496. }
  8497. var xOffset = orthoRight - orthoLeft;
  8498. var yOffset = orthoTop - orthoBottom;
  8499. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8500. };
  8501. DirectionalLight.prototype.supportsVSM = function () {
  8502. return true;
  8503. };
  8504. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8505. return true;
  8506. };
  8507. DirectionalLight.prototype.computeTransformedPosition = function () {
  8508. if (this.parent && this.parent.getWorldMatrix) {
  8509. if (!this.transformedPosition) {
  8510. this.transformedPosition = BABYLON.Vector3.Zero();
  8511. }
  8512. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8513. return true;
  8514. }
  8515. return false;
  8516. };
  8517. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8518. if (this.parent && this.parent.getWorldMatrix) {
  8519. if (!this._transformedDirection) {
  8520. this._transformedDirection = BABYLON.Vector3.Zero();
  8521. }
  8522. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8523. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8524. return;
  8525. }
  8526. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8527. };
  8528. DirectionalLight.prototype._getWorldMatrix = function () {
  8529. if (!this._worldMatrix) {
  8530. this._worldMatrix = BABYLON.Matrix.Identity();
  8531. }
  8532. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8533. return this._worldMatrix;
  8534. };
  8535. return DirectionalLight;
  8536. })(BABYLON.Light);
  8537. BABYLON.DirectionalLight = DirectionalLight;
  8538. })(BABYLON || (BABYLON = {}));
  8539. //# sourceMappingURL=babylon.directionalLight.js.map
  8540. var BABYLON;
  8541. (function (BABYLON) {
  8542. var ShadowGenerator = (function () {
  8543. function ShadowGenerator(mapSize, light) {
  8544. var _this = this;
  8545. // Members
  8546. this._filter = ShadowGenerator.FILTER_NONE;
  8547. this.blurScale = 2;
  8548. this._blurBoxOffset = 0;
  8549. this._bias = 0.00005;
  8550. this._darkness = 0;
  8551. this._transparencyShadow = false;
  8552. this._viewMatrix = BABYLON.Matrix.Zero();
  8553. this._projectionMatrix = BABYLON.Matrix.Zero();
  8554. this._transformMatrix = BABYLON.Matrix.Zero();
  8555. this._worldViewProjection = BABYLON.Matrix.Zero();
  8556. this._light = light;
  8557. this._scene = light.getScene();
  8558. this._mapSize = mapSize;
  8559. light._shadowGenerator = this;
  8560. // Render target
  8561. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8562. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8563. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8564. this._shadowMap.anisotropicFilteringLevel = 1;
  8565. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8566. this._shadowMap.renderParticles = false;
  8567. this._shadowMap.onAfterUnbind = function () {
  8568. if (!_this.useBlurVarianceShadowMap) {
  8569. return;
  8570. }
  8571. if (!_this._shadowMap2) {
  8572. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8573. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8574. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8575. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8576. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8577. _this._downSamplePostprocess.onApply = function (effect) {
  8578. effect.setTexture("textureSampler", _this._shadowMap);
  8579. };
  8580. _this.blurBoxOffset = 1;
  8581. }
  8582. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8583. };
  8584. // Custom render function
  8585. var renderSubMesh = function (subMesh) {
  8586. var mesh = subMesh.getRenderingMesh();
  8587. var scene = _this._scene;
  8588. var engine = scene.getEngine();
  8589. // Culling
  8590. engine.setState(subMesh.getMaterial().backFaceCulling);
  8591. // Managing instances
  8592. var batch = mesh._getInstancesRenderList(subMesh._id);
  8593. if (batch.mustReturn) {
  8594. return;
  8595. }
  8596. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8597. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8598. engine.enableEffect(_this._effect);
  8599. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8600. var material = subMesh.getMaterial();
  8601. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8602. // Alpha test
  8603. if (material && material.needAlphaTesting()) {
  8604. var alphaTexture = material.getAlphaTestTexture();
  8605. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8606. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8607. }
  8608. // Bones
  8609. if (mesh.useBones) {
  8610. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8611. }
  8612. // Draw
  8613. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8614. }
  8615. else {
  8616. // Need to reset refresh rate of the shadowMap
  8617. _this._shadowMap.resetRefreshCounter();
  8618. }
  8619. };
  8620. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8621. var index;
  8622. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8623. renderSubMesh(opaqueSubMeshes.data[index]);
  8624. }
  8625. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8626. renderSubMesh(alphaTestSubMeshes.data[index]);
  8627. }
  8628. if (_this._transparencyShadow) {
  8629. for (index = 0; index < transparentSubMeshes.length; index++) {
  8630. renderSubMesh(transparentSubMeshes.data[index]);
  8631. }
  8632. }
  8633. };
  8634. this._shadowMap.onClear = function (engine) {
  8635. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8636. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8637. }
  8638. else {
  8639. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8640. }
  8641. };
  8642. }
  8643. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8644. // Static
  8645. get: function () {
  8646. return ShadowGenerator._FILTER_NONE;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8652. get: function () {
  8653. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8654. },
  8655. enumerable: true,
  8656. configurable: true
  8657. });
  8658. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8659. get: function () {
  8660. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8661. },
  8662. enumerable: true,
  8663. configurable: true
  8664. });
  8665. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8666. get: function () {
  8667. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8668. },
  8669. enumerable: true,
  8670. configurable: true
  8671. });
  8672. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8673. get: function () {
  8674. return this._bias;
  8675. },
  8676. set: function (bias) {
  8677. this._bias = bias;
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8683. get: function () {
  8684. return this._blurBoxOffset;
  8685. },
  8686. set: function (value) {
  8687. var _this = this;
  8688. if (this._blurBoxOffset === value) {
  8689. return;
  8690. }
  8691. this._blurBoxOffset = value;
  8692. if (this._boxBlurPostprocess) {
  8693. this._boxBlurPostprocess.dispose();
  8694. }
  8695. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  8696. this._boxBlurPostprocess.onApply = function (effect) {
  8697. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8698. };
  8699. },
  8700. enumerable: true,
  8701. configurable: true
  8702. });
  8703. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8704. get: function () {
  8705. return this._filter;
  8706. },
  8707. set: function (value) {
  8708. if (this._filter === value) {
  8709. return;
  8710. }
  8711. this._filter = value;
  8712. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8713. this._shadowMap.anisotropicFilteringLevel = 16;
  8714. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8715. }
  8716. else {
  8717. this._shadowMap.anisotropicFilteringLevel = 1;
  8718. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8719. }
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8725. get: function () {
  8726. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8727. },
  8728. set: function (value) {
  8729. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8730. },
  8731. enumerable: true,
  8732. configurable: true
  8733. });
  8734. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8735. get: function () {
  8736. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8737. },
  8738. set: function (value) {
  8739. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8740. },
  8741. enumerable: true,
  8742. configurable: true
  8743. });
  8744. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8745. get: function () {
  8746. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8747. },
  8748. set: function (value) {
  8749. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8750. },
  8751. enumerable: true,
  8752. configurable: true
  8753. });
  8754. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8755. var defines = [];
  8756. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8757. defines.push("#define VSM");
  8758. }
  8759. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8760. var mesh = subMesh.getMesh();
  8761. var material = subMesh.getMaterial();
  8762. // Alpha test
  8763. if (material && material.needAlphaTesting()) {
  8764. defines.push("#define ALPHATEST");
  8765. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8766. attribs.push(BABYLON.VertexBuffer.UVKind);
  8767. defines.push("#define UV1");
  8768. }
  8769. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8770. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8771. defines.push("#define UV2");
  8772. }
  8773. }
  8774. // Bones
  8775. if (mesh.useBones) {
  8776. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8777. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8778. defines.push("#define BONES");
  8779. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8780. }
  8781. // Instances
  8782. if (useInstances) {
  8783. defines.push("#define INSTANCES");
  8784. attribs.push("world0");
  8785. attribs.push("world1");
  8786. attribs.push("world2");
  8787. attribs.push("world3");
  8788. }
  8789. // Get correct effect
  8790. var join = defines.join("\n");
  8791. if (this._cachedDefines !== join) {
  8792. this._cachedDefines = join;
  8793. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8794. }
  8795. return this._effect.isReady();
  8796. };
  8797. ShadowGenerator.prototype.getShadowMap = function () {
  8798. return this._shadowMap;
  8799. };
  8800. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8801. if (this._shadowMap2) {
  8802. return this._shadowMap2;
  8803. }
  8804. return this._shadowMap;
  8805. };
  8806. ShadowGenerator.prototype.getLight = function () {
  8807. return this._light;
  8808. };
  8809. // Methods
  8810. ShadowGenerator.prototype.getTransformMatrix = function () {
  8811. var scene = this._scene;
  8812. if (this._currentRenderID === scene.getRenderId()) {
  8813. return this._transformMatrix;
  8814. }
  8815. this._currentRenderID = scene.getRenderId();
  8816. var lightPosition = this._light.position;
  8817. var lightDirection = this._light.direction;
  8818. if (this._light.computeTransformedPosition()) {
  8819. lightPosition = this._light.transformedPosition;
  8820. }
  8821. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8822. this._cachedPosition = lightPosition.clone();
  8823. this._cachedDirection = lightDirection.clone();
  8824. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8825. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8826. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8827. }
  8828. return this._transformMatrix;
  8829. };
  8830. ShadowGenerator.prototype.getDarkness = function () {
  8831. return this._darkness;
  8832. };
  8833. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8834. if (darkness >= 1.0)
  8835. this._darkness = 1.0;
  8836. else if (darkness <= 0.0)
  8837. this._darkness = 0.0;
  8838. else
  8839. this._darkness = darkness;
  8840. };
  8841. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8842. this._transparencyShadow = hasShadow;
  8843. };
  8844. ShadowGenerator.prototype._packHalf = function (depth) {
  8845. var scale = depth * 255.0;
  8846. var fract = scale - Math.floor(scale);
  8847. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8848. };
  8849. ShadowGenerator.prototype.dispose = function () {
  8850. this._shadowMap.dispose();
  8851. if (this._shadowMap2) {
  8852. this._shadowMap2.dispose();
  8853. }
  8854. if (this._downSamplePostprocess) {
  8855. this._downSamplePostprocess.dispose();
  8856. }
  8857. if (this._boxBlurPostprocess) {
  8858. this._boxBlurPostprocess.dispose();
  8859. }
  8860. };
  8861. ShadowGenerator._FILTER_NONE = 0;
  8862. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8863. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8864. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8865. return ShadowGenerator;
  8866. })();
  8867. BABYLON.ShadowGenerator = ShadowGenerator;
  8868. })(BABYLON || (BABYLON = {}));
  8869. //# sourceMappingURL=babylon.shadowGenerator.js.map
  8870. var BABYLON;
  8871. (function (BABYLON) {
  8872. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8873. if (boxMin.x > sphereCenter.x + sphereRadius)
  8874. return false;
  8875. if (sphereCenter.x - sphereRadius > boxMax.x)
  8876. return false;
  8877. if (boxMin.y > sphereCenter.y + sphereRadius)
  8878. return false;
  8879. if (sphereCenter.y - sphereRadius > boxMax.y)
  8880. return false;
  8881. if (boxMin.z > sphereCenter.z + sphereRadius)
  8882. return false;
  8883. if (sphereCenter.z - sphereRadius > boxMax.z)
  8884. return false;
  8885. return true;
  8886. };
  8887. var getLowestRoot = function (a, b, c, maxR) {
  8888. var determinant = b * b - 4.0 * a * c;
  8889. var result = { root: 0, found: false };
  8890. if (determinant < 0)
  8891. return result;
  8892. var sqrtD = Math.sqrt(determinant);
  8893. var r1 = (-b - sqrtD) / (2.0 * a);
  8894. var r2 = (-b + sqrtD) / (2.0 * a);
  8895. if (r1 > r2) {
  8896. var temp = r2;
  8897. r2 = r1;
  8898. r1 = temp;
  8899. }
  8900. if (r1 > 0 && r1 < maxR) {
  8901. result.root = r1;
  8902. result.found = true;
  8903. return result;
  8904. }
  8905. if (r2 > 0 && r2 < maxR) {
  8906. result.root = r2;
  8907. result.found = true;
  8908. return result;
  8909. }
  8910. return result;
  8911. };
  8912. var Collider = (function () {
  8913. function Collider() {
  8914. this.radius = new BABYLON.Vector3(1, 1, 1);
  8915. this.retry = 0;
  8916. this.basePointWorld = BABYLON.Vector3.Zero();
  8917. this.velocityWorld = BABYLON.Vector3.Zero();
  8918. this.normalizedVelocity = BABYLON.Vector3.Zero();
  8919. this._collisionPoint = BABYLON.Vector3.Zero();
  8920. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  8921. this._tempVector = BABYLON.Vector3.Zero();
  8922. this._tempVector2 = BABYLON.Vector3.Zero();
  8923. this._tempVector3 = BABYLON.Vector3.Zero();
  8924. this._tempVector4 = BABYLON.Vector3.Zero();
  8925. this._edge = BABYLON.Vector3.Zero();
  8926. this._baseToVertex = BABYLON.Vector3.Zero();
  8927. this._destinationPoint = BABYLON.Vector3.Zero();
  8928. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  8929. this._displacementVector = BABYLON.Vector3.Zero();
  8930. }
  8931. // Methods
  8932. Collider.prototype._initialize = function (source, dir, e) {
  8933. this.velocity = dir;
  8934. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  8935. this.basePoint = source;
  8936. source.multiplyToRef(this.radius, this.basePointWorld);
  8937. dir.multiplyToRef(this.radius, this.velocityWorld);
  8938. this.velocityWorldLength = this.velocityWorld.length();
  8939. this.epsilon = e;
  8940. this.collisionFound = false;
  8941. };
  8942. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  8943. pa.subtractToRef(point, this._tempVector);
  8944. pb.subtractToRef(point, this._tempVector2);
  8945. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  8946. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8947. if (d < 0)
  8948. return false;
  8949. pc.subtractToRef(point, this._tempVector3);
  8950. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  8951. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8952. if (d < 0)
  8953. return false;
  8954. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  8955. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8956. return d >= 0;
  8957. };
  8958. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  8959. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  8960. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  8961. if (distance > this.velocityWorldLength + max + sphereRadius) {
  8962. return false;
  8963. }
  8964. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  8965. return false;
  8966. return true;
  8967. };
  8968. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  8969. var t0;
  8970. var embeddedInPlane = false;
  8971. //defensive programming, actually not needed.
  8972. if (!trianglePlaneArray) {
  8973. trianglePlaneArray = [];
  8974. }
  8975. if (!trianglePlaneArray[faceIndex]) {
  8976. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  8977. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  8978. }
  8979. var trianglePlane = trianglePlaneArray[faceIndex];
  8980. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  8981. return;
  8982. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  8983. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  8984. if (normalDotVelocity == 0) {
  8985. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  8986. return;
  8987. embeddedInPlane = true;
  8988. t0 = 0;
  8989. }
  8990. else {
  8991. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  8992. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  8993. if (t0 > t1) {
  8994. var temp = t1;
  8995. t1 = t0;
  8996. t0 = temp;
  8997. }
  8998. if (t0 > 1.0 || t1 < 0.0)
  8999. return;
  9000. if (t0 < 0)
  9001. t0 = 0;
  9002. if (t0 > 1.0)
  9003. t0 = 1.0;
  9004. }
  9005. this._collisionPoint.copyFromFloats(0, 0, 0);
  9006. var found = false;
  9007. var t = 1.0;
  9008. if (!embeddedInPlane) {
  9009. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9010. this.velocity.scaleToRef(t0, this._tempVector);
  9011. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9012. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9013. found = true;
  9014. t = t0;
  9015. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9016. }
  9017. }
  9018. if (!found) {
  9019. var velocitySquaredLength = this.velocity.lengthSquared();
  9020. var a = velocitySquaredLength;
  9021. this.basePoint.subtractToRef(p1, this._tempVector);
  9022. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9023. var c = this._tempVector.lengthSquared() - 1.0;
  9024. var lowestRoot = getLowestRoot(a, b, c, t);
  9025. if (lowestRoot.found) {
  9026. t = lowestRoot.root;
  9027. found = true;
  9028. this._collisionPoint.copyFrom(p1);
  9029. }
  9030. this.basePoint.subtractToRef(p2, this._tempVector);
  9031. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9032. c = this._tempVector.lengthSquared() - 1.0;
  9033. lowestRoot = getLowestRoot(a, b, c, t);
  9034. if (lowestRoot.found) {
  9035. t = lowestRoot.root;
  9036. found = true;
  9037. this._collisionPoint.copyFrom(p2);
  9038. }
  9039. this.basePoint.subtractToRef(p3, this._tempVector);
  9040. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9041. c = this._tempVector.lengthSquared() - 1.0;
  9042. lowestRoot = getLowestRoot(a, b, c, t);
  9043. if (lowestRoot.found) {
  9044. t = lowestRoot.root;
  9045. found = true;
  9046. this._collisionPoint.copyFrom(p3);
  9047. }
  9048. p2.subtractToRef(p1, this._edge);
  9049. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9050. var edgeSquaredLength = this._edge.lengthSquared();
  9051. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9052. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9053. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9054. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9055. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9056. lowestRoot = getLowestRoot(a, b, c, t);
  9057. if (lowestRoot.found) {
  9058. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9059. if (f >= 0.0 && f <= 1.0) {
  9060. t = lowestRoot.root;
  9061. found = true;
  9062. this._edge.scaleInPlace(f);
  9063. p1.addToRef(this._edge, this._collisionPoint);
  9064. }
  9065. }
  9066. p3.subtractToRef(p2, this._edge);
  9067. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9068. edgeSquaredLength = this._edge.lengthSquared();
  9069. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9070. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9071. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9072. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9073. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9074. lowestRoot = getLowestRoot(a, b, c, t);
  9075. if (lowestRoot.found) {
  9076. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9077. if (f >= 0.0 && f <= 1.0) {
  9078. t = lowestRoot.root;
  9079. found = true;
  9080. this._edge.scaleInPlace(f);
  9081. p2.addToRef(this._edge, this._collisionPoint);
  9082. }
  9083. }
  9084. p1.subtractToRef(p3, this._edge);
  9085. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9086. edgeSquaredLength = this._edge.lengthSquared();
  9087. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9088. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9089. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9090. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9091. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9092. lowestRoot = getLowestRoot(a, b, c, t);
  9093. if (lowestRoot.found) {
  9094. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9095. if (f >= 0.0 && f <= 1.0) {
  9096. t = lowestRoot.root;
  9097. found = true;
  9098. this._edge.scaleInPlace(f);
  9099. p3.addToRef(this._edge, this._collisionPoint);
  9100. }
  9101. }
  9102. }
  9103. if (found) {
  9104. var distToCollision = t * this.velocity.length();
  9105. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9106. if (!this.intersectionPoint) {
  9107. this.intersectionPoint = this._collisionPoint.clone();
  9108. }
  9109. else {
  9110. this.intersectionPoint.copyFrom(this._collisionPoint);
  9111. }
  9112. this.nearestDistance = distToCollision;
  9113. this.collisionFound = true;
  9114. }
  9115. }
  9116. };
  9117. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9118. for (var i = indexStart; i < indexEnd; i += 3) {
  9119. var p1 = pts[indices[i] - decal];
  9120. var p2 = pts[indices[i + 1] - decal];
  9121. var p3 = pts[indices[i + 2] - decal];
  9122. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9123. }
  9124. };
  9125. Collider.prototype._getResponse = function (pos, vel) {
  9126. pos.addToRef(vel, this._destinationPoint);
  9127. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9128. this.basePoint.addToRef(vel, pos);
  9129. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9130. this._slidePlaneNormal.normalize();
  9131. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9132. pos.addInPlace(this._displacementVector);
  9133. this.intersectionPoint.addInPlace(this._displacementVector);
  9134. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9135. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9136. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9137. };
  9138. return Collider;
  9139. })();
  9140. BABYLON.Collider = Collider;
  9141. })(BABYLON || (BABYLON = {}));
  9142. //# sourceMappingURL=babylon.collider.js.map
  9143. var BABYLON;
  9144. (function (BABYLON) {
  9145. //WebWorker code will be inserted to this variable.
  9146. BABYLON.CollisionWorker = "";
  9147. (function (WorkerTaskType) {
  9148. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9149. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9150. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9151. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9152. var WorkerTaskType = BABYLON.WorkerTaskType;
  9153. (function (WorkerReplyType) {
  9154. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9155. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9156. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9157. var WorkerReplyType = BABYLON.WorkerReplyType;
  9158. var CollisionCoordinatorWorker = (function () {
  9159. function CollisionCoordinatorWorker() {
  9160. var _this = this;
  9161. this._scaledPosition = BABYLON.Vector3.Zero();
  9162. this._scaledVelocity = BABYLON.Vector3.Zero();
  9163. this.onMeshUpdated = function (mesh) {
  9164. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9165. };
  9166. this.onGeometryUpdated = function (geometry) {
  9167. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9168. };
  9169. this._afterRender = function () {
  9170. if (!_this._init)
  9171. return;
  9172. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9173. return;
  9174. }
  9175. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9176. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9177. if (_this._runningUpdated > 4) {
  9178. return;
  9179. }
  9180. ++_this._runningUpdated;
  9181. var payload = {
  9182. updatedMeshes: _this._addUpdateMeshesList,
  9183. updatedGeometries: _this._addUpdateGeometriesList,
  9184. removedGeometries: _this._toRemoveGeometryArray,
  9185. removedMeshes: _this._toRemoveMeshesArray
  9186. };
  9187. var message = {
  9188. payload: payload,
  9189. taskType: 1 /* UPDATE */
  9190. };
  9191. var serializable = [];
  9192. for (var id in payload.updatedGeometries) {
  9193. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9194. //prepare transferables
  9195. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9196. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9197. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9198. }
  9199. }
  9200. _this._worker.postMessage(message, serializable);
  9201. _this._addUpdateMeshesList = {};
  9202. _this._addUpdateGeometriesList = {};
  9203. _this._toRemoveGeometryArray = [];
  9204. _this._toRemoveMeshesArray = [];
  9205. };
  9206. this._onMessageFromWorker = function (e) {
  9207. var returnData = e.data;
  9208. if (returnData.error != 0 /* SUCCESS */) {
  9209. //TODO what errors can be returned from the worker?
  9210. BABYLON.Tools.Warn("error returned from worker!");
  9211. return;
  9212. }
  9213. switch (returnData.taskType) {
  9214. case 0 /* INIT */:
  9215. _this._init = true;
  9216. //Update the worked with ALL of the scene's current state
  9217. _this._scene.meshes.forEach(function (mesh) {
  9218. _this.onMeshAdded(mesh);
  9219. });
  9220. _this._scene.getGeometries().forEach(function (geometry) {
  9221. _this.onGeometryAdded(geometry);
  9222. });
  9223. break;
  9224. case 1 /* UPDATE */:
  9225. _this._runningUpdated--;
  9226. break;
  9227. case 2 /* COLLIDE */:
  9228. _this._runningCollisionTask = false;
  9229. var returnPayload = returnData.payload;
  9230. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9231. return;
  9232. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9233. //cleanup
  9234. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9235. break;
  9236. }
  9237. };
  9238. this._collisionsCallbackArray = [];
  9239. this._init = false;
  9240. this._runningUpdated = 0;
  9241. this._runningCollisionTask = false;
  9242. this._addUpdateMeshesList = {};
  9243. this._addUpdateGeometriesList = {};
  9244. this._toRemoveGeometryArray = [];
  9245. this._toRemoveMeshesArray = [];
  9246. }
  9247. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9248. if (!this._init)
  9249. return;
  9250. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9251. return;
  9252. position.divideToRef(collider.radius, this._scaledPosition);
  9253. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9254. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9255. var payload = {
  9256. collider: {
  9257. position: this._scaledPosition.asArray(),
  9258. velocity: this._scaledVelocity.asArray(),
  9259. radius: collider.radius.asArray()
  9260. },
  9261. collisionId: collisionIndex,
  9262. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9263. maximumRetry: maximumRetry
  9264. };
  9265. var message = {
  9266. payload: payload,
  9267. taskType: 2 /* COLLIDE */
  9268. };
  9269. this._worker.postMessage(message);
  9270. };
  9271. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9272. this._scene = scene;
  9273. this._scene.registerAfterRender(this._afterRender);
  9274. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9275. this._worker = new Worker(workerUrl);
  9276. this._worker.onmessage = this._onMessageFromWorker;
  9277. var message = {
  9278. payload: {},
  9279. taskType: 0 /* INIT */
  9280. };
  9281. this._worker.postMessage(message);
  9282. };
  9283. CollisionCoordinatorWorker.prototype.destroy = function () {
  9284. this._scene.unregisterAfterRender(this._afterRender);
  9285. this._worker.terminate();
  9286. };
  9287. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9288. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9289. this.onMeshUpdated(mesh);
  9290. };
  9291. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9292. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9293. };
  9294. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9295. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9296. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9297. this.onGeometryUpdated(geometry);
  9298. };
  9299. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9300. this._toRemoveGeometryArray.push(geometry.id);
  9301. };
  9302. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9303. var submeshes = [];
  9304. if (mesh.subMeshes) {
  9305. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9306. return {
  9307. position: idx,
  9308. verticesStart: sm.verticesStart,
  9309. verticesCount: sm.verticesCount,
  9310. indexStart: sm.indexStart,
  9311. indexCount: sm.indexCount,
  9312. hasMaterial: !!sm.getMaterial(),
  9313. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9314. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9315. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9316. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9317. };
  9318. });
  9319. }
  9320. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9321. return {
  9322. uniqueId: mesh.uniqueId,
  9323. id: mesh.id,
  9324. name: mesh.name,
  9325. geometryId: geometryId,
  9326. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9327. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9328. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9329. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9330. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9331. subMeshes: submeshes,
  9332. checkCollisions: mesh.checkCollisions
  9333. };
  9334. };
  9335. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9336. return {
  9337. id: geometry.id,
  9338. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9339. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9340. indices: new Int32Array(geometry.getIndices() || []),
  9341. };
  9342. };
  9343. return CollisionCoordinatorWorker;
  9344. })();
  9345. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9346. var CollisionCoordinatorLegacy = (function () {
  9347. function CollisionCoordinatorLegacy() {
  9348. this._scaledPosition = BABYLON.Vector3.Zero();
  9349. this._scaledVelocity = BABYLON.Vector3.Zero();
  9350. this._finalPosition = BABYLON.Vector3.Zero();
  9351. }
  9352. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9353. position.divideToRef(collider.radius, this._scaledPosition);
  9354. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9355. collider.retry = 0;
  9356. collider.initialVelocity = this._scaledVelocity;
  9357. collider.initialPosition = this._scaledPosition;
  9358. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9359. this._finalPosition.multiplyInPlace(collider.radius);
  9360. //run the callback
  9361. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9362. };
  9363. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9364. this._scene = scene;
  9365. };
  9366. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9367. //Legacy need no destruction method.
  9368. };
  9369. //No update in legacy mode
  9370. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) {
  9371. };
  9372. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) {
  9373. };
  9374. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) {
  9375. };
  9376. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) {
  9377. };
  9378. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) {
  9379. };
  9380. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) {
  9381. };
  9382. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9383. if (excludedMesh === void 0) { excludedMesh = null; }
  9384. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9385. if (collider.retry >= maximumRetry) {
  9386. finalPosition.copyFrom(position);
  9387. return;
  9388. }
  9389. collider._initialize(position, velocity, closeDistance);
  9390. for (var index = 0; index < this._scene.meshes.length; index++) {
  9391. var mesh = this._scene.meshes[index];
  9392. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9393. mesh._checkCollision(collider);
  9394. }
  9395. }
  9396. if (!collider.collisionFound) {
  9397. position.addToRef(velocity, finalPosition);
  9398. return;
  9399. }
  9400. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9401. collider._getResponse(position, velocity);
  9402. }
  9403. if (velocity.length() <= closeDistance) {
  9404. finalPosition.copyFrom(position);
  9405. return;
  9406. }
  9407. collider.retry++;
  9408. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9409. };
  9410. return CollisionCoordinatorLegacy;
  9411. })();
  9412. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9413. })(BABYLON || (BABYLON = {}));
  9414. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9415. var __extends = this.__extends || function (d, b) {
  9416. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9417. function __() { this.constructor = d; }
  9418. __.prototype = b.prototype;
  9419. d.prototype = new __();
  9420. };
  9421. var BABYLON;
  9422. (function (BABYLON) {
  9423. var Camera = (function (_super) {
  9424. __extends(Camera, _super);
  9425. function Camera(name, position, scene) {
  9426. _super.call(this, name, scene);
  9427. this.position = position;
  9428. // Members
  9429. this.upVector = BABYLON.Vector3.Up();
  9430. this.orthoLeft = null;
  9431. this.orthoRight = null;
  9432. this.orthoBottom = null;
  9433. this.orthoTop = null;
  9434. this.fov = 0.8;
  9435. this.minZ = 1.0;
  9436. this.maxZ = 10000.0;
  9437. this.inertia = 0.9;
  9438. this.mode = Camera.PERSPECTIVE_CAMERA;
  9439. this.isIntermediate = false;
  9440. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9441. this.subCameras = [];
  9442. this.layerMask = 0xFFFFFFFF;
  9443. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9444. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9445. this._projectionMatrix = new BABYLON.Matrix();
  9446. this._postProcesses = new Array();
  9447. this._postProcessesTakenIndices = [];
  9448. this._activeMeshes = new BABYLON.SmartArray(256);
  9449. this._globalPosition = BABYLON.Vector3.Zero();
  9450. scene.addCamera(this);
  9451. if (!scene.activeCamera) {
  9452. scene.activeCamera = this;
  9453. }
  9454. }
  9455. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9456. get: function () {
  9457. return Camera._PERSPECTIVE_CAMERA;
  9458. },
  9459. enumerable: true,
  9460. configurable: true
  9461. });
  9462. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9463. get: function () {
  9464. return Camera._ORTHOGRAPHIC_CAMERA;
  9465. },
  9466. enumerable: true,
  9467. configurable: true
  9468. });
  9469. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9470. get: function () {
  9471. return Camera._FOVMODE_VERTICAL_FIXED;
  9472. },
  9473. enumerable: true,
  9474. configurable: true
  9475. });
  9476. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9477. get: function () {
  9478. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9479. },
  9480. enumerable: true,
  9481. configurable: true
  9482. });
  9483. Object.defineProperty(Camera.prototype, "globalPosition", {
  9484. get: function () {
  9485. return this._globalPosition;
  9486. },
  9487. enumerable: true,
  9488. configurable: true
  9489. });
  9490. Camera.prototype.getActiveMeshes = function () {
  9491. return this._activeMeshes;
  9492. };
  9493. Camera.prototype.isActiveMesh = function (mesh) {
  9494. return (this._activeMeshes.indexOf(mesh) !== -1);
  9495. };
  9496. //Cache
  9497. Camera.prototype._initCache = function () {
  9498. _super.prototype._initCache.call(this);
  9499. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9500. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9501. this._cache.mode = undefined;
  9502. this._cache.minZ = undefined;
  9503. this._cache.maxZ = undefined;
  9504. this._cache.fov = undefined;
  9505. this._cache.aspectRatio = undefined;
  9506. this._cache.orthoLeft = undefined;
  9507. this._cache.orthoRight = undefined;
  9508. this._cache.orthoBottom = undefined;
  9509. this._cache.orthoTop = undefined;
  9510. this._cache.renderWidth = undefined;
  9511. this._cache.renderHeight = undefined;
  9512. };
  9513. Camera.prototype._updateCache = function (ignoreParentClass) {
  9514. if (!ignoreParentClass) {
  9515. _super.prototype._updateCache.call(this);
  9516. }
  9517. var engine = this.getEngine();
  9518. this._cache.position.copyFrom(this.position);
  9519. this._cache.upVector.copyFrom(this.upVector);
  9520. this._cache.mode = this.mode;
  9521. this._cache.minZ = this.minZ;
  9522. this._cache.maxZ = this.maxZ;
  9523. this._cache.fov = this.fov;
  9524. this._cache.aspectRatio = engine.getAspectRatio(this);
  9525. this._cache.orthoLeft = this.orthoLeft;
  9526. this._cache.orthoRight = this.orthoRight;
  9527. this._cache.orthoBottom = this.orthoBottom;
  9528. this._cache.orthoTop = this.orthoTop;
  9529. this._cache.renderWidth = engine.getRenderWidth();
  9530. this._cache.renderHeight = engine.getRenderHeight();
  9531. };
  9532. Camera.prototype._updateFromScene = function () {
  9533. this.updateCache();
  9534. this._update();
  9535. };
  9536. // Synchronized
  9537. Camera.prototype._isSynchronized = function () {
  9538. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9539. };
  9540. Camera.prototype._isSynchronizedViewMatrix = function () {
  9541. if (!_super.prototype._isSynchronized.call(this))
  9542. return false;
  9543. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  9544. };
  9545. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9546. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  9547. if (!check) {
  9548. return false;
  9549. }
  9550. var engine = this.getEngine();
  9551. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9552. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  9553. }
  9554. else {
  9555. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  9556. }
  9557. return check;
  9558. };
  9559. // Controls
  9560. Camera.prototype.attachControl = function (element) {
  9561. };
  9562. Camera.prototype.detachControl = function (element) {
  9563. };
  9564. Camera.prototype._update = function () {
  9565. };
  9566. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9567. if (insertAt === void 0) { insertAt = null; }
  9568. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9569. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9570. return 0;
  9571. }
  9572. if (insertAt == null || insertAt < 0) {
  9573. this._postProcesses.push(postProcess);
  9574. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9575. return this._postProcesses.length - 1;
  9576. }
  9577. var add = 0;
  9578. if (this._postProcesses[insertAt]) {
  9579. var start = this._postProcesses.length - 1;
  9580. for (var i = start; i >= insertAt + 1; --i) {
  9581. this._postProcesses[i + 1] = this._postProcesses[i];
  9582. }
  9583. add = 1;
  9584. }
  9585. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9586. if (this._postProcessesTakenIndices[i] < insertAt) {
  9587. continue;
  9588. }
  9589. start = this._postProcessesTakenIndices.length - 1;
  9590. for (var j = start; j >= i; --j) {
  9591. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9592. }
  9593. this._postProcessesTakenIndices[i] = insertAt;
  9594. break;
  9595. }
  9596. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9597. this._postProcessesTakenIndices.push(insertAt);
  9598. }
  9599. var result = insertAt + add;
  9600. this._postProcesses[result] = postProcess;
  9601. return result;
  9602. };
  9603. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9604. if (atIndices === void 0) { atIndices = null; }
  9605. var result = [];
  9606. if (!atIndices) {
  9607. var length = this._postProcesses.length;
  9608. for (var i = 0; i < length; i++) {
  9609. if (this._postProcesses[i] !== postProcess) {
  9610. continue;
  9611. }
  9612. delete this._postProcesses[i];
  9613. var index = this._postProcessesTakenIndices.indexOf(i);
  9614. this._postProcessesTakenIndices.splice(index, 1);
  9615. }
  9616. }
  9617. else {
  9618. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9619. for (i = 0; i < atIndices.length; i++) {
  9620. var foundPostProcess = this._postProcesses[atIndices[i]];
  9621. if (foundPostProcess !== postProcess) {
  9622. result.push(i);
  9623. continue;
  9624. }
  9625. delete this._postProcesses[atIndices[i]];
  9626. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9627. this._postProcessesTakenIndices.splice(index, 1);
  9628. }
  9629. }
  9630. return result;
  9631. };
  9632. Camera.prototype.getWorldMatrix = function () {
  9633. if (!this._worldMatrix) {
  9634. this._worldMatrix = BABYLON.Matrix.Identity();
  9635. }
  9636. var viewMatrix = this.getViewMatrix();
  9637. viewMatrix.invertToRef(this._worldMatrix);
  9638. return this._worldMatrix;
  9639. };
  9640. Camera.prototype._getViewMatrix = function () {
  9641. return BABYLON.Matrix.Identity();
  9642. };
  9643. Camera.prototype.getViewMatrix = function (force) {
  9644. this._computedViewMatrix = this._computeViewMatrix(force);
  9645. if (!force && this._isSynchronizedViewMatrix()) {
  9646. return this._computedViewMatrix;
  9647. }
  9648. if (!this.parent || !this.parent.getWorldMatrix) {
  9649. this._globalPosition.copyFrom(this.position);
  9650. }
  9651. else {
  9652. if (!this._worldMatrix) {
  9653. this._worldMatrix = BABYLON.Matrix.Identity();
  9654. }
  9655. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9656. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9657. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9658. this._computedViewMatrix.invert();
  9659. this._markSyncedWithParent();
  9660. }
  9661. this._currentRenderId = this.getScene().getRenderId();
  9662. return this._computedViewMatrix;
  9663. };
  9664. Camera.prototype._computeViewMatrix = function (force) {
  9665. if (!force && this._isSynchronizedViewMatrix()) {
  9666. return this._computedViewMatrix;
  9667. }
  9668. this._computedViewMatrix = this._getViewMatrix();
  9669. this._currentRenderId = this.getScene().getRenderId();
  9670. return this._computedViewMatrix;
  9671. };
  9672. Camera.prototype.getProjectionMatrix = function (force) {
  9673. if (!force && this._isSynchronizedProjectionMatrix()) {
  9674. return this._projectionMatrix;
  9675. }
  9676. var engine = this.getEngine();
  9677. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9678. if (this.minZ <= 0) {
  9679. this.minZ = 0.1;
  9680. }
  9681. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9682. return this._projectionMatrix;
  9683. }
  9684. var halfWidth = engine.getRenderWidth() / 2.0;
  9685. var halfHeight = engine.getRenderHeight() / 2.0;
  9686. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9687. return this._projectionMatrix;
  9688. };
  9689. Camera.prototype.dispose = function () {
  9690. // Remove from scene
  9691. this.getScene().removeCamera(this);
  9692. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9693. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9694. }
  9695. };
  9696. // Statics
  9697. Camera._PERSPECTIVE_CAMERA = 0;
  9698. Camera._ORTHOGRAPHIC_CAMERA = 1;
  9699. Camera._FOVMODE_VERTICAL_FIXED = 0;
  9700. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  9701. return Camera;
  9702. })(BABYLON.Node);
  9703. BABYLON.Camera = Camera;
  9704. })(BABYLON || (BABYLON = {}));
  9705. //# sourceMappingURL=babylon.camera.js.map
  9706. var __extends = this.__extends || function (d, b) {
  9707. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9708. function __() { this.constructor = d; }
  9709. __.prototype = b.prototype;
  9710. d.prototype = new __();
  9711. };
  9712. var BABYLON;
  9713. (function (BABYLON) {
  9714. var TargetCamera = (function (_super) {
  9715. __extends(TargetCamera, _super);
  9716. function TargetCamera(name, position, scene) {
  9717. _super.call(this, name, position, scene);
  9718. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  9719. this.cameraRotation = new BABYLON.Vector2(0, 0);
  9720. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9721. this.speed = 2.0;
  9722. this.noRotationConstraint = false;
  9723. this.lockedTarget = null;
  9724. this._currentTarget = BABYLON.Vector3.Zero();
  9725. this._viewMatrix = BABYLON.Matrix.Zero();
  9726. this._camMatrix = BABYLON.Matrix.Zero();
  9727. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  9728. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  9729. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  9730. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  9731. this._lookAtTemp = BABYLON.Matrix.Zero();
  9732. this._tempMatrix = BABYLON.Matrix.Zero();
  9733. }
  9734. TargetCamera.prototype._getLockedTargetPosition = function () {
  9735. if (!this.lockedTarget) {
  9736. return null;
  9737. }
  9738. return this.lockedTarget.position || this.lockedTarget;
  9739. };
  9740. // Cache
  9741. TargetCamera.prototype._initCache = function () {
  9742. _super.prototype._initCache.call(this);
  9743. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9744. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9745. };
  9746. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  9747. if (!ignoreParentClass) {
  9748. _super.prototype._updateCache.call(this);
  9749. }
  9750. var lockedTargetPosition = this._getLockedTargetPosition();
  9751. if (!lockedTargetPosition) {
  9752. this._cache.lockedTarget = null;
  9753. }
  9754. else {
  9755. if (!this._cache.lockedTarget) {
  9756. this._cache.lockedTarget = lockedTargetPosition.clone();
  9757. }
  9758. else {
  9759. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  9760. }
  9761. }
  9762. this._cache.rotation.copyFrom(this.rotation);
  9763. };
  9764. // Synchronized
  9765. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  9766. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  9767. return false;
  9768. }
  9769. var lockedTargetPosition = this._getLockedTargetPosition();
  9770. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  9771. };
  9772. // Methods
  9773. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  9774. var engine = this.getEngine();
  9775. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  9776. };
  9777. // Target
  9778. TargetCamera.prototype.setTarget = function (target) {
  9779. this.upVector.normalize();
  9780. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  9781. this._camMatrix.invert();
  9782. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  9783. var vDir = target.subtract(this.position);
  9784. if (vDir.x >= 0.0) {
  9785. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  9786. }
  9787. else {
  9788. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  9789. }
  9790. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  9791. if (isNaN(this.rotation.x)) {
  9792. this.rotation.x = 0;
  9793. }
  9794. if (isNaN(this.rotation.y)) {
  9795. this.rotation.y = 0;
  9796. }
  9797. if (isNaN(this.rotation.z)) {
  9798. this.rotation.z = 0;
  9799. }
  9800. };
  9801. TargetCamera.prototype.getTarget = function () {
  9802. return this._currentTarget;
  9803. };
  9804. TargetCamera.prototype._decideIfNeedsToMove = function () {
  9805. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  9806. };
  9807. TargetCamera.prototype._updatePosition = function () {
  9808. this.position.addInPlace(this.cameraDirection);
  9809. };
  9810. TargetCamera.prototype._update = function () {
  9811. var needToMove = this._decideIfNeedsToMove();
  9812. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  9813. // Move
  9814. if (needToMove) {
  9815. this._updatePosition();
  9816. }
  9817. // Rotate
  9818. if (needToRotate) {
  9819. this.rotation.x += this.cameraRotation.x;
  9820. this.rotation.y += this.cameraRotation.y;
  9821. if (!this.noRotationConstraint) {
  9822. var limit = (Math.PI / 2) * 0.95;
  9823. if (this.rotation.x > limit)
  9824. this.rotation.x = limit;
  9825. if (this.rotation.x < -limit)
  9826. this.rotation.x = -limit;
  9827. }
  9828. }
  9829. // Inertia
  9830. if (needToMove) {
  9831. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  9832. this.cameraDirection.x = 0;
  9833. }
  9834. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  9835. this.cameraDirection.y = 0;
  9836. }
  9837. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  9838. this.cameraDirection.z = 0;
  9839. }
  9840. this.cameraDirection.scaleInPlace(this.inertia);
  9841. }
  9842. if (needToRotate) {
  9843. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  9844. this.cameraRotation.x = 0;
  9845. }
  9846. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  9847. this.cameraRotation.y = 0;
  9848. }
  9849. this.cameraRotation.scaleInPlace(this.inertia);
  9850. }
  9851. };
  9852. TargetCamera.prototype._getViewMatrix = function () {
  9853. if (!this.lockedTarget) {
  9854. // Compute
  9855. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  9856. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  9857. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9858. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  9859. this._lookAtTemp.invert();
  9860. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  9861. }
  9862. else {
  9863. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9864. }
  9865. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  9866. // Computing target and final matrix
  9867. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  9868. }
  9869. else {
  9870. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  9871. }
  9872. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  9873. return this._viewMatrix;
  9874. };
  9875. return TargetCamera;
  9876. })(BABYLON.Camera);
  9877. BABYLON.TargetCamera = TargetCamera;
  9878. })(BABYLON || (BABYLON = {}));
  9879. //# sourceMappingURL=babylon.targetCamera.js.map
  9880. var __extends = this.__extends || function (d, b) {
  9881. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9882. function __() { this.constructor = d; }
  9883. __.prototype = b.prototype;
  9884. d.prototype = new __();
  9885. };
  9886. var BABYLON;
  9887. (function (BABYLON) {
  9888. var FreeCamera = (function (_super) {
  9889. __extends(FreeCamera, _super);
  9890. function FreeCamera(name, position, scene) {
  9891. var _this = this;
  9892. _super.call(this, name, position, scene);
  9893. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9894. this.keysUp = [38];
  9895. this.keysDown = [40];
  9896. this.keysLeft = [37];
  9897. this.keysRight = [39];
  9898. this.checkCollisions = false;
  9899. this.applyGravity = false;
  9900. this.angularSensibility = 2000.0;
  9901. this._keys = [];
  9902. this._collider = new BABYLON.Collider();
  9903. this._needMoveForGravity = false;
  9904. this._oldPosition = BABYLON.Vector3.Zero();
  9905. this._diffPosition = BABYLON.Vector3.Zero();
  9906. this._newPosition = BABYLON.Vector3.Zero();
  9907. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9908. if (collidedMesh === void 0) { collidedMesh = null; }
  9909. //TODO move this to the collision coordinator!
  9910. if (_this.getScene().workerCollisions)
  9911. newPosition.multiplyInPlace(_this._collider.radius);
  9912. var updatePosition = function (newPos) {
  9913. _this._newPosition.copyFrom(newPos);
  9914. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  9915. var oldPosition = _this.position.clone();
  9916. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  9917. _this.position.addInPlace(_this._diffPosition);
  9918. if (_this.onCollide && collidedMesh) {
  9919. _this.onCollide(collidedMesh);
  9920. }
  9921. }
  9922. };
  9923. updatePosition(newPosition);
  9924. };
  9925. }
  9926. // Controls
  9927. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  9928. var _this = this;
  9929. var previousPosition;
  9930. var engine = this.getEngine();
  9931. if (this._attachedElement) {
  9932. return;
  9933. }
  9934. this._attachedElement = element;
  9935. if (this._onMouseDown === undefined) {
  9936. this._onMouseDown = function (evt) {
  9937. previousPosition = {
  9938. x: evt.clientX,
  9939. y: evt.clientY
  9940. };
  9941. if (!noPreventDefault) {
  9942. evt.preventDefault();
  9943. }
  9944. };
  9945. this._onMouseUp = function (evt) {
  9946. previousPosition = null;
  9947. if (!noPreventDefault) {
  9948. evt.preventDefault();
  9949. }
  9950. };
  9951. this._onMouseOut = function (evt) {
  9952. previousPosition = null;
  9953. _this._keys = [];
  9954. if (!noPreventDefault) {
  9955. evt.preventDefault();
  9956. }
  9957. };
  9958. this._onMouseMove = function (evt) {
  9959. if (!previousPosition && !engine.isPointerLock) {
  9960. return;
  9961. }
  9962. var offsetX;
  9963. var offsetY;
  9964. if (!engine.isPointerLock) {
  9965. offsetX = evt.clientX - previousPosition.x;
  9966. offsetY = evt.clientY - previousPosition.y;
  9967. }
  9968. else {
  9969. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  9970. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  9971. }
  9972. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  9973. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  9974. previousPosition = {
  9975. x: evt.clientX,
  9976. y: evt.clientY
  9977. };
  9978. if (!noPreventDefault) {
  9979. evt.preventDefault();
  9980. }
  9981. };
  9982. this._onKeyDown = function (evt) {
  9983. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  9984. var index = _this._keys.indexOf(evt.keyCode);
  9985. if (index === -1) {
  9986. _this._keys.push(evt.keyCode);
  9987. }
  9988. if (!noPreventDefault) {
  9989. evt.preventDefault();
  9990. }
  9991. }
  9992. };
  9993. this._onKeyUp = function (evt) {
  9994. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  9995. var index = _this._keys.indexOf(evt.keyCode);
  9996. if (index >= 0) {
  9997. _this._keys.splice(index, 1);
  9998. }
  9999. if (!noPreventDefault) {
  10000. evt.preventDefault();
  10001. }
  10002. }
  10003. };
  10004. this._onLostFocus = function () {
  10005. _this._keys = [];
  10006. };
  10007. this._reset = function () {
  10008. _this._keys = [];
  10009. previousPosition = null;
  10010. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10011. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10012. };
  10013. }
  10014. element.addEventListener("mousedown", this._onMouseDown, false);
  10015. element.addEventListener("mouseup", this._onMouseUp, false);
  10016. element.addEventListener("mouseout", this._onMouseOut, false);
  10017. element.addEventListener("mousemove", this._onMouseMove, false);
  10018. BABYLON.Tools.RegisterTopRootEvents([
  10019. { name: "keydown", handler: this._onKeyDown },
  10020. { name: "keyup", handler: this._onKeyUp },
  10021. { name: "blur", handler: this._onLostFocus }
  10022. ]);
  10023. };
  10024. FreeCamera.prototype.detachControl = function (element) {
  10025. if (this._attachedElement != element) {
  10026. return;
  10027. }
  10028. element.removeEventListener("mousedown", this._onMouseDown);
  10029. element.removeEventListener("mouseup", this._onMouseUp);
  10030. element.removeEventListener("mouseout", this._onMouseOut);
  10031. element.removeEventListener("mousemove", this._onMouseMove);
  10032. BABYLON.Tools.UnregisterTopRootEvents([
  10033. { name: "keydown", handler: this._onKeyDown },
  10034. { name: "keyup", handler: this._onKeyUp },
  10035. { name: "blur", handler: this._onLostFocus }
  10036. ]);
  10037. this._attachedElement = null;
  10038. if (this._reset) {
  10039. this._reset();
  10040. }
  10041. };
  10042. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10043. var globalPosition;
  10044. if (this.parent) {
  10045. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10046. }
  10047. else {
  10048. globalPosition = this.position;
  10049. }
  10050. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10051. this._collider.radius = this.ellipsoid;
  10052. //add gravity to the velocity to prevent the dual-collision checking
  10053. if (this.applyGravity) {
  10054. velocity.addInPlace(this.getScene().gravity);
  10055. }
  10056. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10057. };
  10058. FreeCamera.prototype._checkInputs = function () {
  10059. if (!this._localDirection) {
  10060. this._localDirection = BABYLON.Vector3.Zero();
  10061. this._transformedDirection = BABYLON.Vector3.Zero();
  10062. }
  10063. for (var index = 0; index < this._keys.length; index++) {
  10064. var keyCode = this._keys[index];
  10065. var speed = this._computeLocalCameraSpeed();
  10066. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10067. this._localDirection.copyFromFloats(-speed, 0, 0);
  10068. }
  10069. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10070. this._localDirection.copyFromFloats(0, 0, speed);
  10071. }
  10072. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10073. this._localDirection.copyFromFloats(speed, 0, 0);
  10074. }
  10075. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10076. this._localDirection.copyFromFloats(0, 0, -speed);
  10077. }
  10078. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10079. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10080. this.cameraDirection.addInPlace(this._transformedDirection);
  10081. }
  10082. };
  10083. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10084. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10085. };
  10086. FreeCamera.prototype._updatePosition = function () {
  10087. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10088. this._collideWithWorld(this.cameraDirection);
  10089. }
  10090. else {
  10091. this.position.addInPlace(this.cameraDirection);
  10092. }
  10093. };
  10094. FreeCamera.prototype._update = function () {
  10095. this._checkInputs();
  10096. _super.prototype._update.call(this);
  10097. };
  10098. return FreeCamera;
  10099. })(BABYLON.TargetCamera);
  10100. BABYLON.FreeCamera = FreeCamera;
  10101. })(BABYLON || (BABYLON = {}));
  10102. //# sourceMappingURL=babylon.freeCamera.js.map
  10103. var __extends = this.__extends || function (d, b) {
  10104. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10105. function __() { this.constructor = d; }
  10106. __.prototype = b.prototype;
  10107. d.prototype = new __();
  10108. };
  10109. var BABYLON;
  10110. (function (BABYLON) {
  10111. var FollowCamera = (function (_super) {
  10112. __extends(FollowCamera, _super);
  10113. function FollowCamera(name, position, scene) {
  10114. _super.call(this, name, position, scene);
  10115. this.radius = 12;
  10116. this.rotationOffset = 0;
  10117. this.heightOffset = 4;
  10118. this.cameraAcceleration = 0.05;
  10119. this.maxCameraSpeed = 20;
  10120. }
  10121. FollowCamera.prototype.getRadians = function (degrees) {
  10122. return degrees * Math.PI / 180;
  10123. };
  10124. FollowCamera.prototype.follow = function (cameraTarget) {
  10125. if (!cameraTarget)
  10126. return;
  10127. var yRotation;
  10128. if (cameraTarget.rotationQuaternion) {
  10129. var rotMatrix = new BABYLON.Matrix();
  10130. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10131. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10132. }
  10133. else {
  10134. yRotation = cameraTarget.rotation.y;
  10135. }
  10136. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10137. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10138. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10139. var dx = targetX - this.position.x;
  10140. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10141. var dz = (targetZ) - this.position.z;
  10142. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10143. var vy = dy * this.cameraAcceleration;
  10144. var vz = dz * this.cameraAcceleration * 2;
  10145. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10146. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10147. }
  10148. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10149. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10150. }
  10151. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10152. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10153. }
  10154. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10155. this.setTarget(cameraTarget.position);
  10156. };
  10157. FollowCamera.prototype._update = function () {
  10158. _super.prototype._update.call(this);
  10159. this.follow(this.target);
  10160. };
  10161. return FollowCamera;
  10162. })(BABYLON.TargetCamera);
  10163. BABYLON.FollowCamera = FollowCamera;
  10164. })(BABYLON || (BABYLON = {}));
  10165. //# sourceMappingURL=babylon.followCamera.js.map
  10166. var __extends = this.__extends || function (d, b) {
  10167. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10168. function __() { this.constructor = d; }
  10169. __.prototype = b.prototype;
  10170. d.prototype = new __();
  10171. };
  10172. var BABYLON;
  10173. (function (BABYLON) {
  10174. // We're mainly based on the logic defined into the FreeCamera code
  10175. var TouchCamera = (function (_super) {
  10176. __extends(TouchCamera, _super);
  10177. function TouchCamera(name, position, scene) {
  10178. _super.call(this, name, position, scene);
  10179. this._offsetX = null;
  10180. this._offsetY = null;
  10181. this._pointerCount = 0;
  10182. this._pointerPressed = [];
  10183. this.angularSensibility = 200000.0;
  10184. this.moveSensibility = 500.0;
  10185. }
  10186. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10187. var _this = this;
  10188. var previousPosition;
  10189. if (this._attachedCanvas) {
  10190. return;
  10191. }
  10192. this._attachedCanvas = canvas;
  10193. if (this._onPointerDown === undefined) {
  10194. this._onPointerDown = function (evt) {
  10195. if (!noPreventDefault) {
  10196. evt.preventDefault();
  10197. }
  10198. _this._pointerPressed.push(evt.pointerId);
  10199. if (_this._pointerPressed.length !== 1) {
  10200. return;
  10201. }
  10202. previousPosition = {
  10203. x: evt.clientX,
  10204. y: evt.clientY
  10205. };
  10206. };
  10207. this._onPointerUp = function (evt) {
  10208. if (!noPreventDefault) {
  10209. evt.preventDefault();
  10210. }
  10211. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10212. if (index === -1) {
  10213. return;
  10214. }
  10215. _this._pointerPressed.splice(index, 1);
  10216. if (index != 0) {
  10217. return;
  10218. }
  10219. previousPosition = null;
  10220. _this._offsetX = null;
  10221. _this._offsetY = null;
  10222. };
  10223. this._onPointerMove = function (evt) {
  10224. if (!noPreventDefault) {
  10225. evt.preventDefault();
  10226. }
  10227. if (!previousPosition) {
  10228. return;
  10229. }
  10230. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10231. if (index != 0) {
  10232. return;
  10233. }
  10234. _this._offsetX = evt.clientX - previousPosition.x;
  10235. _this._offsetY = -(evt.clientY - previousPosition.y);
  10236. };
  10237. this._onLostFocus = function () {
  10238. _this._offsetX = null;
  10239. _this._offsetY = null;
  10240. };
  10241. }
  10242. canvas.addEventListener("pointerdown", this._onPointerDown);
  10243. canvas.addEventListener("pointerup", this._onPointerUp);
  10244. canvas.addEventListener("pointerout", this._onPointerUp);
  10245. canvas.addEventListener("pointermove", this._onPointerMove);
  10246. BABYLON.Tools.RegisterTopRootEvents([
  10247. { name: "blur", handler: this._onLostFocus }
  10248. ]);
  10249. };
  10250. TouchCamera.prototype.detachControl = function (canvas) {
  10251. if (this._attachedCanvas != canvas) {
  10252. return;
  10253. }
  10254. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10255. canvas.removeEventListener("pointerup", this._onPointerUp);
  10256. canvas.removeEventListener("pointerout", this._onPointerUp);
  10257. canvas.removeEventListener("pointermove", this._onPointerMove);
  10258. BABYLON.Tools.UnregisterTopRootEvents([
  10259. { name: "blur", handler: this._onLostFocus }
  10260. ]);
  10261. this._attachedCanvas = null;
  10262. };
  10263. TouchCamera.prototype._checkInputs = function () {
  10264. if (!this._offsetX) {
  10265. return;
  10266. }
  10267. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10268. if (this._pointerPressed.length > 1) {
  10269. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10270. }
  10271. else {
  10272. var speed = this._computeLocalCameraSpeed();
  10273. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10274. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10275. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10276. }
  10277. };
  10278. return TouchCamera;
  10279. })(BABYLON.FreeCamera);
  10280. BABYLON.TouchCamera = TouchCamera;
  10281. })(BABYLON || (BABYLON = {}));
  10282. //# sourceMappingURL=babylon.touchCamera.js.map
  10283. var __extends = this.__extends || function (d, b) {
  10284. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10285. function __() { this.constructor = d; }
  10286. __.prototype = b.prototype;
  10287. d.prototype = new __();
  10288. };
  10289. var BABYLON;
  10290. (function (BABYLON) {
  10291. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10292. var ArcRotateCamera = (function (_super) {
  10293. __extends(ArcRotateCamera, _super);
  10294. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10295. var _this = this;
  10296. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10297. this.alpha = alpha;
  10298. this.beta = beta;
  10299. this.radius = radius;
  10300. this.target = target;
  10301. this.inertialAlphaOffset = 0;
  10302. this.inertialBetaOffset = 0;
  10303. this.inertialRadiusOffset = 0;
  10304. this.lowerAlphaLimit = null;
  10305. this.upperAlphaLimit = null;
  10306. this.lowerBetaLimit = 0.01;
  10307. this.upperBetaLimit = Math.PI;
  10308. this.lowerRadiusLimit = null;
  10309. this.upperRadiusLimit = null;
  10310. this.angularSensibility = 1000.0;
  10311. this.wheelPrecision = 3.0;
  10312. this.pinchPrecision = 2.0;
  10313. this.keysUp = [38];
  10314. this.keysDown = [40];
  10315. this.keysLeft = [37];
  10316. this.keysRight = [39];
  10317. this.zoomOnFactor = 1;
  10318. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10319. this.pinchInwards = true;
  10320. this._keys = [];
  10321. this._viewMatrix = new BABYLON.Matrix();
  10322. this.checkCollisions = false;
  10323. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10324. this._collider = new BABYLON.Collider();
  10325. this._previousPosition = BABYLON.Vector3.Zero();
  10326. this._collisionVelocity = BABYLON.Vector3.Zero();
  10327. this._newPosition = BABYLON.Vector3.Zero();
  10328. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10329. if (collidedMesh === void 0) { collidedMesh = null; }
  10330. if (collisionId != null || collisionId != undefined)
  10331. newPosition.multiplyInPlace(_this._collider.radius);
  10332. if (!newPosition.equalsWithEpsilon(_this.position)) {
  10333. _this.position.copyFrom(_this._previousPosition);
  10334. _this.alpha = _this._previousAlpha;
  10335. _this.beta = _this._previousBeta;
  10336. _this.radius = _this._previousRadius;
  10337. if (_this.onCollide && collidedMesh) {
  10338. _this.onCollide(collidedMesh);
  10339. }
  10340. }
  10341. _this._collisionTriggered = false;
  10342. };
  10343. if (!this.target) {
  10344. this.target = BABYLON.Vector3.Zero();
  10345. }
  10346. this.getViewMatrix();
  10347. }
  10348. ArcRotateCamera.prototype._getTargetPosition = function () {
  10349. return this.target.position || this.target;
  10350. };
  10351. // Cache
  10352. ArcRotateCamera.prototype._initCache = function () {
  10353. _super.prototype._initCache.call(this);
  10354. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10355. this._cache.alpha = undefined;
  10356. this._cache.beta = undefined;
  10357. this._cache.radius = undefined;
  10358. this._cache.targetScreenOffset = undefined;
  10359. };
  10360. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10361. if (!ignoreParentClass) {
  10362. _super.prototype._updateCache.call(this);
  10363. }
  10364. this._cache.target.copyFrom(this._getTargetPosition());
  10365. this._cache.alpha = this.alpha;
  10366. this._cache.beta = this.beta;
  10367. this._cache.radius = this.radius;
  10368. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10369. };
  10370. // Synchronized
  10371. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10372. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10373. return false;
  10374. return 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);
  10375. };
  10376. // Methods
  10377. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10378. var _this = this;
  10379. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10380. var previousPinchDistance = 0;
  10381. var pointers = new BABYLON.SmartCollection();
  10382. if (this._attachedElement) {
  10383. return;
  10384. }
  10385. this._attachedElement = element;
  10386. var engine = this.getEngine();
  10387. if (this._onPointerDown === undefined) {
  10388. this._onPointerDown = function (evt) {
  10389. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10390. cacheSoloPointer = pointers.item(evt.pointerId);
  10391. if (!noPreventDefault) {
  10392. evt.preventDefault();
  10393. }
  10394. };
  10395. this._onPointerUp = function (evt) {
  10396. cacheSoloPointer = null;
  10397. previousPinchDistance = 0;
  10398. pointers.remove(evt.pointerId);
  10399. if (!noPreventDefault) {
  10400. evt.preventDefault();
  10401. }
  10402. };
  10403. this._onPointerMove = function (evt) {
  10404. if (!noPreventDefault) {
  10405. evt.preventDefault();
  10406. }
  10407. switch (pointers.count) {
  10408. case 1:
  10409. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  10410. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  10411. var offsetX = evt.clientX - cacheSoloPointer.x;
  10412. var offsetY = evt.clientY - cacheSoloPointer.y;
  10413. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10414. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10415. //pointers.item(evt.pointerId).x = evt.clientX;
  10416. //pointers.item(evt.pointerId).y = evt.clientY;
  10417. cacheSoloPointer.x = evt.clientX;
  10418. cacheSoloPointer.y = evt.clientY;
  10419. break;
  10420. case 2:
  10421. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10422. pointers.item(evt.pointerId).x = evt.clientX;
  10423. pointers.item(evt.pointerId).y = evt.clientY;
  10424. var direction = _this.pinchInwards ? 1 : -1;
  10425. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10426. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10427. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10428. if (previousPinchDistance === 0) {
  10429. previousPinchDistance = pinchSquaredDistance;
  10430. return;
  10431. }
  10432. if (pinchSquaredDistance !== previousPinchDistance) {
  10433. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10434. previousPinchDistance = pinchSquaredDistance;
  10435. }
  10436. break;
  10437. default:
  10438. if (pointers.item(evt.pointerId)) {
  10439. pointers.item(evt.pointerId).x = evt.clientX;
  10440. pointers.item(evt.pointerId).y = evt.clientY;
  10441. }
  10442. }
  10443. };
  10444. this._onMouseMove = function (evt) {
  10445. if (!engine.isPointerLock) {
  10446. return;
  10447. }
  10448. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10449. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10450. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10451. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10452. if (!noPreventDefault) {
  10453. evt.preventDefault();
  10454. }
  10455. };
  10456. this._wheel = function (event) {
  10457. var delta = 0;
  10458. if (event.wheelDelta) {
  10459. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10460. }
  10461. else if (event.detail) {
  10462. delta = -event.detail / _this.wheelPrecision;
  10463. }
  10464. if (delta)
  10465. _this.inertialRadiusOffset += delta;
  10466. if (event.preventDefault) {
  10467. if (!noPreventDefault) {
  10468. event.preventDefault();
  10469. }
  10470. }
  10471. };
  10472. this._onKeyDown = function (evt) {
  10473. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10474. var index = _this._keys.indexOf(evt.keyCode);
  10475. if (index === -1) {
  10476. _this._keys.push(evt.keyCode);
  10477. }
  10478. if (evt.preventDefault) {
  10479. if (!noPreventDefault) {
  10480. evt.preventDefault();
  10481. }
  10482. }
  10483. }
  10484. };
  10485. this._onKeyUp = function (evt) {
  10486. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10487. var index = _this._keys.indexOf(evt.keyCode);
  10488. if (index >= 0) {
  10489. _this._keys.splice(index, 1);
  10490. }
  10491. if (evt.preventDefault) {
  10492. if (!noPreventDefault) {
  10493. evt.preventDefault();
  10494. }
  10495. }
  10496. }
  10497. };
  10498. this._onLostFocus = function () {
  10499. _this._keys = [];
  10500. pointers.empty();
  10501. previousPinchDistance = 0;
  10502. cacheSoloPointer = null;
  10503. };
  10504. this._onGestureStart = function (e) {
  10505. if (window.MSGesture === undefined) {
  10506. return;
  10507. }
  10508. if (!_this._MSGestureHandler) {
  10509. _this._MSGestureHandler = new MSGesture();
  10510. _this._MSGestureHandler.target = element;
  10511. }
  10512. _this._MSGestureHandler.addPointer(e.pointerId);
  10513. };
  10514. this._onGesture = function (e) {
  10515. _this.radius *= e.scale;
  10516. if (e.preventDefault) {
  10517. if (!noPreventDefault) {
  10518. e.stopPropagation();
  10519. e.preventDefault();
  10520. }
  10521. }
  10522. };
  10523. this._reset = function () {
  10524. _this._keys = [];
  10525. _this.inertialAlphaOffset = 0;
  10526. _this.inertialBetaOffset = 0;
  10527. _this.inertialRadiusOffset = 0;
  10528. pointers.empty();
  10529. previousPinchDistance = 0;
  10530. cacheSoloPointer = null;
  10531. };
  10532. }
  10533. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10534. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10535. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10536. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10537. element.addEventListener("mousemove", this._onMouseMove, false);
  10538. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10539. element.addEventListener("MSGestureChange", this._onGesture, false);
  10540. element.addEventListener('mousewheel', this._wheel, false);
  10541. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10542. BABYLON.Tools.RegisterTopRootEvents([
  10543. { name: "keydown", handler: this._onKeyDown },
  10544. { name: "keyup", handler: this._onKeyUp },
  10545. { name: "blur", handler: this._onLostFocus }
  10546. ]);
  10547. };
  10548. ArcRotateCamera.prototype.detachControl = function (element) {
  10549. if (this._attachedElement !== element) {
  10550. return;
  10551. }
  10552. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10553. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10554. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10555. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10556. element.removeEventListener("mousemove", this._onMouseMove);
  10557. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10558. element.removeEventListener("MSGestureChange", this._onGesture);
  10559. element.removeEventListener('mousewheel', this._wheel);
  10560. element.removeEventListener('DOMMouseScroll', this._wheel);
  10561. BABYLON.Tools.UnregisterTopRootEvents([
  10562. { name: "keydown", handler: this._onKeyDown },
  10563. { name: "keyup", handler: this._onKeyUp },
  10564. { name: "blur", handler: this._onLostFocus }
  10565. ]);
  10566. this._MSGestureHandler = null;
  10567. this._attachedElement = null;
  10568. if (this._reset) {
  10569. this._reset();
  10570. }
  10571. };
  10572. ArcRotateCamera.prototype._update = function () {
  10573. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10574. if (this._collisionTriggered) {
  10575. return;
  10576. }
  10577. for (var index = 0; index < this._keys.length; index++) {
  10578. var keyCode = this._keys[index];
  10579. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10580. this.inertialAlphaOffset -= 0.01;
  10581. }
  10582. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10583. this.inertialBetaOffset -= 0.01;
  10584. }
  10585. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10586. this.inertialAlphaOffset += 0.01;
  10587. }
  10588. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10589. this.inertialBetaOffset += 0.01;
  10590. }
  10591. }
  10592. // Inertia
  10593. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  10594. this.alpha += this.inertialAlphaOffset;
  10595. this.beta += this.inertialBetaOffset;
  10596. this.radius -= this.inertialRadiusOffset;
  10597. this.inertialAlphaOffset *= this.inertia;
  10598. this.inertialBetaOffset *= this.inertia;
  10599. this.inertialRadiusOffset *= this.inertia;
  10600. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  10601. this.inertialAlphaOffset = 0;
  10602. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  10603. this.inertialBetaOffset = 0;
  10604. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  10605. this.inertialRadiusOffset = 0;
  10606. }
  10607. // Limits
  10608. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  10609. this.alpha = this.lowerAlphaLimit;
  10610. }
  10611. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  10612. this.alpha = this.upperAlphaLimit;
  10613. }
  10614. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  10615. this.beta = this.lowerBetaLimit;
  10616. }
  10617. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  10618. this.beta = this.upperBetaLimit;
  10619. }
  10620. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  10621. this.radius = this.lowerRadiusLimit;
  10622. }
  10623. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  10624. this.radius = this.upperRadiusLimit;
  10625. }
  10626. };
  10627. ArcRotateCamera.prototype.setPosition = function (position) {
  10628. var radiusv3 = position.subtract(this._getTargetPosition());
  10629. this.radius = radiusv3.length();
  10630. // Alpha
  10631. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  10632. if (radiusv3.z < 0) {
  10633. this.alpha = 2 * Math.PI - this.alpha;
  10634. }
  10635. // Beta
  10636. this.beta = Math.acos(radiusv3.y / this.radius);
  10637. };
  10638. ArcRotateCamera.prototype._getViewMatrix = function () {
  10639. // Compute
  10640. var cosa = Math.cos(this.alpha);
  10641. var sina = Math.sin(this.alpha);
  10642. var cosb = Math.cos(this.beta);
  10643. var sinb = Math.sin(this.beta);
  10644. var target = this._getTargetPosition();
  10645. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  10646. if (this.checkCollisions) {
  10647. this._collider.radius = this.collisionRadius;
  10648. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  10649. this._collisionTriggered = true;
  10650. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10651. }
  10652. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  10653. this._previousAlpha = this.alpha;
  10654. this._previousBeta = this.beta;
  10655. this._previousRadius = this.radius;
  10656. this._previousPosition.copyFrom(this.position);
  10657. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  10658. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  10659. return this._viewMatrix;
  10660. };
  10661. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  10662. meshes = meshes || this.getScene().meshes;
  10663. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  10664. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  10665. this.radius = distance * this.zoomOnFactor;
  10666. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  10667. };
  10668. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  10669. var meshesOrMinMaxVector;
  10670. var distance;
  10671. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  10672. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  10673. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10674. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  10675. }
  10676. else {
  10677. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  10678. distance = meshesOrMinMaxVectorAndDistance.distance;
  10679. }
  10680. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  10681. this.maxZ = distance * 2;
  10682. };
  10683. return ArcRotateCamera;
  10684. })(BABYLON.Camera);
  10685. BABYLON.ArcRotateCamera = ArcRotateCamera;
  10686. })(BABYLON || (BABYLON = {}));
  10687. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  10688. var __extends = this.__extends || function (d, b) {
  10689. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10690. function __() { this.constructor = d; }
  10691. __.prototype = b.prototype;
  10692. d.prototype = new __();
  10693. };
  10694. var BABYLON;
  10695. (function (BABYLON) {
  10696. // We're mainly based on the logic defined into the FreeCamera code
  10697. var DeviceOrientationCamera = (function (_super) {
  10698. __extends(DeviceOrientationCamera, _super);
  10699. function DeviceOrientationCamera(name, position, scene) {
  10700. var _this = this;
  10701. _super.call(this, name, position, scene);
  10702. this._offsetX = null;
  10703. this._offsetY = null;
  10704. this._orientationGamma = 0;
  10705. this._orientationBeta = 0;
  10706. this._initialOrientationGamma = 0;
  10707. this._initialOrientationBeta = 0;
  10708. this.angularSensibility = 10000.0;
  10709. this.moveSensibility = 50.0;
  10710. window.addEventListener("resize", function () {
  10711. _this._initialOrientationGamma = null;
  10712. }, false);
  10713. }
  10714. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10715. var _this = this;
  10716. if (this._attachedCanvas) {
  10717. return;
  10718. }
  10719. this._attachedCanvas = canvas;
  10720. if (!this._orientationChanged) {
  10721. this._orientationChanged = function (evt) {
  10722. if (!_this._initialOrientationGamma) {
  10723. _this._initialOrientationGamma = evt.gamma;
  10724. _this._initialOrientationBeta = evt.beta;
  10725. }
  10726. _this._orientationGamma = evt.gamma;
  10727. _this._orientationBeta = evt.beta;
  10728. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  10729. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  10730. };
  10731. }
  10732. window.addEventListener("deviceorientation", this._orientationChanged);
  10733. };
  10734. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  10735. if (this._attachedCanvas != canvas) {
  10736. return;
  10737. }
  10738. window.removeEventListener("deviceorientation", this._orientationChanged);
  10739. this._attachedCanvas = null;
  10740. this._orientationGamma = 0;
  10741. this._orientationBeta = 0;
  10742. this._initialOrientationGamma = 0;
  10743. this._initialOrientationBeta = 0;
  10744. };
  10745. DeviceOrientationCamera.prototype._checkInputs = function () {
  10746. if (!this._offsetX) {
  10747. return;
  10748. }
  10749. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  10750. var speed = this._computeLocalCameraSpeed();
  10751. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10752. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10753. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10754. };
  10755. return DeviceOrientationCamera;
  10756. })(BABYLON.FreeCamera);
  10757. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  10758. })(BABYLON || (BABYLON = {}));
  10759. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  10760. var BABYLON;
  10761. (function (BABYLON) {
  10762. var RenderingManager = (function () {
  10763. function RenderingManager(scene) {
  10764. this._renderingGroups = new Array();
  10765. this._scene = scene;
  10766. }
  10767. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10768. if (this._scene._activeParticleSystems.length === 0) {
  10769. return;
  10770. }
  10771. // Particles
  10772. var beforeParticlesDate = BABYLON.Tools.Now;
  10773. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10774. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10775. if (particleSystem.renderingGroupId !== index) {
  10776. continue;
  10777. }
  10778. this._clearDepthBuffer();
  10779. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10780. this._scene._activeParticles += particleSystem.render();
  10781. }
  10782. }
  10783. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10784. };
  10785. RenderingManager.prototype._renderSprites = function (index) {
  10786. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  10787. return;
  10788. }
  10789. // Sprites
  10790. var beforeSpritessDate = BABYLON.Tools.Now;
  10791. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10792. var spriteManager = this._scene.spriteManagers[id];
  10793. if (spriteManager.renderingGroupId === index) {
  10794. this._clearDepthBuffer();
  10795. spriteManager.render();
  10796. }
  10797. }
  10798. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10799. };
  10800. RenderingManager.prototype._clearDepthBuffer = function () {
  10801. if (this._depthBufferAlreadyCleaned) {
  10802. return;
  10803. }
  10804. this._scene.getEngine().clear(0, false, true);
  10805. this._depthBufferAlreadyCleaned = true;
  10806. };
  10807. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10808. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10809. this._depthBufferAlreadyCleaned = false;
  10810. var renderingGroup = this._renderingGroups[index];
  10811. var needToStepBack = false;
  10812. if (renderingGroup) {
  10813. this._clearDepthBuffer();
  10814. if (!renderingGroup.render(customRenderFunction)) {
  10815. this._renderingGroups.splice(index, 1);
  10816. needToStepBack = true;
  10817. }
  10818. }
  10819. if (renderSprites) {
  10820. this._renderSprites(index);
  10821. }
  10822. if (renderParticles) {
  10823. this._renderParticles(index, activeMeshes);
  10824. }
  10825. if (needToStepBack) {
  10826. index--;
  10827. }
  10828. }
  10829. };
  10830. RenderingManager.prototype.reset = function () {
  10831. for (var index in this._renderingGroups) {
  10832. var renderingGroup = this._renderingGroups[index];
  10833. renderingGroup.prepare();
  10834. }
  10835. };
  10836. RenderingManager.prototype.dispatch = function (subMesh) {
  10837. var mesh = subMesh.getMesh();
  10838. var renderingGroupId = mesh.renderingGroupId || 0;
  10839. if (!this._renderingGroups[renderingGroupId]) {
  10840. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10841. }
  10842. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10843. };
  10844. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10845. return RenderingManager;
  10846. })();
  10847. BABYLON.RenderingManager = RenderingManager;
  10848. })(BABYLON || (BABYLON = {}));
  10849. //# sourceMappingURL=babylon.renderingManager.js.map
  10850. var BABYLON;
  10851. (function (BABYLON) {
  10852. var RenderingGroup = (function () {
  10853. function RenderingGroup(index, scene) {
  10854. this.index = index;
  10855. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10856. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10857. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10858. this._scene = scene;
  10859. }
  10860. RenderingGroup.prototype.render = function (customRenderFunction) {
  10861. if (customRenderFunction) {
  10862. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10863. return true;
  10864. }
  10865. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10866. return false;
  10867. }
  10868. var engine = this._scene.getEngine();
  10869. // Opaque
  10870. var subIndex;
  10871. var submesh;
  10872. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10873. submesh = this._opaqueSubMeshes.data[subIndex];
  10874. submesh.render();
  10875. }
  10876. // Alpha test
  10877. engine.setAlphaTesting(true);
  10878. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10879. submesh = this._alphaTestSubMeshes.data[subIndex];
  10880. submesh.render();
  10881. }
  10882. engine.setAlphaTesting(false);
  10883. // Transparent
  10884. if (this._transparentSubMeshes.length) {
  10885. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10886. submesh = this._transparentSubMeshes.data[subIndex];
  10887. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10888. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10889. }
  10890. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10891. sortedArray.sort(function (a, b) {
  10892. // Alpha index first
  10893. if (a._alphaIndex > b._alphaIndex) {
  10894. return 1;
  10895. }
  10896. if (a._alphaIndex < b._alphaIndex) {
  10897. return -1;
  10898. }
  10899. // Then distance to camera
  10900. if (a._distanceToCamera < b._distanceToCamera) {
  10901. return 1;
  10902. }
  10903. if (a._distanceToCamera > b._distanceToCamera) {
  10904. return -1;
  10905. }
  10906. return 0;
  10907. });
  10908. // Rendering
  10909. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10910. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10911. submesh = sortedArray[subIndex];
  10912. submesh.render();
  10913. }
  10914. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10915. }
  10916. return true;
  10917. };
  10918. RenderingGroup.prototype.prepare = function () {
  10919. this._opaqueSubMeshes.reset();
  10920. this._transparentSubMeshes.reset();
  10921. this._alphaTestSubMeshes.reset();
  10922. };
  10923. RenderingGroup.prototype.dispatch = function (subMesh) {
  10924. var material = subMesh.getMaterial();
  10925. var mesh = subMesh.getMesh();
  10926. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10927. this._transparentSubMeshes.push(subMesh);
  10928. }
  10929. else if (material.needAlphaTesting()) {
  10930. this._alphaTestSubMeshes.push(subMesh);
  10931. }
  10932. else {
  10933. this._opaqueSubMeshes.push(subMesh); // Opaque
  10934. }
  10935. };
  10936. return RenderingGroup;
  10937. })();
  10938. BABYLON.RenderingGroup = RenderingGroup;
  10939. })(BABYLON || (BABYLON = {}));
  10940. //# sourceMappingURL=babylon.renderingGroup.js.map
  10941. var BABYLON;
  10942. (function (BABYLON) {
  10943. /**
  10944. * Represents a scene to be rendered by the engine.
  10945. * @see http://doc.babylonjs.com/page.php?p=21911
  10946. */
  10947. var Scene = (function () {
  10948. /**
  10949. * @constructor
  10950. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  10951. */
  10952. function Scene(engine) {
  10953. // Members
  10954. this.autoClear = true;
  10955. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  10956. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10957. this.forceWireframe = false;
  10958. this.forcePointsCloud = false;
  10959. this.forceShowBoundingBoxes = false;
  10960. this.animationsEnabled = true;
  10961. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  10962. // Fog
  10963. /**
  10964. * is fog enabled on this scene.
  10965. * @type {boolean}
  10966. */
  10967. this.fogEnabled = true;
  10968. this.fogMode = Scene.FOGMODE_NONE;
  10969. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  10970. this.fogDensity = 0.1;
  10971. this.fogStart = 0;
  10972. this.fogEnd = 1000.0;
  10973. // Lights
  10974. /**
  10975. * is shadow enabled on this scene.
  10976. * @type {boolean}
  10977. */
  10978. this.shadowsEnabled = true;
  10979. /**
  10980. * is light enabled on this scene.
  10981. * @type {boolean}
  10982. */
  10983. this.lightsEnabled = true;
  10984. /**
  10985. * All of the lights added to this scene.
  10986. * @see BABYLON.Light
  10987. * @type {BABYLON.Light[]}
  10988. */
  10989. this.lights = new Array();
  10990. // Cameras
  10991. /**
  10992. * All of the cameras added to this scene.
  10993. * @see BABYLON.Camera
  10994. * @type {BABYLON.Camera[]}
  10995. */
  10996. this.cameras = new Array();
  10997. this.activeCameras = new Array();
  10998. // Meshes
  10999. /**
  11000. * All of the (abstract) meshes added to this scene.
  11001. * @see BABYLON.AbstractMesh
  11002. * @type {BABYLON.AbstractMesh[]}
  11003. */
  11004. this.meshes = new Array();
  11005. // Geometries
  11006. this._geometries = new Array();
  11007. this.materials = new Array();
  11008. this.multiMaterials = new Array();
  11009. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11010. // Textures
  11011. this.texturesEnabled = true;
  11012. this.textures = new Array();
  11013. // Particles
  11014. this.particlesEnabled = true;
  11015. this.particleSystems = new Array();
  11016. // Sprites
  11017. this.spritesEnabled = true;
  11018. this.spriteManagers = new Array();
  11019. // Layers
  11020. this.layers = new Array();
  11021. // Skeletons
  11022. this.skeletonsEnabled = true;
  11023. this.skeletons = new Array();
  11024. // Lens flares
  11025. this.lensFlaresEnabled = true;
  11026. this.lensFlareSystems = new Array();
  11027. // Collisions
  11028. this.collisionsEnabled = true;
  11029. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  11030. // Postprocesses
  11031. this.postProcessesEnabled = true;
  11032. // Customs render targets
  11033. this.renderTargetsEnabled = true;
  11034. this.dumpNextRenderTargets = false;
  11035. this.customRenderTargets = new Array();
  11036. // Imported meshes
  11037. this.importedMeshesFiles = new Array();
  11038. this._actionManagers = new Array();
  11039. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11040. // Procedural textures
  11041. this.proceduralTexturesEnabled = true;
  11042. this._proceduralTextures = new Array();
  11043. this.soundTracks = new Array();
  11044. this._audioEnabled = true;
  11045. this._headphone = false;
  11046. this._totalVertices = 0;
  11047. this._activeIndices = 0;
  11048. this._activeParticles = 0;
  11049. this._lastFrameDuration = 0;
  11050. this._evaluateActiveMeshesDuration = 0;
  11051. this._renderTargetsDuration = 0;
  11052. this._particlesDuration = 0;
  11053. this._renderDuration = 0;
  11054. this._spritesDuration = 0;
  11055. this._animationRatio = 0;
  11056. this._renderId = 0;
  11057. this._executeWhenReadyTimeoutId = -1;
  11058. this._toBeDisposed = new BABYLON.SmartArray(256);
  11059. this._onReadyCallbacks = new Array();
  11060. this._pendingData = []; //ANY
  11061. this._onBeforeRenderCallbacks = new Array();
  11062. this._onAfterRenderCallbacks = new Array();
  11063. this._activeMeshes = new BABYLON.SmartArray(256);
  11064. this._processedMaterials = new BABYLON.SmartArray(256);
  11065. this._renderTargets = new BABYLON.SmartArray(256);
  11066. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11067. this._activeSkeletons = new BABYLON.SmartArray(32);
  11068. this._activeBones = 0;
  11069. this._activeAnimatables = new Array();
  11070. this._transformMatrix = BABYLON.Matrix.Zero();
  11071. this._uniqueIdCounter = 0;
  11072. this._engine = engine;
  11073. engine.scenes.push(this);
  11074. this._renderingManager = new BABYLON.RenderingManager(this);
  11075. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11076. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11077. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11078. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11079. this.attachControl();
  11080. this._debugLayer = new BABYLON.DebugLayer(this);
  11081. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11082. //simplification queue
  11083. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11084. //collision coordinator initialization. For now legacy per default.
  11085. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11086. }
  11087. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11088. get: function () {
  11089. return Scene._FOGMODE_NONE;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11095. get: function () {
  11096. return Scene._FOGMODE_EXP;
  11097. },
  11098. enumerable: true,
  11099. configurable: true
  11100. });
  11101. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11102. get: function () {
  11103. return Scene._FOGMODE_EXP2;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11109. get: function () {
  11110. return Scene._FOGMODE_LINEAR;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Scene.prototype, "debugLayer", {
  11116. // Properties
  11117. get: function () {
  11118. return this._debugLayer;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11124. get: function () {
  11125. return this._workerCollisions;
  11126. },
  11127. set: function (enabled) {
  11128. enabled = (enabled && !!Worker);
  11129. this._workerCollisions = enabled;
  11130. if (this.collisionCoordinator) {
  11131. this.collisionCoordinator.destroy();
  11132. }
  11133. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11134. this.collisionCoordinator.init(this);
  11135. },
  11136. enumerable: true,
  11137. configurable: true
  11138. });
  11139. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11140. /**
  11141. * The mesh that is currently under the pointer.
  11142. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11143. */
  11144. get: function () {
  11145. return this._meshUnderPointer;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. Object.defineProperty(Scene.prototype, "pointerX", {
  11151. /**
  11152. * Current on-screen X position of the pointer
  11153. * @return {number} X position of the pointer
  11154. */
  11155. get: function () {
  11156. return this._pointerX;
  11157. },
  11158. enumerable: true,
  11159. configurable: true
  11160. });
  11161. Object.defineProperty(Scene.prototype, "pointerY", {
  11162. /**
  11163. * Current on-screen Y position of the pointer
  11164. * @return {number} Y position of the pointer
  11165. */
  11166. get: function () {
  11167. return this._pointerY;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Scene.prototype.getCachedMaterial = function () {
  11173. return this._cachedMaterial;
  11174. };
  11175. Scene.prototype.getBoundingBoxRenderer = function () {
  11176. return this._boundingBoxRenderer;
  11177. };
  11178. Scene.prototype.getOutlineRenderer = function () {
  11179. return this._outlineRenderer;
  11180. };
  11181. Scene.prototype.getEngine = function () {
  11182. return this._engine;
  11183. };
  11184. Scene.prototype.getTotalVertices = function () {
  11185. return this._totalVertices;
  11186. };
  11187. Scene.prototype.getActiveIndices = function () {
  11188. return this._activeIndices;
  11189. };
  11190. Scene.prototype.getActiveParticles = function () {
  11191. return this._activeParticles;
  11192. };
  11193. Scene.prototype.getActiveBones = function () {
  11194. return this._activeBones;
  11195. };
  11196. // Stats
  11197. Scene.prototype.getLastFrameDuration = function () {
  11198. return this._lastFrameDuration;
  11199. };
  11200. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11201. return this._evaluateActiveMeshesDuration;
  11202. };
  11203. Scene.prototype.getActiveMeshes = function () {
  11204. return this._activeMeshes;
  11205. };
  11206. Scene.prototype.getRenderTargetsDuration = function () {
  11207. return this._renderTargetsDuration;
  11208. };
  11209. Scene.prototype.getRenderDuration = function () {
  11210. return this._renderDuration;
  11211. };
  11212. Scene.prototype.getParticlesDuration = function () {
  11213. return this._particlesDuration;
  11214. };
  11215. Scene.prototype.getSpritesDuration = function () {
  11216. return this._spritesDuration;
  11217. };
  11218. Scene.prototype.getAnimationRatio = function () {
  11219. return this._animationRatio;
  11220. };
  11221. Scene.prototype.getRenderId = function () {
  11222. return this._renderId;
  11223. };
  11224. Scene.prototype.incrementRenderId = function () {
  11225. this._renderId++;
  11226. };
  11227. Scene.prototype._updatePointerPosition = function (evt) {
  11228. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11229. this._pointerX = evt.clientX - canvasRect.left;
  11230. this._pointerY = evt.clientY - canvasRect.top;
  11231. if (this.cameraToUseForPointers) {
  11232. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11233. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11234. }
  11235. };
  11236. // Pointers handling
  11237. Scene.prototype.attachControl = function () {
  11238. var _this = this;
  11239. this._onPointerMove = function (evt) {
  11240. var canvas = _this._engine.getRenderingCanvas();
  11241. _this._updatePointerPosition(evt);
  11242. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  11243. if (pickResult.hit) {
  11244. _this._meshUnderPointer = pickResult.pickedMesh;
  11245. _this.setPointerOverMesh(pickResult.pickedMesh);
  11246. canvas.style.cursor = "pointer";
  11247. }
  11248. else {
  11249. _this.setPointerOverMesh(null);
  11250. canvas.style.cursor = "";
  11251. _this._meshUnderPointer = null;
  11252. }
  11253. };
  11254. this._onPointerDown = function (evt) {
  11255. var predicate = null;
  11256. if (!_this.onPointerDown) {
  11257. predicate = function (mesh) {
  11258. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11259. };
  11260. }
  11261. _this._updatePointerPosition(evt);
  11262. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11263. if (pickResult.hit) {
  11264. if (pickResult.pickedMesh.actionManager) {
  11265. switch (evt.button) {
  11266. case 0:
  11267. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11268. break;
  11269. case 1:
  11270. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11271. break;
  11272. case 2:
  11273. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11274. break;
  11275. }
  11276. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11277. }
  11278. }
  11279. if (_this.onPointerDown) {
  11280. _this.onPointerDown(evt, pickResult);
  11281. }
  11282. };
  11283. this._onPointerUp = function (evt) {
  11284. var predicate = null;
  11285. if (!_this.onPointerUp) {
  11286. predicate = function (mesh) {
  11287. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11288. };
  11289. }
  11290. _this._updatePointerPosition(evt);
  11291. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11292. if (pickResult.hit) {
  11293. if (pickResult.pickedMesh.actionManager) {
  11294. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11295. }
  11296. }
  11297. if (_this.onPointerUp) {
  11298. _this.onPointerUp(evt, pickResult);
  11299. }
  11300. };
  11301. this._onKeyDown = function (evt) {
  11302. if (_this.actionManager) {
  11303. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11304. }
  11305. };
  11306. this._onKeyUp = function (evt) {
  11307. if (_this.actionManager) {
  11308. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11309. }
  11310. };
  11311. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11312. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11313. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11314. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11315. BABYLON.Tools.RegisterTopRootEvents([
  11316. { name: "keydown", handler: this._onKeyDown },
  11317. { name: "keyup", handler: this._onKeyUp }
  11318. ]);
  11319. };
  11320. Scene.prototype.detachControl = function () {
  11321. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11322. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11323. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11324. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11325. BABYLON.Tools.UnregisterTopRootEvents([
  11326. { name: "keydown", handler: this._onKeyDown },
  11327. { name: "keyup", handler: this._onKeyUp }
  11328. ]);
  11329. };
  11330. // Ready
  11331. Scene.prototype.isReady = function () {
  11332. if (this._pendingData.length > 0) {
  11333. return false;
  11334. }
  11335. for (var index = 0; index < this._geometries.length; index++) {
  11336. var geometry = this._geometries[index];
  11337. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11338. return false;
  11339. }
  11340. }
  11341. for (index = 0; index < this.meshes.length; index++) {
  11342. var mesh = this.meshes[index];
  11343. if (!mesh.isReady()) {
  11344. return false;
  11345. }
  11346. var mat = mesh.material;
  11347. if (mat) {
  11348. if (!mat.isReady(mesh)) {
  11349. return false;
  11350. }
  11351. }
  11352. }
  11353. return true;
  11354. };
  11355. Scene.prototype.resetCachedMaterial = function () {
  11356. this._cachedMaterial = null;
  11357. };
  11358. Scene.prototype.registerBeforeRender = function (func) {
  11359. this._onBeforeRenderCallbacks.push(func);
  11360. };
  11361. Scene.prototype.unregisterBeforeRender = function (func) {
  11362. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11363. if (index > -1) {
  11364. this._onBeforeRenderCallbacks.splice(index, 1);
  11365. }
  11366. };
  11367. Scene.prototype.registerAfterRender = function (func) {
  11368. this._onAfterRenderCallbacks.push(func);
  11369. };
  11370. Scene.prototype.unregisterAfterRender = function (func) {
  11371. var index = this._onAfterRenderCallbacks.indexOf(func);
  11372. if (index > -1) {
  11373. this._onAfterRenderCallbacks.splice(index, 1);
  11374. }
  11375. };
  11376. Scene.prototype._addPendingData = function (data) {
  11377. this._pendingData.push(data);
  11378. };
  11379. Scene.prototype._removePendingData = function (data) {
  11380. var index = this._pendingData.indexOf(data);
  11381. if (index !== -1) {
  11382. this._pendingData.splice(index, 1);
  11383. }
  11384. };
  11385. Scene.prototype.getWaitingItemsCount = function () {
  11386. return this._pendingData.length;
  11387. };
  11388. /**
  11389. * Registers a function to be executed when the scene is ready.
  11390. * @param {Function} func - the function to be executed.
  11391. */
  11392. Scene.prototype.executeWhenReady = function (func) {
  11393. var _this = this;
  11394. this._onReadyCallbacks.push(func);
  11395. if (this._executeWhenReadyTimeoutId !== -1) {
  11396. return;
  11397. }
  11398. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11399. _this._checkIsReady();
  11400. }, 150);
  11401. };
  11402. Scene.prototype._checkIsReady = function () {
  11403. var _this = this;
  11404. if (this.isReady()) {
  11405. this._onReadyCallbacks.forEach(function (func) {
  11406. func();
  11407. });
  11408. this._onReadyCallbacks = [];
  11409. this._executeWhenReadyTimeoutId = -1;
  11410. return;
  11411. }
  11412. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11413. _this._checkIsReady();
  11414. }, 150);
  11415. };
  11416. // Animations
  11417. /**
  11418. * Will start the animation sequence of a given target
  11419. * @param target - the target
  11420. * @param {number} from - from which frame should animation start
  11421. * @param {number} to - till which frame should animation run.
  11422. * @param {boolean} [loop] - should the animation loop
  11423. * @param {number} [speedRatio] - the speed in which to run the animation
  11424. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  11425. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  11426. * @return {BABYLON.Animatable} the animatable object created for this animation
  11427. * @see BABYLON.Animatable
  11428. * @see http://doc.babylonjs.com/page.php?p=22081
  11429. */
  11430. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  11431. if (speedRatio === undefined) {
  11432. speedRatio = 1.0;
  11433. }
  11434. this.stopAnimation(target);
  11435. if (!animatable) {
  11436. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  11437. }
  11438. // Local animations
  11439. if (target.animations) {
  11440. animatable.appendAnimations(target, target.animations);
  11441. }
  11442. // Children animations
  11443. if (target.getAnimatables) {
  11444. var animatables = target.getAnimatables();
  11445. for (var index = 0; index < animatables.length; index++) {
  11446. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  11447. }
  11448. }
  11449. return animatable;
  11450. };
  11451. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  11452. if (speedRatio === undefined) {
  11453. speedRatio = 1.0;
  11454. }
  11455. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  11456. return animatable;
  11457. };
  11458. Scene.prototype.getAnimatableByTarget = function (target) {
  11459. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11460. if (this._activeAnimatables[index].target === target) {
  11461. return this._activeAnimatables[index];
  11462. }
  11463. }
  11464. return null;
  11465. };
  11466. /**
  11467. * Will stop the animation of the given target
  11468. * @param target - the target
  11469. * @see beginAnimation
  11470. */
  11471. Scene.prototype.stopAnimation = function (target) {
  11472. var animatable = this.getAnimatableByTarget(target);
  11473. if (animatable) {
  11474. animatable.stop();
  11475. }
  11476. };
  11477. Scene.prototype._animate = function () {
  11478. if (!this.animationsEnabled) {
  11479. return;
  11480. }
  11481. if (!this._animationStartDate) {
  11482. this._animationStartDate = BABYLON.Tools.Now;
  11483. }
  11484. // Getting time
  11485. var now = BABYLON.Tools.Now;
  11486. var delay = now - this._animationStartDate;
  11487. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11488. this._activeAnimatables[index]._animate(delay);
  11489. }
  11490. };
  11491. // Matrix
  11492. Scene.prototype.getViewMatrix = function () {
  11493. return this._viewMatrix;
  11494. };
  11495. Scene.prototype.getProjectionMatrix = function () {
  11496. return this._projectionMatrix;
  11497. };
  11498. Scene.prototype.getTransformMatrix = function () {
  11499. return this._transformMatrix;
  11500. };
  11501. Scene.prototype.setTransformMatrix = function (view, projection) {
  11502. this._viewMatrix = view;
  11503. this._projectionMatrix = projection;
  11504. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11505. };
  11506. // Methods
  11507. Scene.prototype.addMesh = function (newMesh) {
  11508. newMesh.uniqueId = this._uniqueIdCounter++;
  11509. var position = this.meshes.push(newMesh);
  11510. //notify the collision coordinator
  11511. this.collisionCoordinator.onMeshAdded(newMesh);
  11512. if (this.onNewMeshAdded) {
  11513. this.onNewMeshAdded(newMesh, position, this);
  11514. }
  11515. };
  11516. Scene.prototype.removeMesh = function (toRemove) {
  11517. var index = this.meshes.indexOf(toRemove);
  11518. if (index !== -1) {
  11519. // Remove from the scene if mesh found
  11520. this.meshes.splice(index, 1);
  11521. }
  11522. //notify the collision coordinator
  11523. this.collisionCoordinator.onMeshRemoved(toRemove);
  11524. if (this.onMeshRemoved) {
  11525. this.onMeshRemoved(toRemove);
  11526. }
  11527. return index;
  11528. };
  11529. Scene.prototype.removeLight = function (toRemove) {
  11530. var index = this.lights.indexOf(toRemove);
  11531. if (index !== -1) {
  11532. // Remove from the scene if mesh found
  11533. this.lights.splice(index, 1);
  11534. }
  11535. if (this.onLightRemoved) {
  11536. this.onLightRemoved(toRemove);
  11537. }
  11538. return index;
  11539. };
  11540. Scene.prototype.removeCamera = function (toRemove) {
  11541. var index = this.cameras.indexOf(toRemove);
  11542. if (index !== -1) {
  11543. // Remove from the scene if mesh found
  11544. this.cameras.splice(index, 1);
  11545. }
  11546. // Remove from activeCameras
  11547. var index2 = this.activeCameras.indexOf(toRemove);
  11548. if (index2 !== -1) {
  11549. // Remove from the scene if mesh found
  11550. this.activeCameras.splice(index2, 1);
  11551. }
  11552. // Reset the activeCamera
  11553. if (this.activeCamera === toRemove) {
  11554. if (this.cameras.length > 0) {
  11555. this.activeCamera = this.cameras[0];
  11556. }
  11557. else {
  11558. this.activeCamera = null;
  11559. }
  11560. }
  11561. if (this.onCameraRemoved) {
  11562. this.onCameraRemoved(toRemove);
  11563. }
  11564. return index;
  11565. };
  11566. Scene.prototype.addLight = function (newLight) {
  11567. newLight.uniqueId = this._uniqueIdCounter++;
  11568. var position = this.lights.push(newLight);
  11569. if (this.onNewLightAdded) {
  11570. this.onNewLightAdded(newLight, position, this);
  11571. }
  11572. };
  11573. Scene.prototype.addCamera = function (newCamera) {
  11574. newCamera.uniqueId = this._uniqueIdCounter++;
  11575. var position = this.cameras.push(newCamera);
  11576. if (this.onNewCameraAdded) {
  11577. this.onNewCameraAdded(newCamera, position, this);
  11578. }
  11579. };
  11580. /**
  11581. * sets the active camera of the scene using its ID
  11582. * @param {string} id - the camera's ID
  11583. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11584. * @see activeCamera
  11585. */
  11586. Scene.prototype.setActiveCameraByID = function (id) {
  11587. var camera = this.getCameraByID(id);
  11588. if (camera) {
  11589. this.activeCamera = camera;
  11590. return camera;
  11591. }
  11592. return null;
  11593. };
  11594. /**
  11595. * sets the active camera of the scene using its name
  11596. * @param {string} name - the camera's name
  11597. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11598. * @see activeCamera
  11599. */
  11600. Scene.prototype.setActiveCameraByName = function (name) {
  11601. var camera = this.getCameraByName(name);
  11602. if (camera) {
  11603. this.activeCamera = camera;
  11604. return camera;
  11605. }
  11606. return null;
  11607. };
  11608. /**
  11609. * get a material using its id
  11610. * @param {string} the material's ID
  11611. * @return {BABYLON.Material|null} the material or null if none found.
  11612. */
  11613. Scene.prototype.getMaterialByID = function (id) {
  11614. for (var index = 0; index < this.materials.length; index++) {
  11615. if (this.materials[index].id === id) {
  11616. return this.materials[index];
  11617. }
  11618. }
  11619. return null;
  11620. };
  11621. /**
  11622. * get a material using its name
  11623. * @param {string} the material's name
  11624. * @return {BABYLON.Material|null} the material or null if none found.
  11625. */
  11626. Scene.prototype.getMaterialByName = function (name) {
  11627. for (var index = 0; index < this.materials.length; index++) {
  11628. if (this.materials[index].name === name) {
  11629. return this.materials[index];
  11630. }
  11631. }
  11632. return null;
  11633. };
  11634. Scene.prototype.getCameraByID = function (id) {
  11635. for (var index = 0; index < this.cameras.length; index++) {
  11636. if (this.cameras[index].id === id) {
  11637. return this.cameras[index];
  11638. }
  11639. }
  11640. return null;
  11641. };
  11642. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  11643. for (var index = 0; index < this.cameras.length; index++) {
  11644. if (this.cameras[index].uniqueId === uniqueId) {
  11645. return this.cameras[index];
  11646. }
  11647. }
  11648. return null;
  11649. };
  11650. /**
  11651. * get a camera using its name
  11652. * @param {string} the camera's name
  11653. * @return {BABYLON.Camera|null} the camera or null if none found.
  11654. */
  11655. Scene.prototype.getCameraByName = function (name) {
  11656. for (var index = 0; index < this.cameras.length; index++) {
  11657. if (this.cameras[index].name === name) {
  11658. return this.cameras[index];
  11659. }
  11660. }
  11661. return null;
  11662. };
  11663. /**
  11664. * get a light node using its name
  11665. * @param {string} the light's name
  11666. * @return {BABYLON.Light|null} the light or null if none found.
  11667. */
  11668. Scene.prototype.getLightByName = function (name) {
  11669. for (var index = 0; index < this.lights.length; index++) {
  11670. if (this.lights[index].name === name) {
  11671. return this.lights[index];
  11672. }
  11673. }
  11674. return null;
  11675. };
  11676. /**
  11677. * get a light node using its ID
  11678. * @param {string} the light's id
  11679. * @return {BABYLON.Light|null} the light or null if none found.
  11680. */
  11681. Scene.prototype.getLightByID = function (id) {
  11682. for (var index = 0; index < this.lights.length; index++) {
  11683. if (this.lights[index].id === id) {
  11684. return this.lights[index];
  11685. }
  11686. }
  11687. return null;
  11688. };
  11689. /**
  11690. * get a light node using its scene-generated unique ID
  11691. * @param {number} the light's unique id
  11692. * @return {BABYLON.Light|null} the light or null if none found.
  11693. */
  11694. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  11695. for (var index = 0; index < this.lights.length; index++) {
  11696. if (this.lights[index].uniqueId === uniqueId) {
  11697. return this.lights[index];
  11698. }
  11699. }
  11700. return null;
  11701. };
  11702. /**
  11703. * get a geometry using its ID
  11704. * @param {string} the geometry's id
  11705. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  11706. */
  11707. Scene.prototype.getGeometryByID = function (id) {
  11708. for (var index = 0; index < this._geometries.length; index++) {
  11709. if (this._geometries[index].id === id) {
  11710. return this._geometries[index];
  11711. }
  11712. }
  11713. return null;
  11714. };
  11715. /**
  11716. * add a new geometry to this scene.
  11717. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  11718. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  11719. * @return {boolean} was the geometry added or not
  11720. */
  11721. Scene.prototype.pushGeometry = function (geometry, force) {
  11722. if (!force && this.getGeometryByID(geometry.id)) {
  11723. return false;
  11724. }
  11725. this._geometries.push(geometry);
  11726. //notify the collision coordinator
  11727. this.collisionCoordinator.onGeometryAdded(geometry);
  11728. if (this.onGeometryAdded) {
  11729. this.onGeometryAdded(geometry);
  11730. }
  11731. return true;
  11732. };
  11733. /**
  11734. * Removes an existing geometry
  11735. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  11736. * @return {boolean} was the geometry removed or not
  11737. */
  11738. Scene.prototype.removeGeometry = function (geometry) {
  11739. var index = this._geometries.indexOf(geometry);
  11740. if (index > -1) {
  11741. this._geometries.splice(index, 1);
  11742. //notify the collision coordinator
  11743. this.collisionCoordinator.onGeometryDeleted(geometry);
  11744. if (this.onGeometryRemoved) {
  11745. this.onGeometryRemoved(geometry);
  11746. }
  11747. return true;
  11748. }
  11749. return false;
  11750. };
  11751. Scene.prototype.getGeometries = function () {
  11752. return this._geometries;
  11753. };
  11754. /**
  11755. * Get the first added mesh found of a given ID
  11756. * @param {string} id - the id to search for
  11757. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11758. */
  11759. Scene.prototype.getMeshByID = function (id) {
  11760. for (var index = 0; index < this.meshes.length; index++) {
  11761. if (this.meshes[index].id === id) {
  11762. return this.meshes[index];
  11763. }
  11764. }
  11765. return null;
  11766. };
  11767. /**
  11768. * Get a mesh with its auto-generated unique id
  11769. * @param {number} uniqueId - the unique id to search for
  11770. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11771. */
  11772. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  11773. for (var index = 0; index < this.meshes.length; index++) {
  11774. if (this.meshes[index].uniqueId === uniqueId) {
  11775. return this.meshes[index];
  11776. }
  11777. }
  11778. return null;
  11779. };
  11780. /**
  11781. * Get a the last added mesh found of a given ID
  11782. * @param {string} id - the id to search for
  11783. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11784. */
  11785. Scene.prototype.getLastMeshByID = function (id) {
  11786. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11787. if (this.meshes[index].id === id) {
  11788. return this.meshes[index];
  11789. }
  11790. }
  11791. return null;
  11792. };
  11793. /**
  11794. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  11795. * @param {string} id - the id to search for
  11796. * @return {BABYLON.Node|null} the node found or null if not found at all.
  11797. */
  11798. Scene.prototype.getLastEntryByID = function (id) {
  11799. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11800. if (this.meshes[index].id === id) {
  11801. return this.meshes[index];
  11802. }
  11803. }
  11804. for (index = this.cameras.length - 1; index >= 0; index--) {
  11805. if (this.cameras[index].id === id) {
  11806. return this.cameras[index];
  11807. }
  11808. }
  11809. for (index = this.lights.length - 1; index >= 0; index--) {
  11810. if (this.lights[index].id === id) {
  11811. return this.lights[index];
  11812. }
  11813. }
  11814. return null;
  11815. };
  11816. Scene.prototype.getNodeByName = function (name) {
  11817. var mesh = this.getMeshByName(name);
  11818. if (mesh) {
  11819. return mesh;
  11820. }
  11821. var light = this.getLightByName(name);
  11822. if (light) {
  11823. return light;
  11824. }
  11825. return this.getCameraByName(name);
  11826. };
  11827. Scene.prototype.getMeshByName = function (name) {
  11828. for (var index = 0; index < this.meshes.length; index++) {
  11829. if (this.meshes[index].name === name) {
  11830. return this.meshes[index];
  11831. }
  11832. }
  11833. return null;
  11834. };
  11835. Scene.prototype.getSoundByName = function (name) {
  11836. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  11837. if (this.mainSoundTrack.soundCollection[index].name === name) {
  11838. return this.mainSoundTrack.soundCollection[index];
  11839. }
  11840. }
  11841. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  11842. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  11843. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  11844. return this.soundTracks[sdIndex].soundCollection[index];
  11845. }
  11846. }
  11847. }
  11848. return null;
  11849. };
  11850. Scene.prototype.getLastSkeletonByID = function (id) {
  11851. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  11852. if (this.skeletons[index].id === id) {
  11853. return this.skeletons[index];
  11854. }
  11855. }
  11856. return null;
  11857. };
  11858. Scene.prototype.getSkeletonById = function (id) {
  11859. for (var index = 0; index < this.skeletons.length; index++) {
  11860. if (this.skeletons[index].id === id) {
  11861. return this.skeletons[index];
  11862. }
  11863. }
  11864. return null;
  11865. };
  11866. Scene.prototype.getSkeletonByName = function (name) {
  11867. for (var index = 0; index < this.skeletons.length; index++) {
  11868. if (this.skeletons[index].name === name) {
  11869. return this.skeletons[index];
  11870. }
  11871. }
  11872. return null;
  11873. };
  11874. Scene.prototype.isActiveMesh = function (mesh) {
  11875. return (this._activeMeshes.indexOf(mesh) !== -1);
  11876. };
  11877. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  11878. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  11879. var material = subMesh.getMaterial();
  11880. if (mesh.showSubMeshesBoundingBox) {
  11881. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  11882. }
  11883. if (material) {
  11884. // Render targets
  11885. if (material.getRenderTargetTextures) {
  11886. if (this._processedMaterials.indexOf(material) === -1) {
  11887. this._processedMaterials.push(material);
  11888. this._renderTargets.concat(material.getRenderTargetTextures());
  11889. }
  11890. }
  11891. // Dispatch
  11892. this._activeIndices += subMesh.indexCount;
  11893. this._renderingManager.dispatch(subMesh);
  11894. }
  11895. }
  11896. };
  11897. Scene.prototype._evaluateActiveMeshes = function () {
  11898. this.activeCamera._activeMeshes.reset();
  11899. this._activeMeshes.reset();
  11900. this._renderingManager.reset();
  11901. this._processedMaterials.reset();
  11902. this._activeParticleSystems.reset();
  11903. this._activeSkeletons.reset();
  11904. this._boundingBoxRenderer.reset();
  11905. if (!this._frustumPlanes) {
  11906. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  11907. }
  11908. else {
  11909. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  11910. }
  11911. // Meshes
  11912. var meshes;
  11913. var len;
  11914. if (this._selectionOctree) {
  11915. var selection = this._selectionOctree.select(this._frustumPlanes);
  11916. meshes = selection.data;
  11917. len = selection.length;
  11918. }
  11919. else {
  11920. len = this.meshes.length;
  11921. meshes = this.meshes;
  11922. }
  11923. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  11924. var mesh = meshes[meshIndex];
  11925. if (mesh.isBlocked) {
  11926. continue;
  11927. }
  11928. this._totalVertices += mesh.getTotalVertices();
  11929. if (!mesh.isReady() || !mesh.isEnabled()) {
  11930. continue;
  11931. }
  11932. mesh.computeWorldMatrix();
  11933. // Intersections
  11934. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  11935. this._meshesForIntersections.pushNoDuplicate(mesh);
  11936. }
  11937. // Switch to current LOD
  11938. var meshLOD = mesh.getLOD(this.activeCamera);
  11939. if (!meshLOD) {
  11940. continue;
  11941. }
  11942. mesh._preActivate();
  11943. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  11944. this._activeMeshes.push(mesh);
  11945. this.activeCamera._activeMeshes.push(mesh);
  11946. mesh._activate(this._renderId);
  11947. this._activeMesh(meshLOD);
  11948. }
  11949. }
  11950. // Particle systems
  11951. var beforeParticlesDate = BABYLON.Tools.Now;
  11952. if (this.particlesEnabled) {
  11953. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  11954. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  11955. var particleSystem = this.particleSystems[particleIndex];
  11956. if (!particleSystem.isStarted()) {
  11957. continue;
  11958. }
  11959. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  11960. this._activeParticleSystems.push(particleSystem);
  11961. particleSystem.animate();
  11962. }
  11963. }
  11964. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  11965. }
  11966. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11967. };
  11968. Scene.prototype._activeMesh = function (mesh) {
  11969. if (mesh.skeleton && this.skeletonsEnabled) {
  11970. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  11971. }
  11972. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  11973. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  11974. }
  11975. if (mesh && mesh.subMeshes) {
  11976. // Submeshes Octrees
  11977. var len;
  11978. var subMeshes;
  11979. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  11980. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  11981. len = intersections.length;
  11982. subMeshes = intersections.data;
  11983. }
  11984. else {
  11985. subMeshes = mesh.subMeshes;
  11986. len = subMeshes.length;
  11987. }
  11988. for (var subIndex = 0; subIndex < len; subIndex++) {
  11989. var subMesh = subMeshes[subIndex];
  11990. this._evaluateSubMesh(subMesh, mesh);
  11991. }
  11992. }
  11993. };
  11994. Scene.prototype.updateTransformMatrix = function (force) {
  11995. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  11996. };
  11997. Scene.prototype._renderForCamera = function (camera) {
  11998. var engine = this._engine;
  11999. this.activeCamera = camera;
  12000. if (!this.activeCamera)
  12001. throw new Error("Active camera not set");
  12002. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12003. // Viewport
  12004. engine.setViewport(this.activeCamera.viewport);
  12005. // Camera
  12006. this._renderId++;
  12007. this.updateTransformMatrix();
  12008. if (this.beforeCameraRender) {
  12009. this.beforeCameraRender(this.activeCamera);
  12010. }
  12011. // Meshes
  12012. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12013. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12014. this._evaluateActiveMeshes();
  12015. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12016. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12017. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12018. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12019. skeleton.prepare();
  12020. }
  12021. // Render targets
  12022. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12023. if (this.renderTargetsEnabled) {
  12024. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12025. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12026. var renderTarget = this._renderTargets.data[renderIndex];
  12027. if (renderTarget._shouldRender()) {
  12028. this._renderId++;
  12029. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12030. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12031. }
  12032. }
  12033. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12034. this._renderId++;
  12035. }
  12036. if (this._renderTargets.length > 0) {
  12037. engine.restoreDefaultFramebuffer();
  12038. }
  12039. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12040. // Prepare Frame
  12041. this.postProcessManager._prepareFrame();
  12042. var beforeRenderDate = BABYLON.Tools.Now;
  12043. // Backgrounds
  12044. if (this.layers.length) {
  12045. engine.setDepthBuffer(false);
  12046. var layerIndex;
  12047. var layer;
  12048. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12049. layer = this.layers[layerIndex];
  12050. if (layer.isBackground) {
  12051. layer.render();
  12052. }
  12053. }
  12054. engine.setDepthBuffer(true);
  12055. }
  12056. // Render
  12057. BABYLON.Tools.StartPerformanceCounter("Main render");
  12058. this._renderingManager.render(null, null, true, true);
  12059. BABYLON.Tools.EndPerformanceCounter("Main render");
  12060. // Bounding boxes
  12061. this._boundingBoxRenderer.render();
  12062. // Lens flares
  12063. if (this.lensFlaresEnabled) {
  12064. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12065. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12066. this.lensFlareSystems[lensFlareSystemIndex].render();
  12067. }
  12068. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12069. }
  12070. // Foregrounds
  12071. if (this.layers.length) {
  12072. engine.setDepthBuffer(false);
  12073. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12074. layer = this.layers[layerIndex];
  12075. if (!layer.isBackground) {
  12076. layer.render();
  12077. }
  12078. }
  12079. engine.setDepthBuffer(true);
  12080. }
  12081. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12082. // Finalize frame
  12083. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12084. // Update camera
  12085. this.activeCamera._updateFromScene();
  12086. // Reset some special arrays
  12087. this._renderTargets.reset();
  12088. if (this.afterCameraRender) {
  12089. this.afterCameraRender(this.activeCamera);
  12090. }
  12091. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12092. };
  12093. Scene.prototype._processSubCameras = function (camera) {
  12094. if (camera.subCameras.length === 0) {
  12095. this._renderForCamera(camera);
  12096. return;
  12097. }
  12098. for (var index = 0; index < camera.subCameras.length; index++) {
  12099. this._renderForCamera(camera.subCameras[index]);
  12100. }
  12101. this.activeCamera = camera;
  12102. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12103. // Update camera
  12104. this.activeCamera._updateFromScene();
  12105. };
  12106. Scene.prototype._checkIntersections = function () {
  12107. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12108. var sourceMesh = this._meshesForIntersections.data[index];
  12109. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12110. var action = sourceMesh.actionManager.actions[actionIndex];
  12111. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12112. var parameters = action.getTriggerParameter();
  12113. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12114. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12115. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12116. if (areIntersecting && currentIntersectionInProgress === -1) {
  12117. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12118. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12119. sourceMesh._intersectionsInProgress.push(otherMesh);
  12120. }
  12121. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12122. sourceMesh._intersectionsInProgress.push(otherMesh);
  12123. }
  12124. }
  12125. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12126. //They intersected, and now they don't.
  12127. //is this trigger an exit trigger? execute an event.
  12128. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12129. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12130. }
  12131. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12132. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12133. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12134. }
  12135. }
  12136. }
  12137. }
  12138. }
  12139. };
  12140. Scene.prototype.render = function () {
  12141. var startDate = BABYLON.Tools.Now;
  12142. this._particlesDuration = 0;
  12143. this._spritesDuration = 0;
  12144. this._activeParticles = 0;
  12145. this._renderDuration = 0;
  12146. this._renderTargetsDuration = 0;
  12147. this._evaluateActiveMeshesDuration = 0;
  12148. this._totalVertices = 0;
  12149. this._activeIndices = 0;
  12150. this._activeBones = 0;
  12151. this.getEngine().resetDrawCalls();
  12152. this._meshesForIntersections.reset();
  12153. this.resetCachedMaterial();
  12154. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12155. // Actions
  12156. if (this.actionManager) {
  12157. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12158. }
  12159. //Simplification Queue
  12160. if (!this.simplificationQueue.running) {
  12161. this.simplificationQueue.executeNext();
  12162. }
  12163. // Before render
  12164. if (this.beforeRender) {
  12165. this.beforeRender();
  12166. }
  12167. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12168. this._onBeforeRenderCallbacks[callbackIndex]();
  12169. }
  12170. // Animations
  12171. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12172. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12173. this._animate();
  12174. // Physics
  12175. if (this._physicsEngine) {
  12176. BABYLON.Tools.StartPerformanceCounter("Physics");
  12177. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12178. BABYLON.Tools.EndPerformanceCounter("Physics");
  12179. }
  12180. // Customs render targets
  12181. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12182. var engine = this.getEngine();
  12183. var currentActiveCamera = this.activeCamera;
  12184. if (this.renderTargetsEnabled) {
  12185. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12186. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12187. var renderTarget = this.customRenderTargets[customIndex];
  12188. if (renderTarget._shouldRender()) {
  12189. this._renderId++;
  12190. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12191. if (!this.activeCamera)
  12192. throw new Error("Active camera not set");
  12193. // Viewport
  12194. engine.setViewport(this.activeCamera.viewport);
  12195. // Camera
  12196. this.updateTransformMatrix();
  12197. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12198. }
  12199. }
  12200. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12201. this._renderId++;
  12202. }
  12203. if (this.customRenderTargets.length > 0) {
  12204. engine.restoreDefaultFramebuffer();
  12205. }
  12206. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12207. this.activeCamera = currentActiveCamera;
  12208. // Procedural textures
  12209. if (this.proceduralTexturesEnabled) {
  12210. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12211. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12212. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12213. if (proceduralTexture._shouldRender()) {
  12214. proceduralTexture.render();
  12215. }
  12216. }
  12217. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12218. }
  12219. // Clear
  12220. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12221. // Shadows
  12222. if (this.shadowsEnabled) {
  12223. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12224. var light = this.lights[lightIndex];
  12225. var shadowGenerator = light.getShadowGenerator();
  12226. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12227. this._renderTargets.push(shadowGenerator.getShadowMap());
  12228. }
  12229. }
  12230. }
  12231. // Depth renderer
  12232. if (this._depthRenderer) {
  12233. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12234. }
  12235. // RenderPipeline
  12236. this.postProcessRenderPipelineManager.update();
  12237. // Multi-cameras?
  12238. if (this.activeCameras.length > 0) {
  12239. var currentRenderId = this._renderId;
  12240. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12241. this._renderId = currentRenderId;
  12242. this._processSubCameras(this.activeCameras[cameraIndex]);
  12243. }
  12244. }
  12245. else {
  12246. if (!this.activeCamera) {
  12247. throw new Error("No camera defined");
  12248. }
  12249. this._processSubCameras(this.activeCamera);
  12250. }
  12251. // Intersection checks
  12252. this._checkIntersections();
  12253. // Update the audio listener attached to the camera
  12254. this._updateAudioParameters();
  12255. // After render
  12256. if (this.afterRender) {
  12257. this.afterRender();
  12258. }
  12259. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12260. this._onAfterRenderCallbacks[callbackIndex]();
  12261. }
  12262. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12263. this._toBeDisposed.data[index].dispose();
  12264. this._toBeDisposed[index] = null;
  12265. }
  12266. this._toBeDisposed.reset();
  12267. if (this.dumpNextRenderTargets) {
  12268. this.dumpNextRenderTargets = false;
  12269. }
  12270. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12271. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12272. };
  12273. Scene.prototype._updateAudioParameters = function () {
  12274. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  12275. return;
  12276. }
  12277. var listeningCamera;
  12278. var audioEngine = BABYLON.Engine.audioEngine;
  12279. if (this.activeCameras.length > 0) {
  12280. listeningCamera = this.activeCameras[0];
  12281. }
  12282. else {
  12283. listeningCamera = this.activeCamera;
  12284. }
  12285. if (listeningCamera && audioEngine.canUseWebAudio) {
  12286. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12287. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12288. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12289. cameraDirection.normalize();
  12290. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12291. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12292. var sound = this.mainSoundTrack.soundCollection[i];
  12293. if (sound.useCustomAttenuation) {
  12294. sound.updateDistanceFromListener();
  12295. }
  12296. }
  12297. for (i = 0; i < this.soundTracks.length; i++) {
  12298. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12299. sound = this.soundTracks[i].soundCollection[j];
  12300. if (sound.useCustomAttenuation) {
  12301. sound.updateDistanceFromListener();
  12302. }
  12303. }
  12304. }
  12305. }
  12306. };
  12307. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12308. // Audio
  12309. get: function () {
  12310. return this._audioEnabled;
  12311. },
  12312. set: function (value) {
  12313. this._audioEnabled = value;
  12314. if (this._audioEnabled) {
  12315. this._enableAudio();
  12316. }
  12317. else {
  12318. this._disableAudio();
  12319. }
  12320. },
  12321. enumerable: true,
  12322. configurable: true
  12323. });
  12324. Scene.prototype._disableAudio = function () {
  12325. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12326. this.mainSoundTrack.soundCollection[i].pause();
  12327. }
  12328. for (i = 0; i < this.soundTracks.length; i++) {
  12329. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12330. this.soundTracks[i].soundCollection[j].pause();
  12331. }
  12332. }
  12333. };
  12334. Scene.prototype._enableAudio = function () {
  12335. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12336. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  12337. this.mainSoundTrack.soundCollection[i].play();
  12338. }
  12339. }
  12340. for (i = 0; i < this.soundTracks.length; i++) {
  12341. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12342. if (this.soundTracks[i].soundCollection[j].isPaused) {
  12343. this.soundTracks[i].soundCollection[j].play();
  12344. }
  12345. }
  12346. }
  12347. };
  12348. Object.defineProperty(Scene.prototype, "headphone", {
  12349. get: function () {
  12350. return this._headphone;
  12351. },
  12352. set: function (value) {
  12353. this._headphone = value;
  12354. if (this._headphone) {
  12355. this._switchAudioModeForHeadphones();
  12356. }
  12357. else {
  12358. this._switchAudioModeForNormalSpeakers();
  12359. }
  12360. },
  12361. enumerable: true,
  12362. configurable: true
  12363. });
  12364. Scene.prototype._switchAudioModeForHeadphones = function () {
  12365. this.mainSoundTrack.switchPanningModelToHRTF();
  12366. for (var i = 0; i < this.soundTracks.length; i++) {
  12367. this.soundTracks[i].switchPanningModelToHRTF();
  12368. }
  12369. };
  12370. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  12371. this.mainSoundTrack.switchPanningModelToEqualPower();
  12372. for (var i = 0; i < this.soundTracks.length; i++) {
  12373. this.soundTracks[i].switchPanningModelToEqualPower();
  12374. }
  12375. };
  12376. Scene.prototype.enableDepthRenderer = function () {
  12377. if (this._depthRenderer) {
  12378. return this._depthRenderer;
  12379. }
  12380. this._depthRenderer = new BABYLON.DepthRenderer(this);
  12381. return this._depthRenderer;
  12382. };
  12383. Scene.prototype.disableDepthRenderer = function () {
  12384. if (!this._depthRenderer) {
  12385. return;
  12386. }
  12387. this._depthRenderer.dispose();
  12388. this._depthRenderer = null;
  12389. };
  12390. Scene.prototype.dispose = function () {
  12391. this.beforeRender = null;
  12392. this.afterRender = null;
  12393. this.skeletons = [];
  12394. this._boundingBoxRenderer.dispose();
  12395. if (this._depthRenderer) {
  12396. this._depthRenderer.dispose();
  12397. }
  12398. // Debug layer
  12399. this.debugLayer.hide();
  12400. // Events
  12401. if (this.onDispose) {
  12402. this.onDispose();
  12403. }
  12404. this._onBeforeRenderCallbacks = [];
  12405. this._onAfterRenderCallbacks = [];
  12406. this.detachControl();
  12407. // Release sounds & sounds tracks
  12408. this.disposeSounds();
  12409. // Detach cameras
  12410. var canvas = this._engine.getRenderingCanvas();
  12411. var index;
  12412. for (index = 0; index < this.cameras.length; index++) {
  12413. this.cameras[index].detachControl(canvas);
  12414. }
  12415. while (this.lights.length) {
  12416. this.lights[0].dispose();
  12417. }
  12418. while (this.meshes.length) {
  12419. this.meshes[0].dispose(true);
  12420. }
  12421. while (this.cameras.length) {
  12422. this.cameras[0].dispose();
  12423. }
  12424. while (this.materials.length) {
  12425. this.materials[0].dispose();
  12426. }
  12427. while (this.particleSystems.length) {
  12428. this.particleSystems[0].dispose();
  12429. }
  12430. while (this.spriteManagers.length) {
  12431. this.spriteManagers[0].dispose();
  12432. }
  12433. while (this.layers.length) {
  12434. this.layers[0].dispose();
  12435. }
  12436. while (this.textures.length) {
  12437. this.textures[0].dispose();
  12438. }
  12439. // Post-processes
  12440. this.postProcessManager.dispose();
  12441. // Physics
  12442. if (this._physicsEngine) {
  12443. this.disablePhysicsEngine();
  12444. }
  12445. // Remove from engine
  12446. index = this._engine.scenes.indexOf(this);
  12447. if (index > -1) {
  12448. this._engine.scenes.splice(index, 1);
  12449. }
  12450. this._engine.wipeCaches();
  12451. };
  12452. // Release sounds & sounds tracks
  12453. Scene.prototype.disposeSounds = function () {
  12454. this.mainSoundTrack.dispose();
  12455. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  12456. this.soundTracks[scIndex].dispose();
  12457. }
  12458. };
  12459. // Octrees
  12460. Scene.prototype.getWorldExtends = function () {
  12461. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12462. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  12463. for (var index = 0; index < this.meshes.length; index++) {
  12464. var mesh = this.meshes[index];
  12465. mesh.computeWorldMatrix(true);
  12466. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  12467. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  12468. BABYLON.Tools.CheckExtends(minBox, min, max);
  12469. BABYLON.Tools.CheckExtends(maxBox, min, max);
  12470. }
  12471. return {
  12472. min: min,
  12473. max: max
  12474. };
  12475. };
  12476. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  12477. if (maxCapacity === void 0) { maxCapacity = 64; }
  12478. if (maxDepth === void 0) { maxDepth = 2; }
  12479. if (!this._selectionOctree) {
  12480. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  12481. }
  12482. var worldExtends = this.getWorldExtends();
  12483. // Update octree
  12484. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  12485. return this._selectionOctree;
  12486. };
  12487. // Picking
  12488. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  12489. var engine = this._engine;
  12490. if (!camera) {
  12491. if (!this.activeCamera)
  12492. throw new Error("Active camera not set");
  12493. camera = this.activeCamera;
  12494. }
  12495. var cameraViewport = camera.viewport;
  12496. var viewport = cameraViewport.toGlobal(engine);
  12497. // Moving coordinates to local viewport world
  12498. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  12499. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  12500. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12501. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12502. };
  12503. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  12504. var pickingInfo = null;
  12505. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  12506. var mesh = this.meshes[meshIndex];
  12507. if (predicate) {
  12508. if (!predicate(mesh)) {
  12509. continue;
  12510. }
  12511. }
  12512. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  12513. continue;
  12514. }
  12515. var world = mesh.getWorldMatrix();
  12516. var ray = rayFunction(world);
  12517. var result = mesh.intersects(ray, fastCheck);
  12518. if (!result || !result.hit)
  12519. continue;
  12520. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  12521. continue;
  12522. pickingInfo = result;
  12523. if (fastCheck) {
  12524. break;
  12525. }
  12526. }
  12527. return pickingInfo || new BABYLON.PickingInfo();
  12528. };
  12529. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  12530. var _this = this;
  12531. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  12532. /// <param name="x">X position on screen</param>
  12533. /// <param name="y">Y position on screen</param>
  12534. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  12535. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  12536. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  12537. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  12538. };
  12539. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  12540. var _this = this;
  12541. return this._internalPick(function (world) {
  12542. if (!_this._pickWithRayInverseMatrix) {
  12543. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  12544. }
  12545. world.invertToRef(_this._pickWithRayInverseMatrix);
  12546. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  12547. }, predicate, fastCheck);
  12548. };
  12549. Scene.prototype.setPointerOverMesh = function (mesh) {
  12550. if (this._pointerOverMesh === mesh) {
  12551. return;
  12552. }
  12553. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12554. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12555. }
  12556. this._pointerOverMesh = mesh;
  12557. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12558. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12559. }
  12560. };
  12561. Scene.prototype.getPointerOverMesh = function () {
  12562. return this._pointerOverMesh;
  12563. };
  12564. // Physics
  12565. Scene.prototype.getPhysicsEngine = function () {
  12566. return this._physicsEngine;
  12567. };
  12568. Scene.prototype.enablePhysics = function (gravity, plugin) {
  12569. if (this._physicsEngine) {
  12570. return true;
  12571. }
  12572. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  12573. if (!this._physicsEngine.isSupported()) {
  12574. this._physicsEngine = null;
  12575. return false;
  12576. }
  12577. this._physicsEngine._initialize(gravity);
  12578. return true;
  12579. };
  12580. Scene.prototype.disablePhysicsEngine = function () {
  12581. if (!this._physicsEngine) {
  12582. return;
  12583. }
  12584. this._physicsEngine.dispose();
  12585. this._physicsEngine = undefined;
  12586. };
  12587. Scene.prototype.isPhysicsEnabled = function () {
  12588. return this._physicsEngine !== undefined;
  12589. };
  12590. Scene.prototype.setGravity = function (gravity) {
  12591. if (!this._physicsEngine) {
  12592. return;
  12593. }
  12594. this._physicsEngine._setGravity(gravity);
  12595. };
  12596. Scene.prototype.createCompoundImpostor = function (parts, options) {
  12597. if (parts.parts) {
  12598. options = parts;
  12599. parts = parts.parts;
  12600. }
  12601. if (!this._physicsEngine) {
  12602. return null;
  12603. }
  12604. for (var index = 0; index < parts.length; index++) {
  12605. var mesh = parts[index].mesh;
  12606. mesh._physicImpostor = parts[index].impostor;
  12607. mesh._physicsMass = options.mass / parts.length;
  12608. mesh._physicsFriction = options.friction;
  12609. mesh._physicRestitution = options.restitution;
  12610. }
  12611. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  12612. };
  12613. Scene.prototype.deleteCompoundImpostor = function (compound) {
  12614. for (var index = 0; index < compound.parts.length; index++) {
  12615. var mesh = compound.parts[index].mesh;
  12616. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  12617. this._physicsEngine._unregisterMesh(mesh);
  12618. }
  12619. };
  12620. // Misc.
  12621. Scene.prototype.createDefaultCameraOrLight = function () {
  12622. // Light
  12623. if (this.lights.length === 0) {
  12624. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  12625. }
  12626. // Camera
  12627. if (!this.activeCamera) {
  12628. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  12629. // Compute position
  12630. var worldExtends = this.getWorldExtends();
  12631. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  12632. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  12633. camera.setTarget(worldCenter);
  12634. this.activeCamera = camera;
  12635. }
  12636. };
  12637. // Tags
  12638. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  12639. if (tagsQuery === undefined) {
  12640. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  12641. return list;
  12642. }
  12643. var listByTags = [];
  12644. forEach = forEach || (function (item) {
  12645. return;
  12646. });
  12647. for (var i in list) {
  12648. var item = list[i];
  12649. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  12650. listByTags.push(item);
  12651. forEach(item);
  12652. }
  12653. }
  12654. return listByTags;
  12655. };
  12656. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  12657. return this._getByTags(this.meshes, tagsQuery, forEach);
  12658. };
  12659. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  12660. return this._getByTags(this.cameras, tagsQuery, forEach);
  12661. };
  12662. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  12663. return this._getByTags(this.lights, tagsQuery, forEach);
  12664. };
  12665. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  12666. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  12667. };
  12668. // Statics
  12669. Scene._FOGMODE_NONE = 0;
  12670. Scene._FOGMODE_EXP = 1;
  12671. Scene._FOGMODE_EXP2 = 2;
  12672. Scene._FOGMODE_LINEAR = 3;
  12673. Scene.MinDeltaTime = 1.0;
  12674. Scene.MaxDeltaTime = 1000.0;
  12675. return Scene;
  12676. })();
  12677. BABYLON.Scene = Scene;
  12678. })(BABYLON || (BABYLON = {}));
  12679. //# sourceMappingURL=babylon.scene.js.map
  12680. var BABYLON;
  12681. (function (BABYLON) {
  12682. var VertexBuffer = (function () {
  12683. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  12684. if (engine instanceof BABYLON.Mesh) {
  12685. this._engine = engine.getScene().getEngine();
  12686. }
  12687. else {
  12688. this._engine = engine;
  12689. }
  12690. this._updatable = updatable;
  12691. this._data = data;
  12692. if (!postponeInternalCreation) {
  12693. this.create();
  12694. }
  12695. this._kind = kind;
  12696. if (stride) {
  12697. this._strideSize = stride;
  12698. return;
  12699. }
  12700. switch (kind) {
  12701. case VertexBuffer.PositionKind:
  12702. this._strideSize = 3;
  12703. break;
  12704. case VertexBuffer.NormalKind:
  12705. this._strideSize = 3;
  12706. break;
  12707. case VertexBuffer.UVKind:
  12708. this._strideSize = 2;
  12709. break;
  12710. case VertexBuffer.UV2Kind:
  12711. this._strideSize = 2;
  12712. break;
  12713. case VertexBuffer.ColorKind:
  12714. this._strideSize = 4;
  12715. break;
  12716. case VertexBuffer.MatricesIndicesKind:
  12717. this._strideSize = 4;
  12718. break;
  12719. case VertexBuffer.MatricesWeightsKind:
  12720. this._strideSize = 4;
  12721. break;
  12722. }
  12723. }
  12724. // Properties
  12725. VertexBuffer.prototype.isUpdatable = function () {
  12726. return this._updatable;
  12727. };
  12728. VertexBuffer.prototype.getData = function () {
  12729. return this._data;
  12730. };
  12731. VertexBuffer.prototype.getBuffer = function () {
  12732. return this._buffer;
  12733. };
  12734. VertexBuffer.prototype.getStrideSize = function () {
  12735. return this._strideSize;
  12736. };
  12737. // Methods
  12738. VertexBuffer.prototype.create = function (data) {
  12739. if (!data && this._buffer) {
  12740. return; // nothing to do
  12741. }
  12742. data = data || this._data;
  12743. if (!this._buffer) {
  12744. if (this._updatable) {
  12745. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  12746. }
  12747. else {
  12748. this._buffer = this._engine.createVertexBuffer(data);
  12749. }
  12750. }
  12751. if (this._updatable) {
  12752. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  12753. this._data = data;
  12754. }
  12755. };
  12756. VertexBuffer.prototype.update = function (data) {
  12757. this.create(data);
  12758. };
  12759. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  12760. if (!this._buffer) {
  12761. return;
  12762. }
  12763. if (this._updatable) {
  12764. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  12765. this._data = null;
  12766. }
  12767. };
  12768. VertexBuffer.prototype.dispose = function () {
  12769. if (!this._buffer) {
  12770. return;
  12771. }
  12772. if (this._engine._releaseBuffer(this._buffer)) {
  12773. this._buffer = null;
  12774. }
  12775. };
  12776. Object.defineProperty(VertexBuffer, "PositionKind", {
  12777. get: function () {
  12778. return VertexBuffer._PositionKind;
  12779. },
  12780. enumerable: true,
  12781. configurable: true
  12782. });
  12783. Object.defineProperty(VertexBuffer, "NormalKind", {
  12784. get: function () {
  12785. return VertexBuffer._NormalKind;
  12786. },
  12787. enumerable: true,
  12788. configurable: true
  12789. });
  12790. Object.defineProperty(VertexBuffer, "UVKind", {
  12791. get: function () {
  12792. return VertexBuffer._UVKind;
  12793. },
  12794. enumerable: true,
  12795. configurable: true
  12796. });
  12797. Object.defineProperty(VertexBuffer, "UV2Kind", {
  12798. get: function () {
  12799. return VertexBuffer._UV2Kind;
  12800. },
  12801. enumerable: true,
  12802. configurable: true
  12803. });
  12804. Object.defineProperty(VertexBuffer, "ColorKind", {
  12805. get: function () {
  12806. return VertexBuffer._ColorKind;
  12807. },
  12808. enumerable: true,
  12809. configurable: true
  12810. });
  12811. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  12812. get: function () {
  12813. return VertexBuffer._MatricesIndicesKind;
  12814. },
  12815. enumerable: true,
  12816. configurable: true
  12817. });
  12818. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  12819. get: function () {
  12820. return VertexBuffer._MatricesWeightsKind;
  12821. },
  12822. enumerable: true,
  12823. configurable: true
  12824. });
  12825. // Enums
  12826. VertexBuffer._PositionKind = "position";
  12827. VertexBuffer._NormalKind = "normal";
  12828. VertexBuffer._UVKind = "uv";
  12829. VertexBuffer._UV2Kind = "uv2";
  12830. VertexBuffer._ColorKind = "color";
  12831. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  12832. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  12833. return VertexBuffer;
  12834. })();
  12835. BABYLON.VertexBuffer = VertexBuffer;
  12836. })(BABYLON || (BABYLON = {}));
  12837. //# sourceMappingURL=babylon.vertexBuffer.js.map
  12838. var __extends = this.__extends || function (d, b) {
  12839. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12840. function __() { this.constructor = d; }
  12841. __.prototype = b.prototype;
  12842. d.prototype = new __();
  12843. };
  12844. var BABYLON;
  12845. (function (BABYLON) {
  12846. /**
  12847. * Creates an instance based on a source mesh.
  12848. */
  12849. var InstancedMesh = (function (_super) {
  12850. __extends(InstancedMesh, _super);
  12851. function InstancedMesh(name, source) {
  12852. _super.call(this, name, source.getScene());
  12853. source.instances.push(this);
  12854. this._sourceMesh = source;
  12855. this.position.copyFrom(source.position);
  12856. this.rotation.copyFrom(source.rotation);
  12857. this.scaling.copyFrom(source.scaling);
  12858. if (source.rotationQuaternion) {
  12859. this.rotationQuaternion = source.rotationQuaternion.clone();
  12860. }
  12861. this.infiniteDistance = source.infiniteDistance;
  12862. this.setPivotMatrix(source.getPivotMatrix());
  12863. this.refreshBoundingInfo();
  12864. this._syncSubMeshes();
  12865. }
  12866. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12867. // Methods
  12868. get: function () {
  12869. return this._sourceMesh.receiveShadows;
  12870. },
  12871. enumerable: true,
  12872. configurable: true
  12873. });
  12874. Object.defineProperty(InstancedMesh.prototype, "material", {
  12875. get: function () {
  12876. return this._sourceMesh.material;
  12877. },
  12878. enumerable: true,
  12879. configurable: true
  12880. });
  12881. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12882. get: function () {
  12883. return this._sourceMesh.visibility;
  12884. },
  12885. enumerable: true,
  12886. configurable: true
  12887. });
  12888. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12889. get: function () {
  12890. return this._sourceMesh.skeleton;
  12891. },
  12892. enumerable: true,
  12893. configurable: true
  12894. });
  12895. InstancedMesh.prototype.getTotalVertices = function () {
  12896. return this._sourceMesh.getTotalVertices();
  12897. };
  12898. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12899. get: function () {
  12900. return this._sourceMesh;
  12901. },
  12902. enumerable: true,
  12903. configurable: true
  12904. });
  12905. InstancedMesh.prototype.getVerticesData = function (kind) {
  12906. return this._sourceMesh.getVerticesData(kind);
  12907. };
  12908. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12909. return this._sourceMesh.isVerticesDataPresent(kind);
  12910. };
  12911. InstancedMesh.prototype.getIndices = function () {
  12912. return this._sourceMesh.getIndices();
  12913. };
  12914. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12915. get: function () {
  12916. return this._sourceMesh._positions;
  12917. },
  12918. enumerable: true,
  12919. configurable: true
  12920. });
  12921. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12922. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12923. if (data) {
  12924. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12925. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12926. }
  12927. this._updateBoundingInfo();
  12928. };
  12929. InstancedMesh.prototype._preActivate = function () {
  12930. if (this._currentLOD) {
  12931. this._currentLOD._preActivate();
  12932. }
  12933. };
  12934. InstancedMesh.prototype._activate = function (renderId) {
  12935. if (this._currentLOD) {
  12936. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12937. }
  12938. };
  12939. InstancedMesh.prototype.getLOD = function (camera) {
  12940. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12941. if (this._currentLOD === this.sourceMesh) {
  12942. return this;
  12943. }
  12944. return this._currentLOD;
  12945. };
  12946. InstancedMesh.prototype._syncSubMeshes = function () {
  12947. this.releaseSubMeshes();
  12948. if (this._sourceMesh.subMeshes) {
  12949. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12950. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12951. }
  12952. }
  12953. };
  12954. InstancedMesh.prototype._generatePointsArray = function () {
  12955. return this._sourceMesh._generatePointsArray();
  12956. };
  12957. // Clone
  12958. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12959. var result = this._sourceMesh.createInstance(name);
  12960. // Deep copy
  12961. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12962. // Bounding info
  12963. this.refreshBoundingInfo();
  12964. // Parent
  12965. if (newParent) {
  12966. result.parent = newParent;
  12967. }
  12968. if (!doNotCloneChildren) {
  12969. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12970. var mesh = this.getScene().meshes[index];
  12971. if (mesh.parent === this) {
  12972. mesh.clone(mesh.name, result);
  12973. }
  12974. }
  12975. }
  12976. result.computeWorldMatrix(true);
  12977. return result;
  12978. };
  12979. // Dispoe
  12980. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12981. // Remove from mesh
  12982. var index = this._sourceMesh.instances.indexOf(this);
  12983. this._sourceMesh.instances.splice(index, 1);
  12984. _super.prototype.dispose.call(this, doNotRecurse);
  12985. };
  12986. return InstancedMesh;
  12987. })(BABYLON.AbstractMesh);
  12988. BABYLON.InstancedMesh = InstancedMesh;
  12989. })(BABYLON || (BABYLON = {}));
  12990. //# sourceMappingURL=babylon.instancedMesh.js.map
  12991. var __extends = this.__extends || function (d, b) {
  12992. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12993. function __() { this.constructor = d; }
  12994. __.prototype = b.prototype;
  12995. d.prototype = new __();
  12996. };
  12997. var BABYLON;
  12998. (function (BABYLON) {
  12999. var _InstancesBatch = (function () {
  13000. function _InstancesBatch() {
  13001. this.mustReturn = false;
  13002. this.visibleInstances = new Array();
  13003. this.renderSelf = new Array();
  13004. }
  13005. return _InstancesBatch;
  13006. })();
  13007. BABYLON._InstancesBatch = _InstancesBatch;
  13008. var Mesh = (function (_super) {
  13009. __extends(Mesh, _super);
  13010. /**
  13011. * @constructor
  13012. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13013. * @param {Scene} scene - The scene to add this mesh to.
  13014. * @param {Node} parent - The parent of this mesh, if it has one
  13015. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13016. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13017. * When false, achieved by calling a clone(), also passing False.
  13018. * This will make creation of children, recursive.
  13019. */
  13020. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13021. if (parent === void 0) { parent = null; }
  13022. _super.call(this, name, scene);
  13023. // Members
  13024. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13025. this.instances = new Array();
  13026. this._LODLevels = new Array();
  13027. this._onBeforeRenderCallbacks = new Array();
  13028. this._onAfterRenderCallbacks = new Array();
  13029. this._visibleInstances = {};
  13030. this._renderIdForInstances = new Array();
  13031. this._batchCache = new _InstancesBatch();
  13032. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13033. this._sideOrientation = Mesh._DEFAULTSIDE;
  13034. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13035. if (source) {
  13036. // Geometry
  13037. if (source._geometry) {
  13038. source._geometry.applyToMesh(this);
  13039. }
  13040. // Deep copy
  13041. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13042. // Material
  13043. this.material = source.material;
  13044. if (!doNotCloneChildren) {
  13045. for (var index = 0; index < scene.meshes.length; index++) {
  13046. var mesh = scene.meshes[index];
  13047. if (mesh.parent === source) {
  13048. // doNotCloneChildren is always going to be False
  13049. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13050. }
  13051. }
  13052. }
  13053. for (index = 0; index < scene.particleSystems.length; index++) {
  13054. var system = scene.particleSystems[index];
  13055. if (system.emitter === source) {
  13056. system.clone(system.name, this);
  13057. }
  13058. }
  13059. this.computeWorldMatrix(true);
  13060. }
  13061. // Parent
  13062. if (parent !== null) {
  13063. this.parent = parent;
  13064. }
  13065. }
  13066. Object.defineProperty(Mesh, "FRONTSIDE", {
  13067. get: function () {
  13068. return Mesh._FRONTSIDE;
  13069. },
  13070. enumerable: true,
  13071. configurable: true
  13072. });
  13073. Object.defineProperty(Mesh, "BACKSIDE", {
  13074. get: function () {
  13075. return Mesh._BACKSIDE;
  13076. },
  13077. enumerable: true,
  13078. configurable: true
  13079. });
  13080. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13081. get: function () {
  13082. return Mesh._DOUBLESIDE;
  13083. },
  13084. enumerable: true,
  13085. configurable: true
  13086. });
  13087. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13088. get: function () {
  13089. return Mesh._DEFAULTSIDE;
  13090. },
  13091. enumerable: true,
  13092. configurable: true
  13093. });
  13094. Object.defineProperty(Mesh, "NO_CAP", {
  13095. get: function () {
  13096. return Mesh._NO_CAP;
  13097. },
  13098. enumerable: true,
  13099. configurable: true
  13100. });
  13101. Object.defineProperty(Mesh, "CAP_START", {
  13102. get: function () {
  13103. return Mesh._CAP_START;
  13104. },
  13105. enumerable: true,
  13106. configurable: true
  13107. });
  13108. Object.defineProperty(Mesh, "CAP_END", {
  13109. get: function () {
  13110. return Mesh._CAP_END;
  13111. },
  13112. enumerable: true,
  13113. configurable: true
  13114. });
  13115. Object.defineProperty(Mesh, "CAP_ALL", {
  13116. get: function () {
  13117. return Mesh._CAP_ALL;
  13118. },
  13119. enumerable: true,
  13120. configurable: true
  13121. });
  13122. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13123. // Methods
  13124. get: function () {
  13125. return this._LODLevels.length > 0;
  13126. },
  13127. enumerable: true,
  13128. configurable: true
  13129. });
  13130. Mesh.prototype._sortLODLevels = function () {
  13131. this._LODLevels.sort(function (a, b) {
  13132. if (a.distance < b.distance) {
  13133. return 1;
  13134. }
  13135. if (a.distance > b.distance) {
  13136. return -1;
  13137. }
  13138. return 0;
  13139. });
  13140. };
  13141. /**
  13142. * Add a mesh as LOD level triggered at the given distance.
  13143. * @param {number} distance - the distance from the center of the object to show this level
  13144. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13145. * @return {BABYLON.Mesh} this mesh (for chaining)
  13146. */
  13147. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13148. if (mesh && mesh._masterMesh) {
  13149. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13150. return this;
  13151. }
  13152. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13153. this._LODLevels.push(level);
  13154. if (mesh) {
  13155. mesh._masterMesh = this;
  13156. }
  13157. this._sortLODLevels();
  13158. return this;
  13159. };
  13160. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13161. for (var index = 0; index < this._LODLevels.length; index++) {
  13162. var level = this._LODLevels[index];
  13163. if (level.distance === distance) {
  13164. return level.mesh;
  13165. }
  13166. }
  13167. return null;
  13168. };
  13169. /**
  13170. * Remove a mesh from the LOD array
  13171. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13172. * @return {BABYLON.Mesh} this mesh (for chaining)
  13173. */
  13174. Mesh.prototype.removeLODLevel = function (mesh) {
  13175. for (var index = 0; index < this._LODLevels.length; index++) {
  13176. if (this._LODLevels[index].mesh === mesh) {
  13177. this._LODLevels.splice(index, 1);
  13178. if (mesh) {
  13179. mesh._masterMesh = null;
  13180. }
  13181. }
  13182. }
  13183. this._sortLODLevels();
  13184. return this;
  13185. };
  13186. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13187. if (!this._LODLevels || this._LODLevels.length === 0) {
  13188. return this;
  13189. }
  13190. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13191. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13192. if (this.onLODLevelSelection) {
  13193. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13194. }
  13195. return this;
  13196. }
  13197. for (var index = 0; index < this._LODLevels.length; index++) {
  13198. var level = this._LODLevels[index];
  13199. if (level.distance < distanceToCamera) {
  13200. if (level.mesh) {
  13201. level.mesh._preActivate();
  13202. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13203. }
  13204. if (this.onLODLevelSelection) {
  13205. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13206. }
  13207. return level.mesh;
  13208. }
  13209. }
  13210. if (this.onLODLevelSelection) {
  13211. this.onLODLevelSelection(distanceToCamera, this, this);
  13212. }
  13213. return this;
  13214. };
  13215. Object.defineProperty(Mesh.prototype, "geometry", {
  13216. get: function () {
  13217. return this._geometry;
  13218. },
  13219. enumerable: true,
  13220. configurable: true
  13221. });
  13222. Mesh.prototype.getTotalVertices = function () {
  13223. if (!this._geometry) {
  13224. return 0;
  13225. }
  13226. return this._geometry.getTotalVertices();
  13227. };
  13228. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  13229. if (!this._geometry) {
  13230. return null;
  13231. }
  13232. return this._geometry.getVerticesData(kind, copyWhenShared);
  13233. };
  13234. Mesh.prototype.getVertexBuffer = function (kind) {
  13235. if (!this._geometry) {
  13236. return undefined;
  13237. }
  13238. return this._geometry.getVertexBuffer(kind);
  13239. };
  13240. Mesh.prototype.isVerticesDataPresent = function (kind) {
  13241. if (!this._geometry) {
  13242. if (this._delayInfo) {
  13243. return this._delayInfo.indexOf(kind) !== -1;
  13244. }
  13245. return false;
  13246. }
  13247. return this._geometry.isVerticesDataPresent(kind);
  13248. };
  13249. Mesh.prototype.getVerticesDataKinds = function () {
  13250. if (!this._geometry) {
  13251. var result = [];
  13252. if (this._delayInfo) {
  13253. for (var kind in this._delayInfo) {
  13254. result.push(kind);
  13255. }
  13256. }
  13257. return result;
  13258. }
  13259. return this._geometry.getVerticesDataKinds();
  13260. };
  13261. Mesh.prototype.getTotalIndices = function () {
  13262. if (!this._geometry) {
  13263. return 0;
  13264. }
  13265. return this._geometry.getTotalIndices();
  13266. };
  13267. Mesh.prototype.getIndices = function (copyWhenShared) {
  13268. if (!this._geometry) {
  13269. return [];
  13270. }
  13271. return this._geometry.getIndices(copyWhenShared);
  13272. };
  13273. Object.defineProperty(Mesh.prototype, "isBlocked", {
  13274. get: function () {
  13275. return this._masterMesh !== null && this._masterMesh !== undefined;
  13276. },
  13277. enumerable: true,
  13278. configurable: true
  13279. });
  13280. Mesh.prototype.isReady = function () {
  13281. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13282. return false;
  13283. }
  13284. return _super.prototype.isReady.call(this);
  13285. };
  13286. Mesh.prototype.isDisposed = function () {
  13287. return this._isDisposed;
  13288. };
  13289. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  13290. get: function () {
  13291. return this._sideOrientation;
  13292. },
  13293. set: function (sideO) {
  13294. this._sideOrientation = sideO;
  13295. },
  13296. enumerable: true,
  13297. configurable: true
  13298. });
  13299. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  13300. get: function () {
  13301. return this._areNormalsFrozen;
  13302. },
  13303. enumerable: true,
  13304. configurable: true
  13305. });
  13306. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13307. Mesh.prototype.freezeNormals = function () {
  13308. this._areNormalsFrozen = true;
  13309. };
  13310. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13311. Mesh.prototype.unfreezeNormals = function () {
  13312. this._areNormalsFrozen = false;
  13313. };
  13314. // Methods
  13315. Mesh.prototype._preActivate = function () {
  13316. var sceneRenderId = this.getScene().getRenderId();
  13317. if (this._preActivateId === sceneRenderId) {
  13318. return;
  13319. }
  13320. this._preActivateId = sceneRenderId;
  13321. this._visibleInstances = null;
  13322. };
  13323. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  13324. if (!this._visibleInstances) {
  13325. this._visibleInstances = {};
  13326. this._visibleInstances.defaultRenderId = renderId;
  13327. this._visibleInstances.selfDefaultRenderId = this._renderId;
  13328. }
  13329. if (!this._visibleInstances[renderId]) {
  13330. this._visibleInstances[renderId] = new Array();
  13331. }
  13332. this._visibleInstances[renderId].push(instance);
  13333. };
  13334. Mesh.prototype.refreshBoundingInfo = function () {
  13335. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13336. if (data) {
  13337. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  13338. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13339. }
  13340. if (this.subMeshes) {
  13341. for (var index = 0; index < this.subMeshes.length; index++) {
  13342. this.subMeshes[index].refreshBoundingInfo();
  13343. }
  13344. }
  13345. this._updateBoundingInfo();
  13346. };
  13347. Mesh.prototype._createGlobalSubMesh = function () {
  13348. var totalVertices = this.getTotalVertices();
  13349. if (!totalVertices || !this.getIndices()) {
  13350. return null;
  13351. }
  13352. this.releaseSubMeshes();
  13353. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  13354. };
  13355. Mesh.prototype.subdivide = function (count) {
  13356. if (count < 1) {
  13357. return;
  13358. }
  13359. var totalIndices = this.getTotalIndices();
  13360. var subdivisionSize = (totalIndices / count) | 0;
  13361. var offset = 0;
  13362. while (subdivisionSize % 3 !== 0) {
  13363. subdivisionSize++;
  13364. }
  13365. this.releaseSubMeshes();
  13366. for (var index = 0; index < count; index++) {
  13367. if (offset >= totalIndices) {
  13368. break;
  13369. }
  13370. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  13371. offset += subdivisionSize;
  13372. }
  13373. this.synchronizeInstances();
  13374. };
  13375. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13376. if (kind instanceof Array) {
  13377. var temp = data;
  13378. data = kind;
  13379. kind = temp;
  13380. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  13381. }
  13382. if (!this._geometry) {
  13383. var vertexData = new BABYLON.VertexData();
  13384. vertexData.set(data, kind);
  13385. var scene = this.getScene();
  13386. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  13387. }
  13388. else {
  13389. this._geometry.setVerticesData(kind, data, updatable, stride);
  13390. }
  13391. };
  13392. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13393. if (!this._geometry) {
  13394. return;
  13395. }
  13396. if (!makeItUnique) {
  13397. this._geometry.updateVerticesData(kind, data, updateExtends);
  13398. }
  13399. else {
  13400. this.makeGeometryUnique();
  13401. this.updateVerticesData(kind, data, updateExtends, false);
  13402. }
  13403. };
  13404. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  13405. if (!this._geometry) {
  13406. return;
  13407. }
  13408. if (!makeItUnique) {
  13409. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  13410. }
  13411. else {
  13412. this.makeGeometryUnique();
  13413. this.updateVerticesDataDirectly(kind, data, offset, false);
  13414. }
  13415. };
  13416. // Mesh positions update function :
  13417. // updates the mesh positions according to the positionFunction returned values.
  13418. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  13419. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  13420. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  13421. if (computeNormals === void 0) { computeNormals = true; }
  13422. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13423. positionFunction(positions);
  13424. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  13425. if (computeNormals) {
  13426. var indices = this.getIndices();
  13427. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13428. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  13429. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  13430. }
  13431. };
  13432. Mesh.prototype.makeGeometryUnique = function () {
  13433. if (!this._geometry) {
  13434. return;
  13435. }
  13436. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  13437. geometry.applyToMesh(this);
  13438. };
  13439. Mesh.prototype.setIndices = function (indices, totalVertices) {
  13440. if (!this._geometry) {
  13441. var vertexData = new BABYLON.VertexData();
  13442. vertexData.indices = indices;
  13443. var scene = this.getScene();
  13444. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  13445. }
  13446. else {
  13447. this._geometry.setIndices(indices, totalVertices);
  13448. }
  13449. };
  13450. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  13451. var engine = this.getScene().getEngine();
  13452. // Wireframe
  13453. var indexToBind;
  13454. switch (fillMode) {
  13455. case BABYLON.Material.PointFillMode:
  13456. indexToBind = null;
  13457. break;
  13458. case BABYLON.Material.WireFrameFillMode:
  13459. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  13460. break;
  13461. default:
  13462. case BABYLON.Material.TriangleFillMode:
  13463. indexToBind = this._geometry.getIndexBuffer();
  13464. break;
  13465. }
  13466. // VBOs
  13467. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  13468. };
  13469. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  13470. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13471. return;
  13472. }
  13473. var engine = this.getScene().getEngine();
  13474. switch (fillMode) {
  13475. case BABYLON.Material.PointFillMode:
  13476. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  13477. break;
  13478. case BABYLON.Material.WireFrameFillMode:
  13479. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  13480. break;
  13481. default:
  13482. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  13483. }
  13484. };
  13485. Mesh.prototype.registerBeforeRender = function (func) {
  13486. this._onBeforeRenderCallbacks.push(func);
  13487. };
  13488. Mesh.prototype.unregisterBeforeRender = function (func) {
  13489. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13490. if (index > -1) {
  13491. this._onBeforeRenderCallbacks.splice(index, 1);
  13492. }
  13493. };
  13494. Mesh.prototype.registerAfterRender = function (func) {
  13495. this._onAfterRenderCallbacks.push(func);
  13496. };
  13497. Mesh.prototype.unregisterAfterRender = function (func) {
  13498. var index = this._onAfterRenderCallbacks.indexOf(func);
  13499. if (index > -1) {
  13500. this._onAfterRenderCallbacks.splice(index, 1);
  13501. }
  13502. };
  13503. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  13504. var scene = this.getScene();
  13505. this._batchCache.mustReturn = false;
  13506. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  13507. this._batchCache.visibleInstances[subMeshId] = null;
  13508. if (this._visibleInstances) {
  13509. var currentRenderId = scene.getRenderId();
  13510. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  13511. var selfRenderId = this._renderId;
  13512. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  13513. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  13514. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  13515. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  13516. }
  13517. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  13518. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  13519. this._batchCache.mustReturn = true;
  13520. return this._batchCache;
  13521. }
  13522. if (currentRenderId !== selfRenderId) {
  13523. this._batchCache.renderSelf[subMeshId] = false;
  13524. }
  13525. }
  13526. this._renderIdForInstances[subMeshId] = currentRenderId;
  13527. }
  13528. return this._batchCache;
  13529. };
  13530. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  13531. var visibleInstances = batch.visibleInstances[subMesh._id];
  13532. var matricesCount = visibleInstances.length + 1;
  13533. var bufferSize = matricesCount * 16 * 4;
  13534. while (this._instancesBufferSize < bufferSize) {
  13535. this._instancesBufferSize *= 2;
  13536. }
  13537. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  13538. if (this._worldMatricesInstancesBuffer) {
  13539. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13540. }
  13541. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  13542. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  13543. }
  13544. var offset = 0;
  13545. var instancesCount = 0;
  13546. var world = this.getWorldMatrix();
  13547. if (batch.renderSelf[subMesh._id]) {
  13548. world.copyToArray(this._worldMatricesInstancesArray, offset);
  13549. offset += 16;
  13550. instancesCount++;
  13551. }
  13552. if (visibleInstances) {
  13553. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  13554. var instance = visibleInstances[instanceIndex];
  13555. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  13556. offset += 16;
  13557. instancesCount++;
  13558. }
  13559. }
  13560. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  13561. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  13562. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  13563. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  13564. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  13565. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  13566. this._draw(subMesh, fillMode, instancesCount);
  13567. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  13568. };
  13569. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  13570. var scene = this.getScene();
  13571. var engine = scene.getEngine();
  13572. if (hardwareInstancedRendering) {
  13573. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  13574. }
  13575. else {
  13576. if (batch.renderSelf[subMesh._id]) {
  13577. // Draw
  13578. if (onBeforeDraw) {
  13579. onBeforeDraw(false, this.getWorldMatrix());
  13580. }
  13581. this._draw(subMesh, fillMode);
  13582. }
  13583. if (batch.visibleInstances[subMesh._id]) {
  13584. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  13585. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  13586. // World
  13587. var world = instance.getWorldMatrix();
  13588. if (onBeforeDraw) {
  13589. onBeforeDraw(true, world);
  13590. }
  13591. // Draw
  13592. this._draw(subMesh, fillMode);
  13593. }
  13594. }
  13595. }
  13596. };
  13597. Mesh.prototype.render = function (subMesh) {
  13598. var scene = this.getScene();
  13599. // Managing instances
  13600. var batch = this._getInstancesRenderList(subMesh._id);
  13601. if (batch.mustReturn) {
  13602. return;
  13603. }
  13604. // Checking geometry state
  13605. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13606. return;
  13607. }
  13608. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13609. this._onBeforeRenderCallbacks[callbackIndex](this);
  13610. }
  13611. var engine = scene.getEngine();
  13612. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  13613. // Material
  13614. var effectiveMaterial = subMesh.getMaterial();
  13615. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  13616. return;
  13617. }
  13618. // Outline - step 1
  13619. var savedDepthWrite = engine.getDepthWrite();
  13620. if (this.renderOutline) {
  13621. engine.setDepthWrite(false);
  13622. scene.getOutlineRenderer().render(subMesh, batch);
  13623. engine.setDepthWrite(savedDepthWrite);
  13624. }
  13625. effectiveMaterial._preBind();
  13626. var effect = effectiveMaterial.getEffect();
  13627. // Bind
  13628. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  13629. this._bind(subMesh, effect, fillMode);
  13630. var world = this.getWorldMatrix();
  13631. effectiveMaterial.bind(world, this);
  13632. // Draw
  13633. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  13634. if (isInstance) {
  13635. effectiveMaterial.bindOnlyWorldMatrix(world);
  13636. }
  13637. });
  13638. // Unbind
  13639. effectiveMaterial.unbind();
  13640. // Outline - step 2
  13641. if (this.renderOutline && savedDepthWrite) {
  13642. engine.setDepthWrite(true);
  13643. engine.setColorWrite(false);
  13644. scene.getOutlineRenderer().render(subMesh, batch);
  13645. engine.setColorWrite(true);
  13646. }
  13647. // Overlay
  13648. if (this.renderOverlay) {
  13649. var currentMode = engine.getAlphaMode();
  13650. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13651. scene.getOutlineRenderer().render(subMesh, batch, true);
  13652. engine.setAlphaMode(currentMode);
  13653. }
  13654. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13655. this._onAfterRenderCallbacks[callbackIndex](this);
  13656. }
  13657. };
  13658. Mesh.prototype.getEmittedParticleSystems = function () {
  13659. var results = new Array();
  13660. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13661. var particleSystem = this.getScene().particleSystems[index];
  13662. if (particleSystem.emitter === this) {
  13663. results.push(particleSystem);
  13664. }
  13665. }
  13666. return results;
  13667. };
  13668. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  13669. var results = new Array();
  13670. var descendants = this.getDescendants();
  13671. descendants.push(this);
  13672. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13673. var particleSystem = this.getScene().particleSystems[index];
  13674. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  13675. results.push(particleSystem);
  13676. }
  13677. }
  13678. return results;
  13679. };
  13680. Mesh.prototype.getChildren = function () {
  13681. var results = [];
  13682. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13683. var mesh = this.getScene().meshes[index];
  13684. if (mesh.parent === this) {
  13685. results.push(mesh);
  13686. }
  13687. }
  13688. return results;
  13689. };
  13690. Mesh.prototype._checkDelayState = function () {
  13691. var _this = this;
  13692. var that = this;
  13693. var scene = this.getScene();
  13694. if (this._geometry) {
  13695. this._geometry.load(scene);
  13696. }
  13697. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13698. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  13699. scene._addPendingData(that);
  13700. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  13701. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  13702. if (data instanceof ArrayBuffer) {
  13703. _this._delayLoadingFunction(data, _this);
  13704. }
  13705. else {
  13706. _this._delayLoadingFunction(JSON.parse(data), _this);
  13707. }
  13708. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13709. scene._removePendingData(_this);
  13710. }, function () {
  13711. }, scene.database, getBinaryData);
  13712. }
  13713. };
  13714. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  13715. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13716. return false;
  13717. }
  13718. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  13719. return false;
  13720. }
  13721. this._checkDelayState();
  13722. return true;
  13723. };
  13724. Mesh.prototype.setMaterialByID = function (id) {
  13725. var materials = this.getScene().materials;
  13726. for (var index = 0; index < materials.length; index++) {
  13727. if (materials[index].id === id) {
  13728. this.material = materials[index];
  13729. return;
  13730. }
  13731. }
  13732. // Multi
  13733. var multiMaterials = this.getScene().multiMaterials;
  13734. for (index = 0; index < multiMaterials.length; index++) {
  13735. if (multiMaterials[index].id === id) {
  13736. this.material = multiMaterials[index];
  13737. return;
  13738. }
  13739. }
  13740. };
  13741. Mesh.prototype.getAnimatables = function () {
  13742. var results = [];
  13743. if (this.material) {
  13744. results.push(this.material);
  13745. }
  13746. if (this.skeleton) {
  13747. results.push(this.skeleton);
  13748. }
  13749. return results;
  13750. };
  13751. // Geometry
  13752. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  13753. // Position
  13754. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13755. return;
  13756. }
  13757. this._resetPointsArrayCache();
  13758. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13759. var temp = [];
  13760. for (var index = 0; index < data.length; index += 3) {
  13761. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13762. }
  13763. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  13764. // Normals
  13765. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13766. return;
  13767. }
  13768. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13769. temp = [];
  13770. for (index = 0; index < data.length; index += 3) {
  13771. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13772. }
  13773. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  13774. };
  13775. // Cache
  13776. Mesh.prototype._resetPointsArrayCache = function () {
  13777. this._positions = null;
  13778. };
  13779. Mesh.prototype._generatePointsArray = function () {
  13780. if (this._positions)
  13781. return true;
  13782. this._positions = [];
  13783. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13784. if (!data) {
  13785. return false;
  13786. }
  13787. for (var index = 0; index < data.length; index += 3) {
  13788. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  13789. }
  13790. return true;
  13791. };
  13792. // Clone
  13793. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13794. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  13795. };
  13796. // Dispose
  13797. Mesh.prototype.dispose = function (doNotRecurse) {
  13798. if (this._geometry) {
  13799. this._geometry.releaseForMesh(this, true);
  13800. }
  13801. // Instances
  13802. if (this._worldMatricesInstancesBuffer) {
  13803. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13804. this._worldMatricesInstancesBuffer = null;
  13805. }
  13806. while (this.instances.length) {
  13807. this.instances[0].dispose();
  13808. }
  13809. _super.prototype.dispose.call(this, doNotRecurse);
  13810. };
  13811. // Geometric tools
  13812. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  13813. var _this = this;
  13814. var scene = this.getScene();
  13815. var onload = function (img) {
  13816. // Getting height map data
  13817. var canvas = document.createElement("canvas");
  13818. var context = canvas.getContext("2d");
  13819. var heightMapWidth = img.width;
  13820. var heightMapHeight = img.height;
  13821. canvas.width = heightMapWidth;
  13822. canvas.height = heightMapHeight;
  13823. context.drawImage(img, 0, 0);
  13824. // Create VertexData from map data
  13825. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  13826. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  13827. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  13828. //execute success callback, if set
  13829. if (onSuccess) {
  13830. onSuccess(_this);
  13831. }
  13832. };
  13833. BABYLON.Tools.LoadImage(url, onload, function () {
  13834. }, scene.database);
  13835. };
  13836. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  13837. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13838. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  13839. return;
  13840. }
  13841. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13842. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13843. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13844. var position = BABYLON.Vector3.Zero();
  13845. var normal = BABYLON.Vector3.Zero();
  13846. var uv = BABYLON.Vector2.Zero();
  13847. for (var index = 0; index < positions.length; index += 3) {
  13848. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  13849. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  13850. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  13851. // Compute height
  13852. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  13853. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  13854. var pos = (u + v * heightMapWidth) * 4;
  13855. var r = buffer[pos] / 255.0;
  13856. var g = buffer[pos + 1] / 255.0;
  13857. var b = buffer[pos + 2] / 255.0;
  13858. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  13859. normal.normalize();
  13860. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  13861. position = position.add(normal);
  13862. position.toArray(positions, index);
  13863. }
  13864. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  13865. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  13866. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  13867. };
  13868. Mesh.prototype.convertToFlatShadedMesh = function () {
  13869. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  13870. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  13871. var kinds = this.getVerticesDataKinds();
  13872. var vbs = [];
  13873. var data = [];
  13874. var newdata = [];
  13875. var updatableNormals = false;
  13876. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13877. var kind = kinds[kindIndex];
  13878. var vertexBuffer = this.getVertexBuffer(kind);
  13879. if (kind === BABYLON.VertexBuffer.NormalKind) {
  13880. updatableNormals = vertexBuffer.isUpdatable();
  13881. kinds.splice(kindIndex, 1);
  13882. kindIndex--;
  13883. continue;
  13884. }
  13885. vbs[kind] = vertexBuffer;
  13886. data[kind] = vbs[kind].getData();
  13887. newdata[kind] = [];
  13888. }
  13889. // Save previous submeshes
  13890. var previousSubmeshes = this.subMeshes.slice(0);
  13891. var indices = this.getIndices();
  13892. var totalIndices = this.getTotalIndices();
  13893. for (var index = 0; index < totalIndices; index++) {
  13894. var vertexIndex = indices[index];
  13895. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13896. kind = kinds[kindIndex];
  13897. var stride = vbs[kind].getStrideSize();
  13898. for (var offset = 0; offset < stride; offset++) {
  13899. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  13900. }
  13901. }
  13902. }
  13903. // Updating faces & normal
  13904. var normals = [];
  13905. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  13906. for (index = 0; index < totalIndices; index += 3) {
  13907. indices[index] = index;
  13908. indices[index + 1] = index + 1;
  13909. indices[index + 2] = index + 2;
  13910. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  13911. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  13912. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  13913. var p1p2 = p1.subtract(p2);
  13914. var p3p2 = p3.subtract(p2);
  13915. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  13916. for (var localIndex = 0; localIndex < 3; localIndex++) {
  13917. normals.push(normal.x);
  13918. normals.push(normal.y);
  13919. normals.push(normal.z);
  13920. }
  13921. }
  13922. this.setIndices(indices);
  13923. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  13924. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13925. kind = kinds[kindIndex];
  13926. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  13927. }
  13928. // Updating submeshes
  13929. this.releaseSubMeshes();
  13930. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  13931. var previousOne = previousSubmeshes[submeshIndex];
  13932. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  13933. }
  13934. this.synchronizeInstances();
  13935. };
  13936. // Instances
  13937. Mesh.prototype.createInstance = function (name) {
  13938. return new BABYLON.InstancedMesh(name, this);
  13939. };
  13940. Mesh.prototype.synchronizeInstances = function () {
  13941. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  13942. var instance = this.instances[instanceIndex];
  13943. instance._syncSubMeshes();
  13944. }
  13945. };
  13946. /**
  13947. * Simplify the mesh according to the given array of settings.
  13948. * Function will return immediately and will simplify async.
  13949. * @param settings a collection of simplification settings.
  13950. * @param parallelProcessing should all levels calculate parallel or one after the other.
  13951. * @param type the type of simplification to run.
  13952. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  13953. */
  13954. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  13955. if (parallelProcessing === void 0) { parallelProcessing = true; }
  13956. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  13957. this.getScene().simplificationQueue.addTask({
  13958. settings: settings,
  13959. parallelProcessing: parallelProcessing,
  13960. mesh: this,
  13961. simplificationType: simplificationType,
  13962. successCallback: successCallback
  13963. });
  13964. };
  13965. /**
  13966. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  13967. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  13968. * This should be used together with the simplification to avoid disappearing triangles.
  13969. * @param successCallback an optional success callback to be called after the optimization finished.
  13970. */
  13971. Mesh.prototype.optimizeIndices = function (successCallback) {
  13972. var _this = this;
  13973. var indices = this.getIndices();
  13974. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13975. var vectorPositions = [];
  13976. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  13977. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  13978. }
  13979. var dupes = [];
  13980. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  13981. var realPos = vectorPositions.length - 1 - iteration;
  13982. var testedPosition = vectorPositions[realPos];
  13983. for (var j = 0; j < realPos; ++j) {
  13984. var againstPosition = vectorPositions[j];
  13985. if (testedPosition.equals(againstPosition)) {
  13986. dupes[realPos] = j;
  13987. break;
  13988. }
  13989. }
  13990. }, function () {
  13991. for (var i = 0; i < indices.length; ++i) {
  13992. indices[i] = dupes[indices[i]] || indices[i];
  13993. }
  13994. //indices are now reordered
  13995. var originalSubMeshes = _this.subMeshes.slice(0);
  13996. _this.setIndices(indices);
  13997. _this.subMeshes = originalSubMeshes;
  13998. if (successCallback) {
  13999. successCallback(_this);
  14000. }
  14001. });
  14002. };
  14003. // Statics
  14004. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  14005. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14006. if (ribbonInstance === void 0) { ribbonInstance = null; }
  14007. if (ribbonInstance) {
  14008. // positionFunction : ribbon case
  14009. // only pathArray and sideOrientation parameters are taken into account for positions update
  14010. var positionsOfRibbon = function (pathArray, sideOrientation) {
  14011. var positionFunction = function (positions) {
  14012. var minlg = pathArray[0].length;
  14013. var i = 0;
  14014. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  14015. for (var si = 1; si <= ns; si++) {
  14016. for (var p = 0; p < pathArray.length; p++) {
  14017. var path = pathArray[p];
  14018. var l = path.length;
  14019. minlg = (minlg < l) ? minlg : l;
  14020. var j = 0;
  14021. while (j < minlg) {
  14022. positions[i] = path[j].x;
  14023. positions[i + 1] = path[j].y;
  14024. positions[i + 2] = path[j].z;
  14025. j++;
  14026. i += 3;
  14027. }
  14028. }
  14029. }
  14030. };
  14031. return positionFunction;
  14032. };
  14033. var sideOrientation = ribbonInstance.sideOrientation;
  14034. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  14035. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  14036. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  14037. return ribbonInstance;
  14038. }
  14039. else {
  14040. var ribbon = new Mesh(name, scene);
  14041. ribbon.sideOrientation = sideOrientation;
  14042. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  14043. vertexData.applyToMesh(ribbon, updatable);
  14044. return ribbon;
  14045. }
  14046. };
  14047. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14048. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14049. var disc = new Mesh(name, scene);
  14050. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  14051. vertexData.applyToMesh(disc, updatable);
  14052. return disc;
  14053. };
  14054. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14055. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14056. var box = new Mesh(name, scene);
  14057. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  14058. vertexData.applyToMesh(box, updatable);
  14059. return box;
  14060. };
  14061. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14062. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14063. var sphere = new Mesh(name, scene);
  14064. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  14065. vertexData.applyToMesh(sphere, updatable);
  14066. return sphere;
  14067. };
  14068. // Cylinder and cone (Code inspired by SharpDX.org)
  14069. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14070. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14071. // subdivisions is a new parameter, we need to support old signature
  14072. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  14073. if (scene !== undefined) {
  14074. updatable = scene;
  14075. }
  14076. scene = subdivisions;
  14077. subdivisions = 1;
  14078. }
  14079. var cylinder = new Mesh(name, scene);
  14080. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  14081. vertexData.applyToMesh(cylinder, updatable);
  14082. return cylinder;
  14083. };
  14084. // Torus (Code from SharpDX.org)
  14085. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14086. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14087. var torus = new Mesh(name, scene);
  14088. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  14089. vertexData.applyToMesh(torus, updatable);
  14090. return torus;
  14091. };
  14092. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14093. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14094. var torusKnot = new Mesh(name, scene);
  14095. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  14096. vertexData.applyToMesh(torusKnot, updatable);
  14097. return torusKnot;
  14098. };
  14099. // Lines
  14100. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  14101. if (linesInstance === void 0) { linesInstance = null; }
  14102. if (linesInstance) {
  14103. var positionsOfLines = function (points) {
  14104. var positionFunction = function (positions) {
  14105. var i = 0;
  14106. for (var p = 0; p < points.length; p++) {
  14107. positions[i] = points[p].x;
  14108. positions[i + 1] = points[p].y;
  14109. positions[i + 2] = points[p].z;
  14110. i += 3;
  14111. }
  14112. };
  14113. return positionFunction;
  14114. };
  14115. var positionFunction = positionsOfLines(points);
  14116. linesInstance.updateMeshPositions(positionFunction, false);
  14117. return linesInstance;
  14118. }
  14119. // lines creation
  14120. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  14121. var vertexData = BABYLON.VertexData.CreateLines(points);
  14122. vertexData.applyToMesh(lines, updatable);
  14123. return lines;
  14124. };
  14125. // Extrusion
  14126. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14127. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14128. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14129. scale = scale || 1;
  14130. rotation = rotation || 0;
  14131. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  14132. return extruded;
  14133. };
  14134. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14135. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14136. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14137. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  14138. return extrudedCustom;
  14139. };
  14140. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  14141. // extrusion geometry
  14142. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  14143. var tangents = path3D.getTangents();
  14144. var normals = path3D.getNormals();
  14145. var binormals = path3D.getBinormals();
  14146. var distances = path3D.getDistances();
  14147. var angle = 0;
  14148. var returnScale = function (i, distance) {
  14149. return scale;
  14150. };
  14151. var returnRotation = function (i, distance) {
  14152. return rotation;
  14153. };
  14154. var rotate = custom ? rotateFunction : returnRotation;
  14155. var scl = custom ? scaleFunction : returnScale;
  14156. var index = 0;
  14157. for (var i = 0; i < curve.length; i++) {
  14158. var shapePath = new Array();
  14159. var angleStep = rotate(i, distances[i]);
  14160. var scaleRatio = scl(i, distances[i]);
  14161. for (var p = 0; p < shape.length; p++) {
  14162. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  14163. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  14164. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  14165. shapePath.push(rotated);
  14166. }
  14167. shapePaths[index] = shapePath;
  14168. angle += angleStep;
  14169. index++;
  14170. }
  14171. // cap
  14172. var capPath = function (shapePath) {
  14173. var pointCap = Array();
  14174. var barycenter = BABYLON.Vector3.Zero();
  14175. var i;
  14176. for (i = 0; i < shapePath.length; i++) {
  14177. barycenter.addInPlace(shapePath[i]);
  14178. }
  14179. barycenter.scaleInPlace(1 / shapePath.length);
  14180. for (i = 0; i < shapePath.length; i++) {
  14181. pointCap.push(barycenter);
  14182. }
  14183. return pointCap;
  14184. };
  14185. switch (cap) {
  14186. case BABYLON.Mesh.NO_CAP:
  14187. break;
  14188. case BABYLON.Mesh.CAP_START:
  14189. shapePaths.unshift(capPath(shapePaths[0]));
  14190. break;
  14191. case BABYLON.Mesh.CAP_END:
  14192. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14193. break;
  14194. case BABYLON.Mesh.CAP_ALL:
  14195. shapePaths.unshift(capPath(shapePaths[0]));
  14196. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14197. break;
  14198. default:
  14199. break;
  14200. }
  14201. return shapePaths;
  14202. };
  14203. if (instance) {
  14204. var path3D = (instance.path3D).update(curve);
  14205. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  14206. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  14207. return instance;
  14208. }
  14209. // extruded shape creation
  14210. var path3D = new BABYLON.Path3D(curve);
  14211. var newShapePaths = new Array();
  14212. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14213. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  14214. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  14215. extrudedGeneric.pathArray = pathArray;
  14216. extrudedGeneric.path3D = path3D;
  14217. extrudedGeneric.cap = cap;
  14218. return extrudedGeneric;
  14219. };
  14220. // Plane & ground
  14221. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14222. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14223. var plane = new Mesh(name, scene);
  14224. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  14225. vertexData.applyToMesh(plane, updatable);
  14226. return plane;
  14227. };
  14228. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14229. var ground = new BABYLON.GroundMesh(name, scene);
  14230. ground._setReady(false);
  14231. ground._subdivisions = subdivisions;
  14232. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  14233. vertexData.applyToMesh(ground, updatable);
  14234. ground._setReady(true);
  14235. return ground;
  14236. };
  14237. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14238. var tiledGround = new Mesh(name, scene);
  14239. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  14240. vertexData.applyToMesh(tiledGround, updatable);
  14241. return tiledGround;
  14242. };
  14243. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  14244. var ground = new BABYLON.GroundMesh(name, scene);
  14245. ground._subdivisions = subdivisions;
  14246. ground._setReady(false);
  14247. var onload = function (img) {
  14248. // Getting height map data
  14249. var canvas = document.createElement("canvas");
  14250. var context = canvas.getContext("2d");
  14251. var heightMapWidth = img.width;
  14252. var heightMapHeight = img.height;
  14253. canvas.width = heightMapWidth;
  14254. canvas.height = heightMapHeight;
  14255. context.drawImage(img, 0, 0);
  14256. // Create VertexData from map data
  14257. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14258. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14259. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  14260. vertexData.applyToMesh(ground, updatable);
  14261. ground._setReady(true);
  14262. //execute ready callback, if set
  14263. if (onReady) {
  14264. onReady(ground);
  14265. }
  14266. };
  14267. BABYLON.Tools.LoadImage(url, onload, function () {
  14268. }, scene.database);
  14269. return ground;
  14270. };
  14271. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  14272. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14273. if (tubeInstance === void 0) { tubeInstance = null; }
  14274. // tube geometry
  14275. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  14276. var tangents = path3D.getTangents();
  14277. var normals = path3D.getNormals();
  14278. var distances = path3D.getDistances();
  14279. var pi2 = Math.PI * 2;
  14280. var step = pi2 / tessellation;
  14281. var returnRadius = function (i, distance) { return radius; };
  14282. var radiusFunctionFinal = radiusFunction || returnRadius;
  14283. var circlePath;
  14284. var rad;
  14285. var normal;
  14286. var rotated;
  14287. var rotationMatrix;
  14288. var index = 0;
  14289. for (var i = 0; i < path.length; i++) {
  14290. rad = radiusFunctionFinal(i, distances[i]); // current radius
  14291. circlePath = Array(); // current circle array
  14292. normal = normals[i]; // current normal
  14293. for (var t = 0; t < tessellation; t++) {
  14294. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  14295. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  14296. circlePath.push(rotated);
  14297. }
  14298. circlePath.push(circlePath[0]);
  14299. circlePaths[index] = circlePath;
  14300. index++;
  14301. }
  14302. // cap
  14303. var capPath = function (nbPoints, pathIndex) {
  14304. var pointCap = Array();
  14305. for (var i = 0; i < nbPoints; i++) {
  14306. pointCap.push(path[pathIndex]);
  14307. }
  14308. return pointCap;
  14309. };
  14310. switch (cap) {
  14311. case BABYLON.Mesh.NO_CAP:
  14312. break;
  14313. case BABYLON.Mesh.CAP_START:
  14314. circlePaths.unshift(capPath(tessellation + 1, 0));
  14315. break;
  14316. case BABYLON.Mesh.CAP_END:
  14317. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14318. break;
  14319. case BABYLON.Mesh.CAP_ALL:
  14320. circlePaths.unshift(capPath(tessellation + 1, 0));
  14321. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14322. break;
  14323. default:
  14324. break;
  14325. }
  14326. return circlePaths;
  14327. };
  14328. if (tubeInstance) {
  14329. var path3D = (tubeInstance.path3D).update(path);
  14330. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  14331. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  14332. return tubeInstance;
  14333. }
  14334. // tube creation
  14335. var path3D = new BABYLON.Path3D(path);
  14336. var newPathArray = new Array();
  14337. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14338. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  14339. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  14340. tube.pathArray = pathArray;
  14341. tube.path3D = path3D;
  14342. tube.tessellation = tessellation;
  14343. tube.cap = cap;
  14344. return tube;
  14345. };
  14346. // Decals
  14347. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  14348. if (angle === void 0) { angle = 0; }
  14349. var indices = sourceMesh.getIndices();
  14350. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14351. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14352. // Getting correct rotation
  14353. if (!normal) {
  14354. var target = new BABYLON.Vector3(0, 0, 1);
  14355. var camera = sourceMesh.getScene().activeCamera;
  14356. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  14357. normal = camera.globalPosition.subtract(cameraWorldTarget);
  14358. }
  14359. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  14360. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  14361. var pitch = Math.atan2(normal.y, len);
  14362. // Matrix
  14363. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  14364. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  14365. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  14366. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  14367. var vertexData = new BABYLON.VertexData();
  14368. vertexData.indices = [];
  14369. vertexData.positions = [];
  14370. vertexData.normals = [];
  14371. vertexData.uvs = [];
  14372. var currentVertexDataIndex = 0;
  14373. var extractDecalVector3 = function (indexId) {
  14374. var vertexId = indices[indexId];
  14375. var result = new BABYLON.PositionNormalVertex();
  14376. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  14377. // Send vector to decal local world
  14378. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  14379. // Get normal
  14380. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  14381. return result;
  14382. };
  14383. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  14384. var clip = function (vertices, axis) {
  14385. if (vertices.length === 0) {
  14386. return vertices;
  14387. }
  14388. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  14389. var clipVertices = function (v0, v1) {
  14390. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  14391. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  14392. };
  14393. var result = new Array();
  14394. for (var index = 0; index < vertices.length; index += 3) {
  14395. var v1Out;
  14396. var v2Out;
  14397. var v3Out;
  14398. var total = 0;
  14399. var nV1, nV2, nV3, nV4;
  14400. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  14401. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  14402. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  14403. v1Out = d1 > 0;
  14404. v2Out = d2 > 0;
  14405. v3Out = d3 > 0;
  14406. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  14407. switch (total) {
  14408. case 0:
  14409. result.push(vertices[index]);
  14410. result.push(vertices[index + 1]);
  14411. result.push(vertices[index + 2]);
  14412. break;
  14413. case 1:
  14414. if (v1Out) {
  14415. nV1 = vertices[index + 1];
  14416. nV2 = vertices[index + 2];
  14417. nV3 = clipVertices(vertices[index], nV1);
  14418. nV4 = clipVertices(vertices[index], nV2);
  14419. }
  14420. if (v2Out) {
  14421. nV1 = vertices[index];
  14422. nV2 = vertices[index + 2];
  14423. nV3 = clipVertices(vertices[index + 1], nV1);
  14424. nV4 = clipVertices(vertices[index + 1], nV2);
  14425. result.push(nV3);
  14426. result.push(nV2.clone());
  14427. result.push(nV1.clone());
  14428. result.push(nV2.clone());
  14429. result.push(nV3.clone());
  14430. result.push(nV4);
  14431. break;
  14432. }
  14433. if (v3Out) {
  14434. nV1 = vertices[index];
  14435. nV2 = vertices[index + 1];
  14436. nV3 = clipVertices(vertices[index + 2], nV1);
  14437. nV4 = clipVertices(vertices[index + 2], nV2);
  14438. }
  14439. result.push(nV1.clone());
  14440. result.push(nV2.clone());
  14441. result.push(nV3);
  14442. result.push(nV4);
  14443. result.push(nV3.clone());
  14444. result.push(nV2.clone());
  14445. break;
  14446. case 2:
  14447. if (!v1Out) {
  14448. nV1 = vertices[index].clone();
  14449. nV2 = clipVertices(nV1, vertices[index + 1]);
  14450. nV3 = clipVertices(nV1, vertices[index + 2]);
  14451. result.push(nV1);
  14452. result.push(nV2);
  14453. result.push(nV3);
  14454. }
  14455. if (!v2Out) {
  14456. nV1 = vertices[index + 1].clone();
  14457. nV2 = clipVertices(nV1, vertices[index + 2]);
  14458. nV3 = clipVertices(nV1, vertices[index]);
  14459. result.push(nV1);
  14460. result.push(nV2);
  14461. result.push(nV3);
  14462. }
  14463. if (!v3Out) {
  14464. nV1 = vertices[index + 2].clone();
  14465. nV2 = clipVertices(nV1, vertices[index]);
  14466. nV3 = clipVertices(nV1, vertices[index + 1]);
  14467. result.push(nV1);
  14468. result.push(nV2);
  14469. result.push(nV3);
  14470. }
  14471. break;
  14472. case 3:
  14473. break;
  14474. }
  14475. }
  14476. return result;
  14477. };
  14478. for (var index = 0; index < indices.length; index += 3) {
  14479. var faceVertices = new Array();
  14480. faceVertices.push(extractDecalVector3(index));
  14481. faceVertices.push(extractDecalVector3(index + 1));
  14482. faceVertices.push(extractDecalVector3(index + 2));
  14483. // Clip
  14484. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  14485. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  14486. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  14487. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  14488. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  14489. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  14490. if (faceVertices.length === 0) {
  14491. continue;
  14492. }
  14493. // Add UVs and get back to world
  14494. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  14495. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  14496. var vertex = faceVertices[vIndex];
  14497. vertexData.indices.push(currentVertexDataIndex);
  14498. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  14499. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  14500. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  14501. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  14502. currentVertexDataIndex++;
  14503. }
  14504. }
  14505. // Return mesh
  14506. var decal = new Mesh(name, sourceMesh.getScene());
  14507. vertexData.applyToMesh(decal);
  14508. decal.position = position.clone();
  14509. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  14510. return decal;
  14511. };
  14512. // Tools
  14513. Mesh.MinMax = function (meshes) {
  14514. var minVector = null;
  14515. var maxVector = null;
  14516. for (var i in meshes) {
  14517. var mesh = meshes[i];
  14518. var boundingBox = mesh.getBoundingInfo().boundingBox;
  14519. if (!minVector) {
  14520. minVector = boundingBox.minimumWorld;
  14521. maxVector = boundingBox.maximumWorld;
  14522. continue;
  14523. }
  14524. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  14525. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  14526. }
  14527. return {
  14528. min: minVector,
  14529. max: maxVector
  14530. };
  14531. };
  14532. Mesh.Center = function (meshesOrMinMaxVector) {
  14533. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  14534. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  14535. };
  14536. /**
  14537. * Merge the array of meshes into a single mesh for performance reasons.
  14538. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  14539. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  14540. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  14541. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  14542. */
  14543. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  14544. if (disposeSource === void 0) { disposeSource = true; }
  14545. if (!allow32BitsIndices) {
  14546. var totalVertices = 0;
  14547. for (var index = 0; index < meshes.length; index++) {
  14548. if (meshes[index]) {
  14549. totalVertices += meshes[index].getTotalVertices();
  14550. if (totalVertices > 65536) {
  14551. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  14552. return null;
  14553. }
  14554. }
  14555. }
  14556. }
  14557. // Merge
  14558. var vertexData;
  14559. var otherVertexData;
  14560. var source;
  14561. for (index = 0; index < meshes.length; index++) {
  14562. if (meshes[index]) {
  14563. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  14564. otherVertexData.transform(meshes[index].getWorldMatrix());
  14565. if (vertexData) {
  14566. vertexData.merge(otherVertexData);
  14567. }
  14568. else {
  14569. vertexData = otherVertexData;
  14570. source = meshes[index];
  14571. }
  14572. }
  14573. }
  14574. if (!meshSubclass) {
  14575. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  14576. }
  14577. vertexData.applyToMesh(meshSubclass);
  14578. // Setting properties
  14579. meshSubclass.material = source.material;
  14580. meshSubclass.checkCollisions = source.checkCollisions;
  14581. // Cleaning
  14582. if (disposeSource) {
  14583. for (index = 0; index < meshes.length; index++) {
  14584. if (meshes[index]) {
  14585. meshes[index].dispose();
  14586. }
  14587. }
  14588. }
  14589. return meshSubclass;
  14590. };
  14591. // Consts
  14592. Mesh._FRONTSIDE = 0;
  14593. Mesh._BACKSIDE = 1;
  14594. Mesh._DOUBLESIDE = 2;
  14595. Mesh._DEFAULTSIDE = 0;
  14596. Mesh._NO_CAP = 0;
  14597. Mesh._CAP_START = 1;
  14598. Mesh._CAP_END = 2;
  14599. Mesh._CAP_ALL = 3;
  14600. return Mesh;
  14601. })(BABYLON.AbstractMesh);
  14602. BABYLON.Mesh = Mesh;
  14603. })(BABYLON || (BABYLON = {}));
  14604. //# sourceMappingURL=babylon.mesh.js.map
  14605. var BABYLON;
  14606. (function (BABYLON) {
  14607. var SubMesh = (function () {
  14608. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  14609. if (createBoundingBox === void 0) { createBoundingBox = true; }
  14610. this.materialIndex = materialIndex;
  14611. this.verticesStart = verticesStart;
  14612. this.verticesCount = verticesCount;
  14613. this.indexStart = indexStart;
  14614. this.indexCount = indexCount;
  14615. this._renderId = 0;
  14616. this._mesh = mesh;
  14617. this._renderingMesh = renderingMesh || mesh;
  14618. mesh.subMeshes.push(this);
  14619. this._trianglePlanes = [];
  14620. this._id = mesh.subMeshes.length - 1;
  14621. if (createBoundingBox) {
  14622. this.refreshBoundingInfo();
  14623. mesh.computeWorldMatrix(true);
  14624. }
  14625. }
  14626. SubMesh.prototype.getBoundingInfo = function () {
  14627. return this._boundingInfo;
  14628. };
  14629. SubMesh.prototype.getMesh = function () {
  14630. return this._mesh;
  14631. };
  14632. SubMesh.prototype.getRenderingMesh = function () {
  14633. return this._renderingMesh;
  14634. };
  14635. SubMesh.prototype.getMaterial = function () {
  14636. var rootMaterial = this._renderingMesh.material;
  14637. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  14638. var multiMaterial = rootMaterial;
  14639. return multiMaterial.getSubMaterial(this.materialIndex);
  14640. }
  14641. if (!rootMaterial) {
  14642. return this._mesh.getScene().defaultMaterial;
  14643. }
  14644. return rootMaterial;
  14645. };
  14646. // Methods
  14647. SubMesh.prototype.refreshBoundingInfo = function () {
  14648. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14649. if (!data) {
  14650. this._boundingInfo = this._mesh._boundingInfo;
  14651. return;
  14652. }
  14653. var indices = this._renderingMesh.getIndices();
  14654. var extend;
  14655. if (this.indexStart === 0 && this.indexCount === indices.length) {
  14656. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  14657. }
  14658. else {
  14659. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  14660. }
  14661. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14662. };
  14663. SubMesh.prototype._checkCollision = function (collider) {
  14664. return this._boundingInfo._checkCollision(collider);
  14665. };
  14666. SubMesh.prototype.updateBoundingInfo = function (world) {
  14667. if (!this._boundingInfo) {
  14668. this.refreshBoundingInfo();
  14669. }
  14670. this._boundingInfo._update(world);
  14671. };
  14672. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  14673. return this._boundingInfo.isInFrustum(frustumPlanes);
  14674. };
  14675. SubMesh.prototype.render = function () {
  14676. this._renderingMesh.render(this);
  14677. };
  14678. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  14679. if (!this._linesIndexBuffer) {
  14680. var linesIndices = [];
  14681. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14682. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  14683. }
  14684. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  14685. this.linesIndexCount = linesIndices.length;
  14686. }
  14687. return this._linesIndexBuffer;
  14688. };
  14689. SubMesh.prototype.canIntersects = function (ray) {
  14690. return ray.intersectsBox(this._boundingInfo.boundingBox);
  14691. };
  14692. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  14693. var intersectInfo = null;
  14694. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14695. var p0 = positions[indices[index]];
  14696. var p1 = positions[indices[index + 1]];
  14697. var p2 = positions[indices[index + 2]];
  14698. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  14699. if (currentIntersectInfo) {
  14700. if (currentIntersectInfo.distance < 0) {
  14701. continue;
  14702. }
  14703. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14704. intersectInfo = currentIntersectInfo;
  14705. intersectInfo.faceId = index / 3;
  14706. if (fastCheck) {
  14707. break;
  14708. }
  14709. }
  14710. }
  14711. }
  14712. return intersectInfo;
  14713. };
  14714. // Clone
  14715. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  14716. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  14717. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  14718. return result;
  14719. };
  14720. // Dispose
  14721. SubMesh.prototype.dispose = function () {
  14722. if (this._linesIndexBuffer) {
  14723. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  14724. this._linesIndexBuffer = null;
  14725. }
  14726. // Remove from mesh
  14727. var index = this._mesh.subMeshes.indexOf(this);
  14728. this._mesh.subMeshes.splice(index, 1);
  14729. };
  14730. // Statics
  14731. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  14732. var minVertexIndex = Number.MAX_VALUE;
  14733. var maxVertexIndex = -Number.MAX_VALUE;
  14734. renderingMesh = renderingMesh || mesh;
  14735. var indices = renderingMesh.getIndices();
  14736. for (var index = startIndex; index < startIndex + indexCount; index++) {
  14737. var vertexIndex = indices[index];
  14738. if (vertexIndex < minVertexIndex)
  14739. minVertexIndex = vertexIndex;
  14740. if (vertexIndex > maxVertexIndex)
  14741. maxVertexIndex = vertexIndex;
  14742. }
  14743. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  14744. };
  14745. return SubMesh;
  14746. })();
  14747. BABYLON.SubMesh = SubMesh;
  14748. })(BABYLON || (BABYLON = {}));
  14749. //# sourceMappingURL=babylon.subMesh.js.map
  14750. var BABYLON;
  14751. (function (BABYLON) {
  14752. var BaseTexture = (function () {
  14753. function BaseTexture(scene) {
  14754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14755. this.hasAlpha = false;
  14756. this.getAlphaFromRGB = false;
  14757. this.level = 1;
  14758. this.isCube = false;
  14759. this.isRenderTarget = false;
  14760. this.animations = new Array();
  14761. this.coordinatesIndex = 0;
  14762. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  14763. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14764. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14765. this.anisotropicFilteringLevel = 4;
  14766. this._scene = scene;
  14767. this._scene.textures.push(this);
  14768. }
  14769. BaseTexture.prototype.getScene = function () {
  14770. return this._scene;
  14771. };
  14772. BaseTexture.prototype.getTextureMatrix = function () {
  14773. return null;
  14774. };
  14775. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  14776. return null;
  14777. };
  14778. BaseTexture.prototype.getInternalTexture = function () {
  14779. return this._texture;
  14780. };
  14781. BaseTexture.prototype.isReady = function () {
  14782. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14783. return true;
  14784. }
  14785. if (this._texture) {
  14786. return this._texture.isReady;
  14787. }
  14788. return false;
  14789. };
  14790. BaseTexture.prototype.getSize = function () {
  14791. if (this._texture._width) {
  14792. return { width: this._texture._width, height: this._texture._height };
  14793. }
  14794. if (this._texture._size) {
  14795. return { width: this._texture._size, height: this._texture._size };
  14796. }
  14797. return { width: 0, height: 0 };
  14798. };
  14799. BaseTexture.prototype.getBaseSize = function () {
  14800. if (!this.isReady())
  14801. return { width: 0, height: 0 };
  14802. if (this._texture._size) {
  14803. return { width: this._texture._size, height: this._texture._size };
  14804. }
  14805. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  14806. };
  14807. BaseTexture.prototype.scale = function (ratio) {
  14808. };
  14809. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  14810. get: function () {
  14811. return false;
  14812. },
  14813. enumerable: true,
  14814. configurable: true
  14815. });
  14816. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  14817. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14818. for (var index = 0; index < texturesCache.length; index++) {
  14819. var texturesCacheEntry = texturesCache[index];
  14820. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14821. texturesCache.splice(index, 1);
  14822. return;
  14823. }
  14824. }
  14825. };
  14826. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  14827. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14828. for (var index = 0; index < texturesCache.length; index++) {
  14829. var texturesCacheEntry = texturesCache[index];
  14830. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14831. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  14832. texturesCacheEntry.references++;
  14833. return texturesCacheEntry;
  14834. }
  14835. }
  14836. }
  14837. return null;
  14838. };
  14839. BaseTexture.prototype.delayLoad = function () {
  14840. };
  14841. BaseTexture.prototype.releaseInternalTexture = function () {
  14842. if (!this._texture) {
  14843. return;
  14844. }
  14845. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14846. this._texture.references--;
  14847. // Final reference ?
  14848. if (this._texture.references === 0) {
  14849. var index = texturesCache.indexOf(this._texture);
  14850. texturesCache.splice(index, 1);
  14851. this._scene.getEngine()._releaseTexture(this._texture);
  14852. delete this._texture;
  14853. }
  14854. };
  14855. BaseTexture.prototype.clone = function () {
  14856. return null;
  14857. };
  14858. BaseTexture.prototype.dispose = function () {
  14859. // Remove from scene
  14860. var index = this._scene.textures.indexOf(this);
  14861. if (index >= 0) {
  14862. this._scene.textures.splice(index, 1);
  14863. }
  14864. if (this._texture === undefined) {
  14865. return;
  14866. }
  14867. this.releaseInternalTexture();
  14868. // Callback
  14869. if (this.onDispose) {
  14870. this.onDispose();
  14871. }
  14872. };
  14873. return BaseTexture;
  14874. })();
  14875. BABYLON.BaseTexture = BaseTexture;
  14876. })(BABYLON || (BABYLON = {}));
  14877. //# sourceMappingURL=babylon.baseTexture.js.map
  14878. var __extends = this.__extends || function (d, b) {
  14879. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14880. function __() { this.constructor = d; }
  14881. __.prototype = b.prototype;
  14882. d.prototype = new __();
  14883. };
  14884. var BABYLON;
  14885. (function (BABYLON) {
  14886. var Texture = (function (_super) {
  14887. __extends(Texture, _super);
  14888. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  14889. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  14890. if (onLoad === void 0) { onLoad = null; }
  14891. if (onError === void 0) { onError = null; }
  14892. if (buffer === void 0) { buffer = null; }
  14893. if (deleteBuffer === void 0) { deleteBuffer = false; }
  14894. _super.call(this, scene);
  14895. this.uOffset = 0;
  14896. this.vOffset = 0;
  14897. this.uScale = 1.0;
  14898. this.vScale = 1.0;
  14899. this.uAng = 0;
  14900. this.vAng = 0;
  14901. this.wAng = 0;
  14902. this.name = url;
  14903. this.url = url;
  14904. this._noMipmap = noMipmap;
  14905. this._invertY = invertY;
  14906. this._samplingMode = samplingMode;
  14907. this._buffer = buffer;
  14908. this._deleteBuffer = deleteBuffer;
  14909. if (!url) {
  14910. return;
  14911. }
  14912. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  14913. if (!this._texture) {
  14914. if (!scene.useDelayedTextureLoading) {
  14915. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  14916. if (deleteBuffer) {
  14917. delete this._buffer;
  14918. }
  14919. }
  14920. else {
  14921. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14922. }
  14923. }
  14924. }
  14925. Texture.prototype.delayLoad = function () {
  14926. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14927. return;
  14928. }
  14929. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14930. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  14931. if (!this._texture) {
  14932. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  14933. if (this._deleteBuffer) {
  14934. delete this._buffer;
  14935. }
  14936. }
  14937. };
  14938. Texture.prototype.updateSamplingMode = function (samplingMode) {
  14939. if (!this._texture) {
  14940. return;
  14941. }
  14942. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  14943. };
  14944. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  14945. x -= this.uOffset + 0.5;
  14946. y -= this.vOffset + 0.5;
  14947. z -= 0.5;
  14948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  14949. t.x *= this.uScale;
  14950. t.y *= this.vScale;
  14951. t.x += 0.5;
  14952. t.y += 0.5;
  14953. t.z += 0.5;
  14954. };
  14955. Texture.prototype.getTextureMatrix = function () {
  14956. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  14957. return this._cachedTextureMatrix;
  14958. }
  14959. this._cachedUOffset = this.uOffset;
  14960. this._cachedVOffset = this.vOffset;
  14961. this._cachedUScale = this.uScale;
  14962. this._cachedVScale = this.vScale;
  14963. this._cachedUAng = this.uAng;
  14964. this._cachedVAng = this.vAng;
  14965. this._cachedWAng = this.wAng;
  14966. if (!this._cachedTextureMatrix) {
  14967. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  14968. this._rowGenerationMatrix = new BABYLON.Matrix();
  14969. this._t0 = BABYLON.Vector3.Zero();
  14970. this._t1 = BABYLON.Vector3.Zero();
  14971. this._t2 = BABYLON.Vector3.Zero();
  14972. }
  14973. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  14974. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  14975. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  14976. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  14977. this._t1.subtractInPlace(this._t0);
  14978. this._t2.subtractInPlace(this._t0);
  14979. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  14980. this._cachedTextureMatrix.m[0] = this._t1.x;
  14981. this._cachedTextureMatrix.m[1] = this._t1.y;
  14982. this._cachedTextureMatrix.m[2] = this._t1.z;
  14983. this._cachedTextureMatrix.m[4] = this._t2.x;
  14984. this._cachedTextureMatrix.m[5] = this._t2.y;
  14985. this._cachedTextureMatrix.m[6] = this._t2.z;
  14986. this._cachedTextureMatrix.m[8] = this._t0.x;
  14987. this._cachedTextureMatrix.m[9] = this._t0.y;
  14988. this._cachedTextureMatrix.m[10] = this._t0.z;
  14989. return this._cachedTextureMatrix;
  14990. };
  14991. Texture.prototype.getReflectionTextureMatrix = function () {
  14992. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  14993. return this._cachedTextureMatrix;
  14994. }
  14995. if (!this._cachedTextureMatrix) {
  14996. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  14997. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  14998. }
  14999. this._cachedCoordinatesMode = this.coordinatesMode;
  15000. switch (this.coordinatesMode) {
  15001. case Texture.SPHERICAL_MODE:
  15002. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15003. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  15004. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  15005. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  15006. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  15007. break;
  15008. case Texture.PLANAR_MODE:
  15009. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15010. this._cachedTextureMatrix[0] = this.uScale;
  15011. this._cachedTextureMatrix[5] = this.vScale;
  15012. this._cachedTextureMatrix[12] = this.uOffset;
  15013. this._cachedTextureMatrix[13] = this.vOffset;
  15014. break;
  15015. case Texture.PROJECTION_MODE:
  15016. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  15017. this._projectionModeMatrix.m[0] = 0.5;
  15018. this._projectionModeMatrix.m[5] = -0.5;
  15019. this._projectionModeMatrix.m[10] = 0.0;
  15020. this._projectionModeMatrix.m[12] = 0.5;
  15021. this._projectionModeMatrix.m[13] = 0.5;
  15022. this._projectionModeMatrix.m[14] = 1.0;
  15023. this._projectionModeMatrix.m[15] = 1.0;
  15024. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  15025. break;
  15026. default:
  15027. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15028. break;
  15029. }
  15030. return this._cachedTextureMatrix;
  15031. };
  15032. Texture.prototype.clone = function () {
  15033. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  15034. // Base texture
  15035. newTexture.hasAlpha = this.hasAlpha;
  15036. newTexture.level = this.level;
  15037. newTexture.wrapU = this.wrapU;
  15038. newTexture.wrapV = this.wrapV;
  15039. newTexture.coordinatesIndex = this.coordinatesIndex;
  15040. newTexture.coordinatesMode = this.coordinatesMode;
  15041. // Texture
  15042. newTexture.uOffset = this.uOffset;
  15043. newTexture.vOffset = this.vOffset;
  15044. newTexture.uScale = this.uScale;
  15045. newTexture.vScale = this.vScale;
  15046. newTexture.uAng = this.uAng;
  15047. newTexture.vAng = this.vAng;
  15048. newTexture.wAng = this.wAng;
  15049. return newTexture;
  15050. };
  15051. // Statics
  15052. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  15053. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  15054. if (onLoad === void 0) { onLoad = null; }
  15055. if (onError === void 0) { onError = null; }
  15056. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  15057. };
  15058. // Constants
  15059. Texture.NEAREST_SAMPLINGMODE = 1;
  15060. Texture.BILINEAR_SAMPLINGMODE = 2;
  15061. Texture.TRILINEAR_SAMPLINGMODE = 3;
  15062. Texture.EXPLICIT_MODE = 0;
  15063. Texture.SPHERICAL_MODE = 1;
  15064. Texture.PLANAR_MODE = 2;
  15065. Texture.CUBIC_MODE = 3;
  15066. Texture.PROJECTION_MODE = 4;
  15067. Texture.SKYBOX_MODE = 5;
  15068. Texture.CLAMP_ADDRESSMODE = 0;
  15069. Texture.WRAP_ADDRESSMODE = 1;
  15070. Texture.MIRROR_ADDRESSMODE = 2;
  15071. return Texture;
  15072. })(BABYLON.BaseTexture);
  15073. BABYLON.Texture = Texture;
  15074. })(BABYLON || (BABYLON = {}));
  15075. //# sourceMappingURL=babylon.texture.js.map
  15076. var __extends = this.__extends || function (d, b) {
  15077. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15078. function __() { this.constructor = d; }
  15079. __.prototype = b.prototype;
  15080. d.prototype = new __();
  15081. };
  15082. var BABYLON;
  15083. (function (BABYLON) {
  15084. var CubeTexture = (function (_super) {
  15085. __extends(CubeTexture, _super);
  15086. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  15087. _super.call(this, scene);
  15088. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  15089. this.name = rootUrl;
  15090. this.url = rootUrl;
  15091. this._noMipmap = noMipmap;
  15092. this.hasAlpha = false;
  15093. this._texture = this._getFromCache(rootUrl, noMipmap);
  15094. if (!extensions) {
  15095. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  15096. }
  15097. this._extensions = extensions;
  15098. if (!this._texture) {
  15099. if (!scene.useDelayedTextureLoading) {
  15100. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  15101. }
  15102. else {
  15103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15104. }
  15105. }
  15106. this.isCube = true;
  15107. this._textureMatrix = BABYLON.Matrix.Identity();
  15108. }
  15109. CubeTexture.prototype.clone = function () {
  15110. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  15111. // Base texture
  15112. newTexture.level = this.level;
  15113. newTexture.wrapU = this.wrapU;
  15114. newTexture.wrapV = this.wrapV;
  15115. newTexture.coordinatesIndex = this.coordinatesIndex;
  15116. newTexture.coordinatesMode = this.coordinatesMode;
  15117. return newTexture;
  15118. };
  15119. // Methods
  15120. CubeTexture.prototype.delayLoad = function () {
  15121. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15122. return;
  15123. }
  15124. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15125. this._texture = this._getFromCache(this.url, this._noMipmap);
  15126. if (!this._texture) {
  15127. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  15128. }
  15129. };
  15130. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  15131. return this._textureMatrix;
  15132. };
  15133. return CubeTexture;
  15134. })(BABYLON.BaseTexture);
  15135. BABYLON.CubeTexture = CubeTexture;
  15136. })(BABYLON || (BABYLON = {}));
  15137. //# sourceMappingURL=babylon.cubeTexture.js.map
  15138. var __extends = this.__extends || function (d, b) {
  15139. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15140. function __() { this.constructor = d; }
  15141. __.prototype = b.prototype;
  15142. d.prototype = new __();
  15143. };
  15144. var BABYLON;
  15145. (function (BABYLON) {
  15146. var RenderTargetTexture = (function (_super) {
  15147. __extends(RenderTargetTexture, _super);
  15148. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  15149. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  15150. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  15151. _super.call(this, null, scene, !generateMipMaps);
  15152. this.renderList = new Array();
  15153. this.renderParticles = true;
  15154. this.renderSprites = false;
  15155. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  15156. this._currentRefreshId = -1;
  15157. this._refreshRate = 1;
  15158. this.name = name;
  15159. this.isRenderTarget = true;
  15160. this._size = size;
  15161. this._generateMipMaps = generateMipMaps;
  15162. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  15163. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  15164. // Rendering groups
  15165. this._renderingManager = new BABYLON.RenderingManager(scene);
  15166. }
  15167. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  15168. this._currentRefreshId = -1;
  15169. };
  15170. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  15171. get: function () {
  15172. return this._refreshRate;
  15173. },
  15174. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15175. set: function (value) {
  15176. this._refreshRate = value;
  15177. this.resetRefreshCounter();
  15178. },
  15179. enumerable: true,
  15180. configurable: true
  15181. });
  15182. RenderTargetTexture.prototype._shouldRender = function () {
  15183. if (this._currentRefreshId === -1) {
  15184. this._currentRefreshId = 1;
  15185. return true;
  15186. }
  15187. if (this.refreshRate === this._currentRefreshId) {
  15188. this._currentRefreshId = 1;
  15189. return true;
  15190. }
  15191. this._currentRefreshId++;
  15192. return false;
  15193. };
  15194. RenderTargetTexture.prototype.isReady = function () {
  15195. if (!this.getScene().renderTargetsEnabled) {
  15196. return false;
  15197. }
  15198. return _super.prototype.isReady.call(this);
  15199. };
  15200. RenderTargetTexture.prototype.getRenderSize = function () {
  15201. return this._size;
  15202. };
  15203. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  15204. get: function () {
  15205. return true;
  15206. },
  15207. enumerable: true,
  15208. configurable: true
  15209. });
  15210. RenderTargetTexture.prototype.scale = function (ratio) {
  15211. var newSize = this._size * ratio;
  15212. this.resize(newSize, this._generateMipMaps);
  15213. };
  15214. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  15215. this.releaseInternalTexture();
  15216. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15217. };
  15218. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  15219. var scene = this.getScene();
  15220. var engine = scene.getEngine();
  15221. if (this._waitingRenderList) {
  15222. this.renderList = [];
  15223. for (var index = 0; index < this._waitingRenderList.length; index++) {
  15224. var id = this._waitingRenderList[index];
  15225. this.renderList.push(scene.getMeshByID(id));
  15226. }
  15227. delete this._waitingRenderList;
  15228. }
  15229. if (this.renderList && this.renderList.length === 0) {
  15230. return;
  15231. }
  15232. // Bind
  15233. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  15234. engine.bindFramebuffer(this._texture);
  15235. }
  15236. this._renderingManager.reset();
  15237. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  15238. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  15239. var mesh = currentRenderList[meshIndex];
  15240. if (mesh) {
  15241. if (!mesh.isReady()) {
  15242. // Reset _currentRefreshId
  15243. this.resetRefreshCounter();
  15244. continue;
  15245. }
  15246. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  15247. mesh._activate(scene.getRenderId());
  15248. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15249. var subMesh = mesh.subMeshes[subIndex];
  15250. scene._activeIndices += subMesh.indexCount;
  15251. this._renderingManager.dispatch(subMesh);
  15252. }
  15253. }
  15254. }
  15255. }
  15256. if (this.onBeforeRender) {
  15257. this.onBeforeRender();
  15258. }
  15259. // Clear
  15260. if (this.onClear) {
  15261. this.onClear(engine);
  15262. }
  15263. else {
  15264. engine.clear(scene.clearColor, true, true);
  15265. }
  15266. if (!this._doNotChangeAspectRatio) {
  15267. scene.updateTransformMatrix(true);
  15268. }
  15269. // Render
  15270. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  15271. if (useCameraPostProcess) {
  15272. scene.postProcessManager._finalizeFrame(false, this._texture);
  15273. }
  15274. if (!this._doNotChangeAspectRatio) {
  15275. scene.updateTransformMatrix(true);
  15276. }
  15277. if (this.onAfterRender) {
  15278. this.onAfterRender();
  15279. }
  15280. // Dump ?
  15281. if (dumpForDebug) {
  15282. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  15283. }
  15284. // Unbind
  15285. engine.unBindFramebuffer(this._texture);
  15286. if (this.onAfterUnbind) {
  15287. this.onAfterUnbind();
  15288. }
  15289. };
  15290. RenderTargetTexture.prototype.clone = function () {
  15291. var textureSize = this.getSize();
  15292. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15293. // Base texture
  15294. newTexture.hasAlpha = this.hasAlpha;
  15295. newTexture.level = this.level;
  15296. // RenderTarget Texture
  15297. newTexture.coordinatesMode = this.coordinatesMode;
  15298. newTexture.renderList = this.renderList.slice(0);
  15299. return newTexture;
  15300. };
  15301. return RenderTargetTexture;
  15302. })(BABYLON.Texture);
  15303. BABYLON.RenderTargetTexture = RenderTargetTexture;
  15304. })(BABYLON || (BABYLON = {}));
  15305. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  15306. var __extends = this.__extends || function (d, b) {
  15307. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15308. function __() { this.constructor = d; }
  15309. __.prototype = b.prototype;
  15310. d.prototype = new __();
  15311. };
  15312. var BABYLON;
  15313. (function (BABYLON) {
  15314. var ProceduralTexture = (function (_super) {
  15315. __extends(ProceduralTexture, _super);
  15316. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  15317. if (generateMipMaps === void 0) { generateMipMaps = true; }
  15318. _super.call(this, null, scene, !generateMipMaps);
  15319. this._currentRefreshId = -1;
  15320. this._refreshRate = 1;
  15321. this._vertexDeclaration = [2];
  15322. this._vertexStrideSize = 2 * 4;
  15323. this._uniforms = new Array();
  15324. this._samplers = new Array();
  15325. this._textures = new Array();
  15326. this._floats = new Array();
  15327. this._floatsArrays = {};
  15328. this._colors3 = new Array();
  15329. this._colors4 = new Array();
  15330. this._vectors2 = new Array();
  15331. this._vectors3 = new Array();
  15332. this._matrices = new Array();
  15333. this._fallbackTextureUsed = false;
  15334. scene._proceduralTextures.push(this);
  15335. this.name = name;
  15336. this.isRenderTarget = true;
  15337. this._size = size;
  15338. this._generateMipMaps = generateMipMaps;
  15339. this.setFragment(fragment);
  15340. this._fallbackTexture = fallbackTexture;
  15341. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  15342. // VBO
  15343. var vertices = [];
  15344. vertices.push(1, 1);
  15345. vertices.push(-1, 1);
  15346. vertices.push(-1, -1);
  15347. vertices.push(1, -1);
  15348. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15349. // Indices
  15350. var indices = [];
  15351. indices.push(0);
  15352. indices.push(1);
  15353. indices.push(2);
  15354. indices.push(0);
  15355. indices.push(2);
  15356. indices.push(3);
  15357. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15358. }
  15359. ProceduralTexture.prototype.reset = function () {
  15360. if (this._effect === undefined) {
  15361. return;
  15362. }
  15363. var engine = this.getScene().getEngine();
  15364. engine._releaseEffect(this._effect);
  15365. };
  15366. ProceduralTexture.prototype.isReady = function () {
  15367. var _this = this;
  15368. var engine = this.getScene().getEngine();
  15369. var shaders;
  15370. if (!this._fragment) {
  15371. return false;
  15372. }
  15373. if (this._fallbackTextureUsed) {
  15374. return true;
  15375. }
  15376. if (this._fragment.fragmentElement !== undefined) {
  15377. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  15378. }
  15379. else {
  15380. shaders = { vertex: "procedural", fragment: this._fragment };
  15381. }
  15382. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  15383. _this.releaseInternalTexture();
  15384. if (_this._fallbackTexture) {
  15385. _this._texture = _this._fallbackTexture._texture;
  15386. _this._texture.references++;
  15387. }
  15388. _this._fallbackTextureUsed = true;
  15389. });
  15390. return this._effect.isReady();
  15391. };
  15392. ProceduralTexture.prototype.resetRefreshCounter = function () {
  15393. this._currentRefreshId = -1;
  15394. };
  15395. ProceduralTexture.prototype.setFragment = function (fragment) {
  15396. this._fragment = fragment;
  15397. };
  15398. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  15399. get: function () {
  15400. return this._refreshRate;
  15401. },
  15402. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15403. set: function (value) {
  15404. this._refreshRate = value;
  15405. this.resetRefreshCounter();
  15406. },
  15407. enumerable: true,
  15408. configurable: true
  15409. });
  15410. ProceduralTexture.prototype._shouldRender = function () {
  15411. if (!this.isReady() || !this._texture) {
  15412. return false;
  15413. }
  15414. if (this._fallbackTextureUsed) {
  15415. return false;
  15416. }
  15417. if (this._currentRefreshId === -1) {
  15418. this._currentRefreshId = 1;
  15419. return true;
  15420. }
  15421. if (this.refreshRate === this._currentRefreshId) {
  15422. this._currentRefreshId = 1;
  15423. return true;
  15424. }
  15425. this._currentRefreshId++;
  15426. return false;
  15427. };
  15428. ProceduralTexture.prototype.getRenderSize = function () {
  15429. return this._size;
  15430. };
  15431. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  15432. if (this._fallbackTextureUsed) {
  15433. return;
  15434. }
  15435. this.releaseInternalTexture();
  15436. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15437. };
  15438. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  15439. if (this._uniforms.indexOf(uniformName) === -1) {
  15440. this._uniforms.push(uniformName);
  15441. }
  15442. };
  15443. ProceduralTexture.prototype.setTexture = function (name, texture) {
  15444. if (this._samplers.indexOf(name) === -1) {
  15445. this._samplers.push(name);
  15446. }
  15447. this._textures[name] = texture;
  15448. return this;
  15449. };
  15450. ProceduralTexture.prototype.setFloat = function (name, value) {
  15451. this._checkUniform(name);
  15452. this._floats[name] = value;
  15453. return this;
  15454. };
  15455. ProceduralTexture.prototype.setFloats = function (name, value) {
  15456. this._checkUniform(name);
  15457. this._floatsArrays[name] = value;
  15458. return this;
  15459. };
  15460. ProceduralTexture.prototype.setColor3 = function (name, value) {
  15461. this._checkUniform(name);
  15462. this._colors3[name] = value;
  15463. return this;
  15464. };
  15465. ProceduralTexture.prototype.setColor4 = function (name, value) {
  15466. this._checkUniform(name);
  15467. this._colors4[name] = value;
  15468. return this;
  15469. };
  15470. ProceduralTexture.prototype.setVector2 = function (name, value) {
  15471. this._checkUniform(name);
  15472. this._vectors2[name] = value;
  15473. return this;
  15474. };
  15475. ProceduralTexture.prototype.setVector3 = function (name, value) {
  15476. this._checkUniform(name);
  15477. this._vectors3[name] = value;
  15478. return this;
  15479. };
  15480. ProceduralTexture.prototype.setMatrix = function (name, value) {
  15481. this._checkUniform(name);
  15482. this._matrices[name] = value;
  15483. return this;
  15484. };
  15485. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15486. var scene = this.getScene();
  15487. var engine = scene.getEngine();
  15488. engine.bindFramebuffer(this._texture);
  15489. // Clear
  15490. engine.clear(scene.clearColor, true, true);
  15491. // Render
  15492. engine.enableEffect(this._effect);
  15493. engine.setState(false);
  15494. for (var name in this._textures) {
  15495. this._effect.setTexture(name, this._textures[name]);
  15496. }
  15497. for (name in this._floats) {
  15498. this._effect.setFloat(name, this._floats[name]);
  15499. }
  15500. for (name in this._floatsArrays) {
  15501. this._effect.setArray(name, this._floatsArrays[name]);
  15502. }
  15503. for (name in this._colors3) {
  15504. this._effect.setColor3(name, this._colors3[name]);
  15505. }
  15506. for (name in this._colors4) {
  15507. var color = this._colors4[name];
  15508. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15509. }
  15510. for (name in this._vectors2) {
  15511. this._effect.setVector2(name, this._vectors2[name]);
  15512. }
  15513. for (name in this._vectors3) {
  15514. this._effect.setVector3(name, this._vectors3[name]);
  15515. }
  15516. for (name in this._matrices) {
  15517. this._effect.setMatrix(name, this._matrices[name]);
  15518. }
  15519. // VBOs
  15520. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15521. // Draw order
  15522. engine.draw(true, 0, 6);
  15523. // Unbind
  15524. engine.unBindFramebuffer(this._texture);
  15525. };
  15526. ProceduralTexture.prototype.clone = function () {
  15527. var textureSize = this.getSize();
  15528. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  15529. // Base texture
  15530. newTexture.hasAlpha = this.hasAlpha;
  15531. newTexture.level = this.level;
  15532. // RenderTarget Texture
  15533. newTexture.coordinatesMode = this.coordinatesMode;
  15534. return newTexture;
  15535. };
  15536. ProceduralTexture.prototype.dispose = function () {
  15537. var index = this.getScene()._proceduralTextures.indexOf(this);
  15538. if (index >= 0) {
  15539. this.getScene()._proceduralTextures.splice(index, 1);
  15540. }
  15541. _super.prototype.dispose.call(this);
  15542. };
  15543. return ProceduralTexture;
  15544. })(BABYLON.Texture);
  15545. BABYLON.ProceduralTexture = ProceduralTexture;
  15546. })(BABYLON || (BABYLON = {}));
  15547. //# sourceMappingURL=babylon.proceduralTexture.js.map
  15548. var __extends = this.__extends || function (d, b) {
  15549. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15550. function __() { this.constructor = d; }
  15551. __.prototype = b.prototype;
  15552. d.prototype = new __();
  15553. };
  15554. var BABYLON;
  15555. (function (BABYLON) {
  15556. var MirrorTexture = (function (_super) {
  15557. __extends(MirrorTexture, _super);
  15558. function MirrorTexture(name, size, scene, generateMipMaps) {
  15559. var _this = this;
  15560. _super.call(this, name, size, scene, generateMipMaps, true);
  15561. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  15562. this._transformMatrix = BABYLON.Matrix.Zero();
  15563. this._mirrorMatrix = BABYLON.Matrix.Zero();
  15564. this.onBeforeRender = function () {
  15565. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  15566. _this._savedViewMatrix = scene.getViewMatrix();
  15567. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  15568. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  15569. scene.clipPlane = _this.mirrorPlane;
  15570. scene.getEngine().cullBackFaces = false;
  15571. };
  15572. this.onAfterRender = function () {
  15573. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  15574. scene.getEngine().cullBackFaces = true;
  15575. delete scene.clipPlane;
  15576. };
  15577. }
  15578. MirrorTexture.prototype.clone = function () {
  15579. var textureSize = this.getSize();
  15580. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15581. // Base texture
  15582. newTexture.hasAlpha = this.hasAlpha;
  15583. newTexture.level = this.level;
  15584. // Mirror Texture
  15585. newTexture.mirrorPlane = this.mirrorPlane.clone();
  15586. newTexture.renderList = this.renderList.slice(0);
  15587. return newTexture;
  15588. };
  15589. return MirrorTexture;
  15590. })(BABYLON.RenderTargetTexture);
  15591. BABYLON.MirrorTexture = MirrorTexture;
  15592. })(BABYLON || (BABYLON = {}));
  15593. //# sourceMappingURL=babylon.mirrorTexture.js.map
  15594. var __extends = this.__extends || function (d, b) {
  15595. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15596. function __() { this.constructor = d; }
  15597. __.prototype = b.prototype;
  15598. d.prototype = new __();
  15599. };
  15600. var BABYLON;
  15601. (function (BABYLON) {
  15602. var DynamicTexture = (function (_super) {
  15603. __extends(DynamicTexture, _super);
  15604. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  15605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15606. _super.call(this, null, scene, !generateMipMaps);
  15607. this.name = name;
  15608. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15609. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15610. this._generateMipMaps = generateMipMaps;
  15611. if (options.getContext) {
  15612. this._canvas = options;
  15613. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15614. }
  15615. else {
  15616. this._canvas = document.createElement("canvas");
  15617. if (options.width) {
  15618. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15619. }
  15620. else {
  15621. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  15622. }
  15623. }
  15624. var textureSize = this.getSize();
  15625. this._canvas.width = textureSize.width;
  15626. this._canvas.height = textureSize.height;
  15627. this._context = this._canvas.getContext("2d");
  15628. }
  15629. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  15630. get: function () {
  15631. return true;
  15632. },
  15633. enumerable: true,
  15634. configurable: true
  15635. });
  15636. DynamicTexture.prototype.scale = function (ratio) {
  15637. var textureSize = this.getSize();
  15638. textureSize.width *= ratio;
  15639. textureSize.height *= ratio;
  15640. this._canvas.width = textureSize.width;
  15641. this._canvas.height = textureSize.height;
  15642. this.releaseInternalTexture();
  15643. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  15644. };
  15645. DynamicTexture.prototype.getContext = function () {
  15646. return this._context;
  15647. };
  15648. DynamicTexture.prototype.clear = function () {
  15649. var size = this.getSize();
  15650. this._context.fillRect(0, 0, size.width, size.height);
  15651. };
  15652. DynamicTexture.prototype.update = function (invertY) {
  15653. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  15654. };
  15655. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  15656. if (update === void 0) { update = true; }
  15657. var size = this.getSize();
  15658. if (clearColor) {
  15659. this._context.fillStyle = clearColor;
  15660. this._context.fillRect(0, 0, size.width, size.height);
  15661. }
  15662. this._context.font = font;
  15663. if (x === null) {
  15664. var textSize = this._context.measureText(text);
  15665. x = (size.width - textSize.width) / 2;
  15666. }
  15667. this._context.fillStyle = color;
  15668. this._context.fillText(text, x, y);
  15669. if (update) {
  15670. this.update(invertY);
  15671. }
  15672. };
  15673. DynamicTexture.prototype.clone = function () {
  15674. var textureSize = this.getSize();
  15675. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15676. // Base texture
  15677. newTexture.hasAlpha = this.hasAlpha;
  15678. newTexture.level = this.level;
  15679. // Dynamic Texture
  15680. newTexture.wrapU = this.wrapU;
  15681. newTexture.wrapV = this.wrapV;
  15682. return newTexture;
  15683. };
  15684. return DynamicTexture;
  15685. })(BABYLON.Texture);
  15686. BABYLON.DynamicTexture = DynamicTexture;
  15687. })(BABYLON || (BABYLON = {}));
  15688. //# sourceMappingURL=babylon.dynamicTexture.js.map
  15689. var __extends = this.__extends || function (d, b) {
  15690. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15691. function __() { this.constructor = d; }
  15692. __.prototype = b.prototype;
  15693. d.prototype = new __();
  15694. };
  15695. var BABYLON;
  15696. (function (BABYLON) {
  15697. var VideoTexture = (function (_super) {
  15698. __extends(VideoTexture, _super);
  15699. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  15700. var _this = this;
  15701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15702. _super.call(this, null, scene, !generateMipMaps, invertY);
  15703. this._autoLaunch = true;
  15704. this.name = name;
  15705. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15706. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15707. var requiredWidth = size.width || size;
  15708. var requiredHeight = size.height || size;
  15709. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  15710. var textureSize = this.getSize();
  15711. this.video = document.createElement("video");
  15712. this.video.width = textureSize.width;
  15713. this.video.height = textureSize.height;
  15714. this.video.autoplay = false;
  15715. this.video.loop = true;
  15716. this.video.addEventListener("canplaythrough", function () {
  15717. if (_this._texture) {
  15718. _this._texture.isReady = true;
  15719. }
  15720. });
  15721. urls.forEach(function (url) {
  15722. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  15723. var source = document.createElement("source");
  15724. source.src = url;
  15725. _this.video.appendChild(source);
  15726. });
  15727. this._lastUpdate = BABYLON.Tools.Now;
  15728. }
  15729. VideoTexture.prototype.update = function () {
  15730. if (this._autoLaunch) {
  15731. this._autoLaunch = false;
  15732. this.video.play();
  15733. }
  15734. var now = BABYLON.Tools.Now;
  15735. if (now - this._lastUpdate < 15) {
  15736. return false;
  15737. }
  15738. this._lastUpdate = now;
  15739. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  15740. return true;
  15741. };
  15742. return VideoTexture;
  15743. })(BABYLON.Texture);
  15744. BABYLON.VideoTexture = VideoTexture;
  15745. })(BABYLON || (BABYLON = {}));
  15746. //# sourceMappingURL=babylon.videoTexture.js.map
  15747. var __extends = this.__extends || function (d, b) {
  15748. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15749. function __() { this.constructor = d; }
  15750. __.prototype = b.prototype;
  15751. d.prototype = new __();
  15752. };
  15753. var BABYLON;
  15754. (function (BABYLON) {
  15755. var CustomProceduralTexture = (function (_super) {
  15756. __extends(CustomProceduralTexture, _super);
  15757. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  15758. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  15759. this._animate = true;
  15760. this._time = 0;
  15761. this._texturePath = texturePath;
  15762. //Try to load json
  15763. this.loadJson(texturePath);
  15764. this.refreshRate = 1;
  15765. }
  15766. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  15767. var _this = this;
  15768. var that = this;
  15769. function noConfigFile() {
  15770. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  15771. try {
  15772. that.setFragment(that._texturePath);
  15773. }
  15774. catch (ex) {
  15775. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  15776. }
  15777. }
  15778. var configFileUrl = jsonUrl + "/config.json";
  15779. var xhr = new XMLHttpRequest();
  15780. xhr.open("GET", configFileUrl, true);
  15781. xhr.addEventListener("load", function () {
  15782. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15783. try {
  15784. _this._config = JSON.parse(xhr.response);
  15785. _this.updateShaderUniforms();
  15786. _this.updateTextures();
  15787. _this.setFragment(_this._texturePath + "/custom");
  15788. _this._animate = _this._config.animate;
  15789. _this.refreshRate = _this._config.refreshrate;
  15790. }
  15791. catch (ex) {
  15792. noConfigFile();
  15793. }
  15794. }
  15795. else {
  15796. noConfigFile();
  15797. }
  15798. }, false);
  15799. xhr.addEventListener("error", function () {
  15800. noConfigFile();
  15801. }, false);
  15802. try {
  15803. xhr.send();
  15804. }
  15805. catch (ex) {
  15806. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  15807. }
  15808. };
  15809. CustomProceduralTexture.prototype.isReady = function () {
  15810. if (!_super.prototype.isReady.call(this)) {
  15811. return false;
  15812. }
  15813. for (var name in this._textures) {
  15814. var texture = this._textures[name];
  15815. if (!texture.isReady()) {
  15816. return false;
  15817. }
  15818. }
  15819. return true;
  15820. };
  15821. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15822. if (this._animate) {
  15823. this._time += this.getScene().getAnimationRatio() * 0.03;
  15824. this.updateShaderUniforms();
  15825. }
  15826. _super.prototype.render.call(this, useCameraPostProcess);
  15827. };
  15828. CustomProceduralTexture.prototype.updateTextures = function () {
  15829. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  15830. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  15831. }
  15832. };
  15833. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  15834. if (this._config) {
  15835. for (var j = 0; j < this._config.uniforms.length; j++) {
  15836. var uniform = this._config.uniforms[j];
  15837. switch (uniform.type) {
  15838. case "float":
  15839. this.setFloat(uniform.name, uniform.value);
  15840. break;
  15841. case "color3":
  15842. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  15843. break;
  15844. case "color4":
  15845. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  15846. break;
  15847. case "vector2":
  15848. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  15849. break;
  15850. case "vector3":
  15851. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  15852. break;
  15853. }
  15854. }
  15855. }
  15856. this.setFloat("time", this._time);
  15857. };
  15858. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  15859. get: function () {
  15860. return this._animate;
  15861. },
  15862. set: function (value) {
  15863. this._animate = value;
  15864. },
  15865. enumerable: true,
  15866. configurable: true
  15867. });
  15868. return CustomProceduralTexture;
  15869. })(BABYLON.ProceduralTexture);
  15870. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  15871. })(BABYLON || (BABYLON = {}));
  15872. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  15873. var __extends = this.__extends || function (d, b) {
  15874. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15875. function __() { this.constructor = d; }
  15876. __.prototype = b.prototype;
  15877. d.prototype = new __();
  15878. };
  15879. var BABYLON;
  15880. (function (BABYLON) {
  15881. var WoodProceduralTexture = (function (_super) {
  15882. __extends(WoodProceduralTexture, _super);
  15883. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  15884. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  15885. this._ampScale = 100.0;
  15886. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  15887. this.updateShaderUniforms();
  15888. this.refreshRate = 0;
  15889. }
  15890. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  15891. this.setFloat("ampScale", this._ampScale);
  15892. this.setColor3("woodColor", this._woodColor);
  15893. };
  15894. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  15895. get: function () {
  15896. return this._ampScale;
  15897. },
  15898. set: function (value) {
  15899. this._ampScale = value;
  15900. this.updateShaderUniforms();
  15901. },
  15902. enumerable: true,
  15903. configurable: true
  15904. });
  15905. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  15906. get: function () {
  15907. return this._woodColor;
  15908. },
  15909. set: function (value) {
  15910. this._woodColor = value;
  15911. this.updateShaderUniforms();
  15912. },
  15913. enumerable: true,
  15914. configurable: true
  15915. });
  15916. return WoodProceduralTexture;
  15917. })(BABYLON.ProceduralTexture);
  15918. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  15919. var FireProceduralTexture = (function (_super) {
  15920. __extends(FireProceduralTexture, _super);
  15921. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  15922. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  15923. this._time = 0.0;
  15924. this._speed = new BABYLON.Vector2(0.5, 0.3);
  15925. this._autoGenerateTime = true;
  15926. this._alphaThreshold = 0.5;
  15927. this._fireColors = FireProceduralTexture.RedFireColors;
  15928. this.updateShaderUniforms();
  15929. this.refreshRate = 1;
  15930. }
  15931. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  15932. this.setFloat("time", this._time);
  15933. this.setVector2("speed", this._speed);
  15934. this.setColor3("c1", this._fireColors[0]);
  15935. this.setColor3("c2", this._fireColors[1]);
  15936. this.setColor3("c3", this._fireColors[2]);
  15937. this.setColor3("c4", this._fireColors[3]);
  15938. this.setColor3("c5", this._fireColors[4]);
  15939. this.setColor3("c6", this._fireColors[5]);
  15940. this.setFloat("alphaThreshold", this._alphaThreshold);
  15941. };
  15942. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15943. if (this._autoGenerateTime) {
  15944. this._time += this.getScene().getAnimationRatio() * 0.03;
  15945. this.updateShaderUniforms();
  15946. }
  15947. _super.prototype.render.call(this, useCameraPostProcess);
  15948. };
  15949. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  15950. get: function () {
  15951. return [
  15952. new BABYLON.Color3(0.5, 0.0, 1.0),
  15953. new BABYLON.Color3(0.9, 0.0, 1.0),
  15954. new BABYLON.Color3(0.2, 0.0, 1.0),
  15955. new BABYLON.Color3(1.0, 0.9, 1.0),
  15956. new BABYLON.Color3(0.1, 0.1, 1.0),
  15957. new BABYLON.Color3(0.9, 0.9, 1.0)
  15958. ];
  15959. },
  15960. enumerable: true,
  15961. configurable: true
  15962. });
  15963. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  15964. get: function () {
  15965. return [
  15966. new BABYLON.Color3(0.5, 1.0, 0.0),
  15967. new BABYLON.Color3(0.5, 1.0, 0.0),
  15968. new BABYLON.Color3(0.3, 0.4, 0.0),
  15969. new BABYLON.Color3(0.5, 1.0, 0.0),
  15970. new BABYLON.Color3(0.2, 0.0, 0.0),
  15971. new BABYLON.Color3(0.5, 1.0, 0.0)
  15972. ];
  15973. },
  15974. enumerable: true,
  15975. configurable: true
  15976. });
  15977. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  15978. get: function () {
  15979. return [
  15980. new BABYLON.Color3(0.5, 0.0, 0.1),
  15981. new BABYLON.Color3(0.9, 0.0, 0.0),
  15982. new BABYLON.Color3(0.2, 0.0, 0.0),
  15983. new BABYLON.Color3(1.0, 0.9, 0.0),
  15984. new BABYLON.Color3(0.1, 0.1, 0.1),
  15985. new BABYLON.Color3(0.9, 0.9, 0.9)
  15986. ];
  15987. },
  15988. enumerable: true,
  15989. configurable: true
  15990. });
  15991. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  15992. get: function () {
  15993. return [
  15994. new BABYLON.Color3(0.1, 0.0, 0.5),
  15995. new BABYLON.Color3(0.0, 0.0, 0.5),
  15996. new BABYLON.Color3(0.1, 0.0, 0.2),
  15997. new BABYLON.Color3(0.0, 0.0, 1.0),
  15998. new BABYLON.Color3(0.1, 0.2, 0.3),
  15999. new BABYLON.Color3(0.0, 0.2, 0.9)
  16000. ];
  16001. },
  16002. enumerable: true,
  16003. configurable: true
  16004. });
  16005. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  16006. get: function () {
  16007. return this._fireColors;
  16008. },
  16009. set: function (value) {
  16010. this._fireColors = value;
  16011. this.updateShaderUniforms();
  16012. },
  16013. enumerable: true,
  16014. configurable: true
  16015. });
  16016. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  16017. get: function () {
  16018. return this._time;
  16019. },
  16020. set: function (value) {
  16021. this._time = value;
  16022. this.updateShaderUniforms();
  16023. },
  16024. enumerable: true,
  16025. configurable: true
  16026. });
  16027. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  16028. get: function () {
  16029. return this._speed;
  16030. },
  16031. set: function (value) {
  16032. this._speed = value;
  16033. this.updateShaderUniforms();
  16034. },
  16035. enumerable: true,
  16036. configurable: true
  16037. });
  16038. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  16039. get: function () {
  16040. return this._alphaThreshold;
  16041. },
  16042. set: function (value) {
  16043. this._alphaThreshold = value;
  16044. this.updateShaderUniforms();
  16045. },
  16046. enumerable: true,
  16047. configurable: true
  16048. });
  16049. return FireProceduralTexture;
  16050. })(BABYLON.ProceduralTexture);
  16051. BABYLON.FireProceduralTexture = FireProceduralTexture;
  16052. var CloudProceduralTexture = (function (_super) {
  16053. __extends(CloudProceduralTexture, _super);
  16054. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16055. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  16056. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  16057. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  16058. this.updateShaderUniforms();
  16059. this.refreshRate = 0;
  16060. }
  16061. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  16062. this.setColor3("skyColor", this._skyColor);
  16063. this.setColor3("cloudColor", this._cloudColor);
  16064. };
  16065. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  16066. get: function () {
  16067. return this._skyColor;
  16068. },
  16069. set: function (value) {
  16070. this._skyColor = value;
  16071. this.updateShaderUniforms();
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  16077. get: function () {
  16078. return this._cloudColor;
  16079. },
  16080. set: function (value) {
  16081. this._cloudColor = value;
  16082. this.updateShaderUniforms();
  16083. },
  16084. enumerable: true,
  16085. configurable: true
  16086. });
  16087. return CloudProceduralTexture;
  16088. })(BABYLON.ProceduralTexture);
  16089. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  16090. var GrassProceduralTexture = (function (_super) {
  16091. __extends(GrassProceduralTexture, _super);
  16092. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16093. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  16094. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  16095. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  16096. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  16097. this._groundColor = new BABYLON.Color3(1, 1, 1);
  16098. this._grassColors = [
  16099. new BABYLON.Color3(0.29, 0.38, 0.02),
  16100. new BABYLON.Color3(0.36, 0.49, 0.09),
  16101. new BABYLON.Color3(0.51, 0.6, 0.28)
  16102. ];
  16103. this.updateShaderUniforms();
  16104. this.refreshRate = 0;
  16105. }
  16106. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  16107. this.setColor3("herb1Color", this._grassColors[0]);
  16108. this.setColor3("herb2Color", this._grassColors[1]);
  16109. this.setColor3("herb3Color", this._grassColors[2]);
  16110. this.setColor3("groundColor", this._groundColor);
  16111. };
  16112. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  16113. get: function () {
  16114. return this._grassColors;
  16115. },
  16116. set: function (value) {
  16117. this._grassColors = value;
  16118. this.updateShaderUniforms();
  16119. },
  16120. enumerable: true,
  16121. configurable: true
  16122. });
  16123. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  16124. get: function () {
  16125. return this._groundColor;
  16126. },
  16127. set: function (value) {
  16128. this.groundColor = value;
  16129. this.updateShaderUniforms();
  16130. },
  16131. enumerable: true,
  16132. configurable: true
  16133. });
  16134. return GrassProceduralTexture;
  16135. })(BABYLON.ProceduralTexture);
  16136. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  16137. var RoadProceduralTexture = (function (_super) {
  16138. __extends(RoadProceduralTexture, _super);
  16139. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16140. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  16141. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  16142. this.updateShaderUniforms();
  16143. this.refreshRate = 0;
  16144. }
  16145. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  16146. this.setColor3("roadColor", this._roadColor);
  16147. };
  16148. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  16149. get: function () {
  16150. return this._roadColor;
  16151. },
  16152. set: function (value) {
  16153. this._roadColor = value;
  16154. this.updateShaderUniforms();
  16155. },
  16156. enumerable: true,
  16157. configurable: true
  16158. });
  16159. return RoadProceduralTexture;
  16160. })(BABYLON.ProceduralTexture);
  16161. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  16162. var BrickProceduralTexture = (function (_super) {
  16163. __extends(BrickProceduralTexture, _super);
  16164. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16165. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  16166. this._numberOfBricksHeight = 15;
  16167. this._numberOfBricksWidth = 5;
  16168. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16169. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16170. this.updateShaderUniforms();
  16171. this.refreshRate = 0;
  16172. }
  16173. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  16174. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  16175. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  16176. this.setColor3("brickColor", this._brickColor);
  16177. this.setColor3("jointColor", this._jointColor);
  16178. };
  16179. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  16180. get: function () {
  16181. return this._numberOfBricksHeight;
  16182. },
  16183. set: function (value) {
  16184. this._numberOfBricksHeight = value;
  16185. this.updateShaderUniforms();
  16186. },
  16187. enumerable: true,
  16188. configurable: true
  16189. });
  16190. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  16191. get: function () {
  16192. return this._numberOfBricksWidth;
  16193. },
  16194. set: function (value) {
  16195. this._numberOfBricksHeight = value;
  16196. this.updateShaderUniforms();
  16197. },
  16198. enumerable: true,
  16199. configurable: true
  16200. });
  16201. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  16202. get: function () {
  16203. return this._jointColor;
  16204. },
  16205. set: function (value) {
  16206. this._jointColor = value;
  16207. this.updateShaderUniforms();
  16208. },
  16209. enumerable: true,
  16210. configurable: true
  16211. });
  16212. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  16213. get: function () {
  16214. return this._brickColor;
  16215. },
  16216. set: function (value) {
  16217. this._brickColor = value;
  16218. this.updateShaderUniforms();
  16219. },
  16220. enumerable: true,
  16221. configurable: true
  16222. });
  16223. return BrickProceduralTexture;
  16224. })(BABYLON.ProceduralTexture);
  16225. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  16226. var MarbleProceduralTexture = (function (_super) {
  16227. __extends(MarbleProceduralTexture, _super);
  16228. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16229. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  16230. this._numberOfTilesHeight = 3;
  16231. this._numberOfTilesWidth = 3;
  16232. this._amplitude = 9.0;
  16233. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16234. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16235. this.updateShaderUniforms();
  16236. this.refreshRate = 0;
  16237. }
  16238. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  16239. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  16240. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  16241. this.setFloat("amplitude", this._amplitude);
  16242. this.setColor3("marbleColor", this._marbleColor);
  16243. this.setColor3("jointColor", this._jointColor);
  16244. };
  16245. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  16246. get: function () {
  16247. return this._numberOfTilesHeight;
  16248. },
  16249. set: function (value) {
  16250. this._numberOfTilesHeight = value;
  16251. this.updateShaderUniforms();
  16252. },
  16253. enumerable: true,
  16254. configurable: true
  16255. });
  16256. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  16257. get: function () {
  16258. return this._numberOfTilesWidth;
  16259. },
  16260. set: function (value) {
  16261. this._numberOfTilesWidth = value;
  16262. this.updateShaderUniforms();
  16263. },
  16264. enumerable: true,
  16265. configurable: true
  16266. });
  16267. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  16268. get: function () {
  16269. return this._jointColor;
  16270. },
  16271. set: function (value) {
  16272. this._jointColor = value;
  16273. this.updateShaderUniforms();
  16274. },
  16275. enumerable: true,
  16276. configurable: true
  16277. });
  16278. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  16279. get: function () {
  16280. return this._marbleColor;
  16281. },
  16282. set: function (value) {
  16283. this._marbleColor = value;
  16284. this.updateShaderUniforms();
  16285. },
  16286. enumerable: true,
  16287. configurable: true
  16288. });
  16289. return MarbleProceduralTexture;
  16290. })(BABYLON.ProceduralTexture);
  16291. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  16292. })(BABYLON || (BABYLON = {}));
  16293. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  16294. var BABYLON;
  16295. (function (BABYLON) {
  16296. var EffectFallbacks = (function () {
  16297. function EffectFallbacks() {
  16298. this._defines = {};
  16299. this._currentRank = 32;
  16300. this._maxRank = -1;
  16301. }
  16302. EffectFallbacks.prototype.addFallback = function (rank, define) {
  16303. if (!this._defines[rank]) {
  16304. if (rank < this._currentRank) {
  16305. this._currentRank = rank;
  16306. }
  16307. if (rank > this._maxRank) {
  16308. this._maxRank = rank;
  16309. }
  16310. this._defines[rank] = new Array();
  16311. }
  16312. this._defines[rank].push(define);
  16313. };
  16314. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  16315. get: function () {
  16316. return this._currentRank <= this._maxRank;
  16317. },
  16318. enumerable: true,
  16319. configurable: true
  16320. });
  16321. EffectFallbacks.prototype.reduce = function (currentDefines) {
  16322. var currentFallbacks = this._defines[this._currentRank];
  16323. for (var index = 0; index < currentFallbacks.length; index++) {
  16324. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  16325. }
  16326. this._currentRank++;
  16327. return currentDefines;
  16328. };
  16329. return EffectFallbacks;
  16330. })();
  16331. BABYLON.EffectFallbacks = EffectFallbacks;
  16332. var Effect = (function () {
  16333. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  16334. var _this = this;
  16335. this._isReady = false;
  16336. this._compilationError = "";
  16337. this._valueCache = [];
  16338. this._engine = engine;
  16339. this.name = baseName;
  16340. this.defines = defines;
  16341. this._uniformsNames = uniformsNames.concat(samplers);
  16342. this._samplers = samplers;
  16343. this._attributesNames = attributesNames;
  16344. this.onError = onError;
  16345. this.onCompiled = onCompiled;
  16346. var vertexSource;
  16347. var fragmentSource;
  16348. if (baseName.vertexElement) {
  16349. vertexSource = document.getElementById(baseName.vertexElement);
  16350. if (!vertexSource) {
  16351. vertexSource = baseName.vertexElement;
  16352. }
  16353. }
  16354. else {
  16355. vertexSource = baseName.vertex || baseName;
  16356. }
  16357. if (baseName.fragmentElement) {
  16358. fragmentSource = document.getElementById(baseName.fragmentElement);
  16359. if (!fragmentSource) {
  16360. fragmentSource = baseName.fragmentElement;
  16361. }
  16362. }
  16363. else {
  16364. fragmentSource = baseName.fragment || baseName;
  16365. }
  16366. this._loadVertexShader(vertexSource, function (vertexCode) {
  16367. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  16368. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  16369. });
  16370. });
  16371. }
  16372. // Properties
  16373. Effect.prototype.isReady = function () {
  16374. return this._isReady;
  16375. };
  16376. Effect.prototype.getProgram = function () {
  16377. return this._program;
  16378. };
  16379. Effect.prototype.getAttributesNames = function () {
  16380. return this._attributesNames;
  16381. };
  16382. Effect.prototype.getAttributeLocation = function (index) {
  16383. return this._attributes[index];
  16384. };
  16385. Effect.prototype.getAttributeLocationByName = function (name) {
  16386. var index = this._attributesNames.indexOf(name);
  16387. return this._attributes[index];
  16388. };
  16389. Effect.prototype.getAttributesCount = function () {
  16390. return this._attributes.length;
  16391. };
  16392. Effect.prototype.getUniformIndex = function (uniformName) {
  16393. return this._uniformsNames.indexOf(uniformName);
  16394. };
  16395. Effect.prototype.getUniform = function (uniformName) {
  16396. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  16397. };
  16398. Effect.prototype.getSamplers = function () {
  16399. return this._samplers;
  16400. };
  16401. Effect.prototype.getCompilationError = function () {
  16402. return this._compilationError;
  16403. };
  16404. // Methods
  16405. Effect.prototype._loadVertexShader = function (vertex, callback) {
  16406. // DOM element ?
  16407. if (vertex instanceof HTMLElement) {
  16408. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  16409. callback(vertexCode);
  16410. return;
  16411. }
  16412. // Is in local store ?
  16413. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  16414. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  16415. return;
  16416. }
  16417. var vertexShaderUrl;
  16418. if (vertex[0] === ".") {
  16419. vertexShaderUrl = vertex;
  16420. }
  16421. else {
  16422. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  16423. }
  16424. // Vertex shader
  16425. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  16426. };
  16427. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  16428. // DOM element ?
  16429. if (fragment instanceof HTMLElement) {
  16430. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  16431. callback(fragmentCode);
  16432. return;
  16433. }
  16434. // Is in local store ?
  16435. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  16436. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  16437. return;
  16438. }
  16439. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  16440. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  16441. return;
  16442. }
  16443. var fragmentShaderUrl;
  16444. if (fragment[0] === ".") {
  16445. fragmentShaderUrl = fragment;
  16446. }
  16447. else {
  16448. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  16449. }
  16450. // Fragment shader
  16451. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  16452. };
  16453. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  16454. try {
  16455. var engine = this._engine;
  16456. if (!engine.getCaps().highPrecisionShaderSupported) {
  16457. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16458. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16459. }
  16460. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  16461. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  16462. this._attributes = engine.getAttributes(this._program, attributesNames);
  16463. for (var index = 0; index < this._samplers.length; index++) {
  16464. var sampler = this.getUniform(this._samplers[index]);
  16465. if (sampler == null) {
  16466. this._samplers.splice(index, 1);
  16467. index--;
  16468. }
  16469. }
  16470. engine.bindSamplers(this);
  16471. this._isReady = true;
  16472. if (this.onCompiled) {
  16473. this.onCompiled(this);
  16474. }
  16475. }
  16476. catch (e) {
  16477. // Is it a problem with precision?
  16478. if (e.message.indexOf("highp") !== -1) {
  16479. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16480. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16481. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16482. return;
  16483. }
  16484. // Let's go through fallbacks then
  16485. if (fallbacks && fallbacks.isMoreFallbacks) {
  16486. defines = fallbacks.reduce(defines);
  16487. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16488. }
  16489. else {
  16490. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  16491. BABYLON.Tools.Error("Defines: " + defines);
  16492. BABYLON.Tools.Error("Error: " + e.message);
  16493. this._compilationError = e.message;
  16494. if (this.onError) {
  16495. this.onError(this, this._compilationError);
  16496. }
  16497. }
  16498. }
  16499. };
  16500. Effect.prototype._bindTexture = function (channel, texture) {
  16501. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  16502. };
  16503. Effect.prototype.setTexture = function (channel, texture) {
  16504. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  16505. };
  16506. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16507. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  16508. };
  16509. //public _cacheMatrix(uniformName, matrix) {
  16510. // if (!this._valueCache[uniformName]) {
  16511. // this._valueCache[uniformName] = new BABYLON.Matrix();
  16512. // }
  16513. // for (var index = 0; index < 16; index++) {
  16514. // this._valueCache[uniformName].m[index] = matrix.m[index];
  16515. // }
  16516. //};
  16517. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  16518. if (!this._valueCache[uniformName]) {
  16519. this._valueCache[uniformName] = [x, y];
  16520. return;
  16521. }
  16522. this._valueCache[uniformName][0] = x;
  16523. this._valueCache[uniformName][1] = y;
  16524. };
  16525. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  16526. if (!this._valueCache[uniformName]) {
  16527. this._valueCache[uniformName] = [x, y, z];
  16528. return;
  16529. }
  16530. this._valueCache[uniformName][0] = x;
  16531. this._valueCache[uniformName][1] = y;
  16532. this._valueCache[uniformName][2] = z;
  16533. };
  16534. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  16535. if (!this._valueCache[uniformName]) {
  16536. this._valueCache[uniformName] = [x, y, z, w];
  16537. return;
  16538. }
  16539. this._valueCache[uniformName][0] = x;
  16540. this._valueCache[uniformName][1] = y;
  16541. this._valueCache[uniformName][2] = z;
  16542. this._valueCache[uniformName][3] = w;
  16543. };
  16544. Effect.prototype.setArray = function (uniformName, array) {
  16545. this._engine.setArray(this.getUniform(uniformName), array);
  16546. return this;
  16547. };
  16548. Effect.prototype.setArray2 = function (uniformName, array) {
  16549. this._engine.setArray2(this.getUniform(uniformName), array);
  16550. return this;
  16551. };
  16552. Effect.prototype.setArray3 = function (uniformName, array) {
  16553. this._engine.setArray3(this.getUniform(uniformName), array);
  16554. return this;
  16555. };
  16556. Effect.prototype.setArray4 = function (uniformName, array) {
  16557. this._engine.setArray4(this.getUniform(uniformName), array);
  16558. return this;
  16559. };
  16560. Effect.prototype.setMatrices = function (uniformName, matrices) {
  16561. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  16562. return this;
  16563. };
  16564. Effect.prototype.setMatrix = function (uniformName, matrix) {
  16565. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  16566. // return;
  16567. //this._cacheMatrix(uniformName, matrix);
  16568. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  16569. return this;
  16570. };
  16571. Effect.prototype.setFloat = function (uniformName, value) {
  16572. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  16573. return this;
  16574. this._valueCache[uniformName] = value;
  16575. this._engine.setFloat(this.getUniform(uniformName), value);
  16576. return this;
  16577. };
  16578. Effect.prototype.setBool = function (uniformName, bool) {
  16579. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  16580. return this;
  16581. this._valueCache[uniformName] = bool;
  16582. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  16583. return this;
  16584. };
  16585. Effect.prototype.setVector2 = function (uniformName, vector2) {
  16586. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  16587. return this;
  16588. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  16589. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  16590. return this;
  16591. };
  16592. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  16593. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  16594. return this;
  16595. this._cacheFloat2(uniformName, x, y);
  16596. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  16597. return this;
  16598. };
  16599. Effect.prototype.setVector3 = function (uniformName, vector3) {
  16600. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  16601. return this;
  16602. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  16603. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  16604. return this;
  16605. };
  16606. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  16607. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  16608. return this;
  16609. this._cacheFloat3(uniformName, x, y, z);
  16610. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  16611. return this;
  16612. };
  16613. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  16614. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  16615. return this;
  16616. this._cacheFloat4(uniformName, x, y, z, w);
  16617. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  16618. return this;
  16619. };
  16620. Effect.prototype.setColor3 = function (uniformName, color3) {
  16621. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  16622. return this;
  16623. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  16624. this._engine.setColor3(this.getUniform(uniformName), color3);
  16625. return this;
  16626. };
  16627. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  16628. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
  16629. return this;
  16630. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  16631. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  16632. return this;
  16633. };
  16634. // Statics
  16635. Effect.ShadersStore = {};
  16636. return Effect;
  16637. })();
  16638. BABYLON.Effect = Effect;
  16639. })(BABYLON || (BABYLON = {}));
  16640. //# sourceMappingURL=babylon.effect.js.map
  16641. var BABYLON;
  16642. (function (BABYLON) {
  16643. var Material = (function () {
  16644. function Material(name, scene, doNotAdd) {
  16645. this.name = name;
  16646. this.checkReadyOnEveryCall = true;
  16647. this.checkReadyOnlyOnce = false;
  16648. this.state = "";
  16649. this.alpha = 1.0;
  16650. this.backFaceCulling = true;
  16651. this._wasPreviouslyReady = false;
  16652. this._fillMode = Material.TriangleFillMode;
  16653. this.pointSize = 1.0;
  16654. this.zOffset = 0;
  16655. this.id = name;
  16656. this._scene = scene;
  16657. if (!doNotAdd) {
  16658. scene.materials.push(this);
  16659. }
  16660. }
  16661. Object.defineProperty(Material, "TriangleFillMode", {
  16662. get: function () {
  16663. return Material._TriangleFillMode;
  16664. },
  16665. enumerable: true,
  16666. configurable: true
  16667. });
  16668. Object.defineProperty(Material, "WireFrameFillMode", {
  16669. get: function () {
  16670. return Material._WireFrameFillMode;
  16671. },
  16672. enumerable: true,
  16673. configurable: true
  16674. });
  16675. Object.defineProperty(Material, "PointFillMode", {
  16676. get: function () {
  16677. return Material._PointFillMode;
  16678. },
  16679. enumerable: true,
  16680. configurable: true
  16681. });
  16682. Object.defineProperty(Material.prototype, "wireframe", {
  16683. get: function () {
  16684. return this._fillMode === Material.WireFrameFillMode;
  16685. },
  16686. set: function (value) {
  16687. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  16688. },
  16689. enumerable: true,
  16690. configurable: true
  16691. });
  16692. Object.defineProperty(Material.prototype, "pointsCloud", {
  16693. get: function () {
  16694. return this._fillMode === Material.PointFillMode;
  16695. },
  16696. set: function (value) {
  16697. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  16698. },
  16699. enumerable: true,
  16700. configurable: true
  16701. });
  16702. Object.defineProperty(Material.prototype, "fillMode", {
  16703. get: function () {
  16704. return this._fillMode;
  16705. },
  16706. set: function (value) {
  16707. this._fillMode = value;
  16708. },
  16709. enumerable: true,
  16710. configurable: true
  16711. });
  16712. Material.prototype.isReady = function (mesh, useInstances) {
  16713. return true;
  16714. };
  16715. Material.prototype.getEffect = function () {
  16716. return this._effect;
  16717. };
  16718. Material.prototype.getScene = function () {
  16719. return this._scene;
  16720. };
  16721. Material.prototype.needAlphaBlending = function () {
  16722. return (this.alpha < 1.0);
  16723. };
  16724. Material.prototype.needAlphaTesting = function () {
  16725. return false;
  16726. };
  16727. Material.prototype.getAlphaTestTexture = function () {
  16728. return null;
  16729. };
  16730. Material.prototype.trackCreation = function (onCompiled, onError) {
  16731. };
  16732. Material.prototype._preBind = function () {
  16733. var engine = this._scene.getEngine();
  16734. engine.enableEffect(this._effect);
  16735. engine.setState(this.backFaceCulling, this.zOffset);
  16736. };
  16737. Material.prototype.bind = function (world, mesh) {
  16738. this._scene._cachedMaterial = this;
  16739. if (this.onBind) {
  16740. this.onBind(this, mesh);
  16741. }
  16742. };
  16743. Material.prototype.bindOnlyWorldMatrix = function (world) {
  16744. };
  16745. Material.prototype.unbind = function () {
  16746. };
  16747. Material.prototype.dispose = function (forceDisposeEffect) {
  16748. // Remove from scene
  16749. var index = this._scene.materials.indexOf(this);
  16750. this._scene.materials.splice(index, 1);
  16751. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  16752. if (forceDisposeEffect && this._effect) {
  16753. this._scene.getEngine()._releaseEffect(this._effect);
  16754. this._effect = null;
  16755. }
  16756. // Callback
  16757. if (this.onDispose) {
  16758. this.onDispose();
  16759. }
  16760. };
  16761. Material._TriangleFillMode = 0;
  16762. Material._WireFrameFillMode = 1;
  16763. Material._PointFillMode = 2;
  16764. return Material;
  16765. })();
  16766. BABYLON.Material = Material;
  16767. })(BABYLON || (BABYLON = {}));
  16768. //# sourceMappingURL=babylon.material.js.map
  16769. var __extends = this.__extends || function (d, b) {
  16770. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16771. function __() { this.constructor = d; }
  16772. __.prototype = b.prototype;
  16773. d.prototype = new __();
  16774. };
  16775. var BABYLON;
  16776. (function (BABYLON) {
  16777. var maxSimultaneousLights = 4;
  16778. var FresnelParameters = (function () {
  16779. function FresnelParameters() {
  16780. this.isEnabled = true;
  16781. this.leftColor = BABYLON.Color3.White();
  16782. this.rightColor = BABYLON.Color3.Black();
  16783. this.bias = 0;
  16784. this.power = 1;
  16785. }
  16786. return FresnelParameters;
  16787. })();
  16788. BABYLON.FresnelParameters = FresnelParameters;
  16789. var StandardMaterial = (function (_super) {
  16790. __extends(StandardMaterial, _super);
  16791. function StandardMaterial(name, scene) {
  16792. var _this = this;
  16793. _super.call(this, name, scene);
  16794. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16795. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  16796. this.specularColor = new BABYLON.Color3(1, 1, 1);
  16797. this.specularPower = 64;
  16798. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  16799. this.useAlphaFromDiffuseTexture = false;
  16800. this.useSpecularOverAlpha = true;
  16801. this.fogEnabled = true;
  16802. this._cachedDefines = null;
  16803. this._renderTargets = new BABYLON.SmartArray(16);
  16804. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  16805. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  16806. this._scaledDiffuse = new BABYLON.Color3();
  16807. this._scaledSpecular = new BABYLON.Color3();
  16808. this.getRenderTargetTextures = function () {
  16809. _this._renderTargets.reset();
  16810. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  16811. _this._renderTargets.push(_this.reflectionTexture);
  16812. }
  16813. return _this._renderTargets;
  16814. };
  16815. }
  16816. StandardMaterial.prototype.needAlphaBlending = function () {
  16817. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  16818. };
  16819. StandardMaterial.prototype.needAlphaTesting = function () {
  16820. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  16821. };
  16822. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  16823. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  16824. };
  16825. StandardMaterial.prototype.getAlphaTestTexture = function () {
  16826. return this.diffuseTexture;
  16827. };
  16828. // Methods
  16829. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  16830. if (this.checkReadyOnlyOnce) {
  16831. if (this._wasPreviouslyReady) {
  16832. return true;
  16833. }
  16834. }
  16835. var scene = this.getScene();
  16836. if (!this.checkReadyOnEveryCall) {
  16837. if (this._renderId === scene.getRenderId()) {
  16838. return true;
  16839. }
  16840. }
  16841. var engine = scene.getEngine();
  16842. var defines = [];
  16843. var fallbacks = new BABYLON.EffectFallbacks();
  16844. var needNormals = false;
  16845. var needUVs = false;
  16846. // Textures
  16847. if (scene.texturesEnabled) {
  16848. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  16849. if (!this.diffuseTexture.isReady()) {
  16850. return false;
  16851. }
  16852. else {
  16853. needUVs = true;
  16854. defines.push("#define DIFFUSE");
  16855. }
  16856. }
  16857. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  16858. if (!this.ambientTexture.isReady()) {
  16859. return false;
  16860. }
  16861. else {
  16862. needUVs = true;
  16863. defines.push("#define AMBIENT");
  16864. }
  16865. }
  16866. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  16867. if (!this.opacityTexture.isReady()) {
  16868. return false;
  16869. }
  16870. else {
  16871. needUVs = true;
  16872. defines.push("#define OPACITY");
  16873. if (this.opacityTexture.getAlphaFromRGB) {
  16874. defines.push("#define OPACITYRGB");
  16875. }
  16876. }
  16877. }
  16878. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  16879. if (!this.reflectionTexture.isReady()) {
  16880. return false;
  16881. }
  16882. else {
  16883. needNormals = true;
  16884. needUVs = true;
  16885. defines.push("#define REFLECTION");
  16886. fallbacks.addFallback(0, "REFLECTION");
  16887. }
  16888. }
  16889. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  16890. if (!this.emissiveTexture.isReady()) {
  16891. return false;
  16892. }
  16893. else {
  16894. needUVs = true;
  16895. defines.push("#define EMISSIVE");
  16896. }
  16897. }
  16898. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  16899. if (!this.specularTexture.isReady()) {
  16900. return false;
  16901. }
  16902. else {
  16903. needUVs = true;
  16904. defines.push("#define SPECULAR");
  16905. fallbacks.addFallback(0, "SPECULAR");
  16906. }
  16907. }
  16908. }
  16909. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  16910. if (!this.bumpTexture.isReady()) {
  16911. return false;
  16912. }
  16913. else {
  16914. needUVs = true;
  16915. defines.push("#define BUMP");
  16916. fallbacks.addFallback(0, "BUMP");
  16917. }
  16918. }
  16919. // Effect
  16920. if (this.useSpecularOverAlpha) {
  16921. defines.push("#define SPECULAROVERALPHA");
  16922. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  16923. }
  16924. if (scene.clipPlane) {
  16925. defines.push("#define CLIPPLANE");
  16926. }
  16927. if (engine.getAlphaTesting()) {
  16928. defines.push("#define ALPHATEST");
  16929. }
  16930. if (this._shouldUseAlphaFromDiffuseTexture()) {
  16931. defines.push("#define ALPHAFROMDIFFUSE");
  16932. }
  16933. // Point size
  16934. if (this.pointsCloud || scene.forcePointsCloud) {
  16935. defines.push("#define POINTSIZE");
  16936. }
  16937. // Fog
  16938. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16939. defines.push("#define FOG");
  16940. fallbacks.addFallback(1, "FOG");
  16941. }
  16942. var shadowsActivated = false;
  16943. var lightIndex = 0;
  16944. if (scene.lightsEnabled) {
  16945. for (var index = 0; index < scene.lights.length; index++) {
  16946. var light = scene.lights[index];
  16947. if (!light.isEnabled()) {
  16948. continue;
  16949. }
  16950. // Excluded check
  16951. if (light._excludedMeshesIds.length > 0) {
  16952. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  16953. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  16954. if (excludedMesh) {
  16955. light.excludedMeshes.push(excludedMesh);
  16956. }
  16957. }
  16958. light._excludedMeshesIds = [];
  16959. }
  16960. // Included check
  16961. if (light._includedOnlyMeshesIds.length > 0) {
  16962. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  16963. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  16964. if (includedOnlyMesh) {
  16965. light.includedOnlyMeshes.push(includedOnlyMesh);
  16966. }
  16967. }
  16968. light._includedOnlyMeshesIds = [];
  16969. }
  16970. if (!light.canAffectMesh(mesh)) {
  16971. continue;
  16972. }
  16973. needNormals = true;
  16974. defines.push("#define LIGHT" + lightIndex);
  16975. if (lightIndex > 0) {
  16976. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  16977. }
  16978. var type;
  16979. if (light instanceof BABYLON.SpotLight) {
  16980. type = "#define SPOTLIGHT" + lightIndex;
  16981. }
  16982. else if (light instanceof BABYLON.HemisphericLight) {
  16983. type = "#define HEMILIGHT" + lightIndex;
  16984. }
  16985. else {
  16986. type = "#define POINTDIRLIGHT" + lightIndex;
  16987. }
  16988. defines.push(type);
  16989. if (lightIndex > 0) {
  16990. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  16991. }
  16992. // Shadows
  16993. if (scene.shadowsEnabled) {
  16994. var shadowGenerator = light.getShadowGenerator();
  16995. if (mesh && mesh.receiveShadows && shadowGenerator) {
  16996. defines.push("#define SHADOW" + lightIndex);
  16997. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  16998. if (!shadowsActivated) {
  16999. defines.push("#define SHADOWS");
  17000. shadowsActivated = true;
  17001. }
  17002. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  17003. defines.push("#define SHADOWVSM" + lightIndex);
  17004. if (lightIndex > 0) {
  17005. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  17006. }
  17007. }
  17008. if (shadowGenerator.usePoissonSampling) {
  17009. defines.push("#define SHADOWPCF" + lightIndex);
  17010. if (lightIndex > 0) {
  17011. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  17012. }
  17013. }
  17014. }
  17015. }
  17016. lightIndex++;
  17017. if (lightIndex === maxSimultaneousLights)
  17018. break;
  17019. }
  17020. }
  17021. if (StandardMaterial.FresnelEnabled) {
  17022. // Fresnel
  17023. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17024. var fresnelRank = 1;
  17025. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17026. defines.push("#define DIFFUSEFRESNEL");
  17027. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  17028. fresnelRank++;
  17029. }
  17030. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17031. defines.push("#define OPACITYFRESNEL");
  17032. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  17033. fresnelRank++;
  17034. }
  17035. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17036. defines.push("#define REFLECTIONFRESNEL");
  17037. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  17038. fresnelRank++;
  17039. }
  17040. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17041. defines.push("#define EMISSIVEFRESNEL");
  17042. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  17043. fresnelRank++;
  17044. }
  17045. needNormals = true;
  17046. defines.push("#define FRESNEL");
  17047. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  17048. }
  17049. }
  17050. // Attribs
  17051. var attribs = [BABYLON.VertexBuffer.PositionKind];
  17052. if (mesh) {
  17053. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17054. attribs.push(BABYLON.VertexBuffer.NormalKind);
  17055. defines.push("#define NORMAL");
  17056. }
  17057. if (needUVs) {
  17058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17059. attribs.push(BABYLON.VertexBuffer.UVKind);
  17060. defines.push("#define UV1");
  17061. }
  17062. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17063. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  17064. defines.push("#define UV2");
  17065. }
  17066. }
  17067. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17068. attribs.push(BABYLON.VertexBuffer.ColorKind);
  17069. defines.push("#define VERTEXCOLOR");
  17070. if (mesh.hasVertexAlpha) {
  17071. defines.push("#define VERTEXALPHA");
  17072. }
  17073. }
  17074. if (mesh.useBones) {
  17075. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17076. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17077. defines.push("#define BONES");
  17078. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  17079. defines.push("#define BONES4");
  17080. fallbacks.addFallback(0, "BONES4");
  17081. }
  17082. // Instances
  17083. if (useInstances) {
  17084. defines.push("#define INSTANCES");
  17085. attribs.push("world0");
  17086. attribs.push("world1");
  17087. attribs.push("world2");
  17088. attribs.push("world3");
  17089. }
  17090. }
  17091. // Get correct effect
  17092. var join = defines.join("\n");
  17093. if (this._cachedDefines !== join) {
  17094. this._cachedDefines = join;
  17095. scene.resetCachedMaterial();
  17096. // Legacy browser patch
  17097. var shaderName = "default";
  17098. if (!scene.getEngine().getCaps().standardDerivatives) {
  17099. shaderName = "legacydefault";
  17100. }
  17101. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  17102. }
  17103. if (!this._effect.isReady()) {
  17104. return false;
  17105. }
  17106. this._renderId = scene.getRenderId();
  17107. this._wasPreviouslyReady = true;
  17108. return true;
  17109. };
  17110. StandardMaterial.prototype.unbind = function () {
  17111. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  17112. this._effect.setTexture("reflection2DSampler", null);
  17113. }
  17114. };
  17115. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  17116. this._effect.setMatrix("world", world);
  17117. };
  17118. StandardMaterial.prototype.bind = function (world, mesh) {
  17119. var scene = this.getScene();
  17120. // Matrices
  17121. this.bindOnlyWorldMatrix(world);
  17122. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  17123. // Bones
  17124. if (mesh && mesh.useBones) {
  17125. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  17126. }
  17127. if (scene.getCachedMaterial() !== this) {
  17128. if (StandardMaterial.FresnelEnabled) {
  17129. // Fresnel
  17130. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17131. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  17132. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  17133. }
  17134. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17135. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  17136. }
  17137. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17138. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  17139. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  17140. }
  17141. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17142. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  17143. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  17144. }
  17145. }
  17146. // Textures
  17147. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17148. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  17149. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  17150. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  17151. }
  17152. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17153. this._effect.setTexture("ambientSampler", this.ambientTexture);
  17154. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  17155. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  17156. }
  17157. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17158. this._effect.setTexture("opacitySampler", this.opacityTexture);
  17159. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  17160. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  17161. }
  17162. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17163. if (this.reflectionTexture.isCube) {
  17164. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  17165. }
  17166. else {
  17167. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  17168. }
  17169. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  17170. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  17171. }
  17172. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17173. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  17174. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  17175. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  17176. }
  17177. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  17178. this._effect.setTexture("specularSampler", this.specularTexture);
  17179. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  17180. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  17181. }
  17182. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  17183. this._effect.setTexture("bumpSampler", this.bumpTexture);
  17184. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  17185. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  17186. }
  17187. // Clip plane
  17188. if (scene.clipPlane) {
  17189. var clipPlane = scene.clipPlane;
  17190. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  17191. }
  17192. // Point size
  17193. if (this.pointsCloud) {
  17194. this._effect.setFloat("pointSize", this.pointSize);
  17195. }
  17196. // Colors
  17197. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  17198. // Scaling down color according to emissive
  17199. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17200. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17201. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17202. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  17203. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  17204. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  17205. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  17206. }
  17207. // Scaling down color according to emissive
  17208. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17209. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17210. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17211. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  17212. if (scene.lightsEnabled) {
  17213. var lightIndex = 0;
  17214. for (var index = 0; index < scene.lights.length; index++) {
  17215. var light = scene.lights[index];
  17216. if (!light.isEnabled()) {
  17217. continue;
  17218. }
  17219. if (!light.canAffectMesh(mesh)) {
  17220. continue;
  17221. }
  17222. if (light instanceof BABYLON.PointLight) {
  17223. // Point Light
  17224. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17225. }
  17226. else if (light instanceof BABYLON.DirectionalLight) {
  17227. // Directional Light
  17228. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17229. }
  17230. else if (light instanceof BABYLON.SpotLight) {
  17231. // Spot Light
  17232. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  17233. }
  17234. else if (light instanceof BABYLON.HemisphericLight) {
  17235. // Hemispheric Light
  17236. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  17237. }
  17238. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  17239. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  17240. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  17241. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  17242. // Shadows
  17243. if (scene.shadowsEnabled) {
  17244. var shadowGenerator = light.getShadowGenerator();
  17245. if (mesh.receiveShadows && shadowGenerator) {
  17246. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  17247. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  17248. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  17249. }
  17250. }
  17251. lightIndex++;
  17252. if (lightIndex === maxSimultaneousLights)
  17253. break;
  17254. }
  17255. }
  17256. // View
  17257. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  17258. this._effect.setMatrix("view", scene.getViewMatrix());
  17259. }
  17260. // Fog
  17261. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  17262. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  17263. this._effect.setColor3("vFogColor", scene.fogColor);
  17264. }
  17265. _super.prototype.bind.call(this, world, mesh);
  17266. };
  17267. StandardMaterial.prototype.getAnimatables = function () {
  17268. var results = [];
  17269. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  17270. results.push(this.diffuseTexture);
  17271. }
  17272. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  17273. results.push(this.ambientTexture);
  17274. }
  17275. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  17276. results.push(this.opacityTexture);
  17277. }
  17278. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  17279. results.push(this.reflectionTexture);
  17280. }
  17281. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  17282. results.push(this.emissiveTexture);
  17283. }
  17284. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  17285. results.push(this.specularTexture);
  17286. }
  17287. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  17288. results.push(this.bumpTexture);
  17289. }
  17290. return results;
  17291. };
  17292. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  17293. if (this.diffuseTexture) {
  17294. this.diffuseTexture.dispose();
  17295. }
  17296. if (this.ambientTexture) {
  17297. this.ambientTexture.dispose();
  17298. }
  17299. if (this.opacityTexture) {
  17300. this.opacityTexture.dispose();
  17301. }
  17302. if (this.reflectionTexture) {
  17303. this.reflectionTexture.dispose();
  17304. }
  17305. if (this.emissiveTexture) {
  17306. this.emissiveTexture.dispose();
  17307. }
  17308. if (this.specularTexture) {
  17309. this.specularTexture.dispose();
  17310. }
  17311. if (this.bumpTexture) {
  17312. this.bumpTexture.dispose();
  17313. }
  17314. _super.prototype.dispose.call(this, forceDisposeEffect);
  17315. };
  17316. StandardMaterial.prototype.clone = function (name) {
  17317. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  17318. // Base material
  17319. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  17320. newStandardMaterial.alpha = this.alpha;
  17321. newStandardMaterial.fillMode = this.fillMode;
  17322. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  17323. // Standard material
  17324. if (this.diffuseTexture && this.diffuseTexture.clone) {
  17325. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  17326. }
  17327. if (this.ambientTexture && this.ambientTexture.clone) {
  17328. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  17329. }
  17330. if (this.opacityTexture && this.opacityTexture.clone) {
  17331. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  17332. }
  17333. if (this.reflectionTexture && this.reflectionTexture.clone) {
  17334. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  17335. }
  17336. if (this.emissiveTexture && this.emissiveTexture.clone) {
  17337. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  17338. }
  17339. if (this.specularTexture && this.specularTexture.clone) {
  17340. newStandardMaterial.specularTexture = this.specularTexture.clone();
  17341. }
  17342. if (this.bumpTexture && this.bumpTexture.clone) {
  17343. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  17344. }
  17345. newStandardMaterial.ambientColor = this.ambientColor.clone();
  17346. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  17347. newStandardMaterial.specularColor = this.specularColor.clone();
  17348. newStandardMaterial.specularPower = this.specularPower;
  17349. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  17350. return newStandardMaterial;
  17351. };
  17352. // Statics
  17353. // Flags used to enable or disable a type of texture for all Standard Materials
  17354. StandardMaterial.DiffuseTextureEnabled = true;
  17355. StandardMaterial.AmbientTextureEnabled = true;
  17356. StandardMaterial.OpacityTextureEnabled = true;
  17357. StandardMaterial.ReflectionTextureEnabled = true;
  17358. StandardMaterial.EmissiveTextureEnabled = true;
  17359. StandardMaterial.SpecularTextureEnabled = true;
  17360. StandardMaterial.BumpTextureEnabled = true;
  17361. StandardMaterial.FresnelEnabled = true;
  17362. return StandardMaterial;
  17363. })(BABYLON.Material);
  17364. BABYLON.StandardMaterial = StandardMaterial;
  17365. })(BABYLON || (BABYLON = {}));
  17366. //# sourceMappingURL=babylon.standardMaterial.js.map
  17367. var __extends = this.__extends || function (d, b) {
  17368. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17369. function __() { this.constructor = d; }
  17370. __.prototype = b.prototype;
  17371. d.prototype = new __();
  17372. };
  17373. var BABYLON;
  17374. (function (BABYLON) {
  17375. var MultiMaterial = (function (_super) {
  17376. __extends(MultiMaterial, _super);
  17377. function MultiMaterial(name, scene) {
  17378. _super.call(this, name, scene, true);
  17379. this.subMaterials = new Array();
  17380. scene.multiMaterials.push(this);
  17381. }
  17382. // Properties
  17383. MultiMaterial.prototype.getSubMaterial = function (index) {
  17384. if (index < 0 || index >= this.subMaterials.length) {
  17385. return this.getScene().defaultMaterial;
  17386. }
  17387. return this.subMaterials[index];
  17388. };
  17389. // Methods
  17390. MultiMaterial.prototype.isReady = function (mesh) {
  17391. for (var index = 0; index < this.subMaterials.length; index++) {
  17392. var subMaterial = this.subMaterials[index];
  17393. if (subMaterial) {
  17394. if (!this.subMaterials[index].isReady(mesh)) {
  17395. return false;
  17396. }
  17397. }
  17398. }
  17399. return true;
  17400. };
  17401. return MultiMaterial;
  17402. })(BABYLON.Material);
  17403. BABYLON.MultiMaterial = MultiMaterial;
  17404. })(BABYLON || (BABYLON = {}));
  17405. //# sourceMappingURL=babylon.multiMaterial.js.map
  17406. var BABYLON;
  17407. (function (BABYLON) {
  17408. var SceneLoader = (function () {
  17409. function SceneLoader() {
  17410. }
  17411. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17412. get: function () {
  17413. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17414. },
  17415. set: function (value) {
  17416. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17417. },
  17418. enumerable: true,
  17419. configurable: true
  17420. });
  17421. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17422. get: function () {
  17423. return SceneLoader._ShowLoadingScreen;
  17424. },
  17425. set: function (value) {
  17426. SceneLoader._ShowLoadingScreen = value;
  17427. },
  17428. enumerable: true,
  17429. configurable: true
  17430. });
  17431. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17432. var dotPosition = sceneFilename.lastIndexOf(".");
  17433. var queryStringPosition = sceneFilename.indexOf("?");
  17434. if (queryStringPosition === -1) {
  17435. queryStringPosition = sceneFilename.length;
  17436. }
  17437. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17438. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17439. var plugin = this._registeredPlugins[index];
  17440. if (plugin.extensions.indexOf(extension) !== -1) {
  17441. return plugin;
  17442. }
  17443. }
  17444. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17445. };
  17446. // Public functions
  17447. SceneLoader.RegisterPlugin = function (plugin) {
  17448. plugin.extensions = plugin.extensions.toLowerCase();
  17449. SceneLoader._registeredPlugins.push(plugin);
  17450. };
  17451. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17452. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17453. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17454. return;
  17455. }
  17456. var manifestChecked = function (success) {
  17457. scene.database = database;
  17458. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17459. var importMeshFromData = function (data) {
  17460. var meshes = [];
  17461. var particleSystems = [];
  17462. var skeletons = [];
  17463. try {
  17464. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17465. if (onerror) {
  17466. onerror(scene, 'unable to load the scene');
  17467. }
  17468. return;
  17469. }
  17470. }
  17471. catch (e) {
  17472. if (onerror) {
  17473. onerror(scene, e);
  17474. }
  17475. return;
  17476. }
  17477. if (onsuccess) {
  17478. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17479. onsuccess(meshes, particleSystems, skeletons);
  17480. }
  17481. };
  17482. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17483. // Direct load
  17484. importMeshFromData(sceneFilename.substr(5));
  17485. return;
  17486. }
  17487. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17488. importMeshFromData(data);
  17489. }, progressCallBack, database);
  17490. };
  17491. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17492. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17493. };
  17494. /**
  17495. * Load a scene
  17496. * @param rootUrl a string that defines the root url for scene and resources
  17497. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17498. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17499. */
  17500. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17501. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17502. };
  17503. /**
  17504. * Append a scene
  17505. * @param rootUrl a string that defines the root url for scene and resources
  17506. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17507. * @param scene is the instance of BABYLON.Scene to append to
  17508. */
  17509. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17510. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17511. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17512. return;
  17513. }
  17514. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17515. var database;
  17516. if (SceneLoader.ShowLoadingScreen) {
  17517. scene.getEngine().displayLoadingUI();
  17518. }
  17519. var loadSceneFromData = function (data) {
  17520. scene.database = database;
  17521. if (!plugin.load(scene, data, rootUrl)) {
  17522. if (onerror) {
  17523. onerror(scene);
  17524. }
  17525. scene.getEngine().hideLoadingUI();
  17526. return;
  17527. }
  17528. if (onsuccess) {
  17529. onsuccess(scene);
  17530. }
  17531. if (SceneLoader.ShowLoadingScreen) {
  17532. scene.executeWhenReady(function () {
  17533. scene.getEngine().hideLoadingUI();
  17534. });
  17535. }
  17536. };
  17537. var manifestChecked = function (success) {
  17538. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17539. };
  17540. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17541. // Direct load
  17542. loadSceneFromData(sceneFilename.substr(5));
  17543. return;
  17544. }
  17545. if (rootUrl.indexOf("file:") === -1) {
  17546. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17547. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17548. }
  17549. else {
  17550. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17551. }
  17552. };
  17553. // Flags
  17554. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17555. SceneLoader._ShowLoadingScreen = true;
  17556. // Members
  17557. SceneLoader._registeredPlugins = new Array();
  17558. return SceneLoader;
  17559. })();
  17560. BABYLON.SceneLoader = SceneLoader;
  17561. ;
  17562. })(BABYLON || (BABYLON = {}));
  17563. //# sourceMappingURL=babylon.sceneLoader.js.map
  17564. var BABYLON;
  17565. (function (BABYLON) {
  17566. var Internals;
  17567. (function (Internals) {
  17568. var checkColors4 = function (colors, count) {
  17569. // Check if color3 was used
  17570. if (colors.length === count * 3) {
  17571. var colors4 = [];
  17572. for (var index = 0; index < colors.length; index += 3) {
  17573. var newIndex = (index / 3) * 4;
  17574. colors4[newIndex] = colors[index];
  17575. colors4[newIndex + 1] = colors[index + 1];
  17576. colors4[newIndex + 2] = colors[index + 2];
  17577. colors4[newIndex + 3] = 1.0;
  17578. }
  17579. return colors4;
  17580. }
  17581. return colors;
  17582. };
  17583. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17584. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17585. texture.name = parsedTexture.name;
  17586. texture.hasAlpha = parsedTexture.hasAlpha;
  17587. texture.level = parsedTexture.level;
  17588. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17589. return texture;
  17590. };
  17591. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17592. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17593. return null;
  17594. }
  17595. if (parsedTexture.isCube) {
  17596. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17597. }
  17598. var texture;
  17599. if (parsedTexture.mirrorPlane) {
  17600. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17601. texture._waitingRenderList = parsedTexture.renderList;
  17602. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17603. }
  17604. else if (parsedTexture.isRenderTarget) {
  17605. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17606. texture._waitingRenderList = parsedTexture.renderList;
  17607. }
  17608. else {
  17609. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17610. }
  17611. texture.name = parsedTexture.name;
  17612. texture.hasAlpha = parsedTexture.hasAlpha;
  17613. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17614. texture.level = parsedTexture.level;
  17615. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17616. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17617. texture.uOffset = parsedTexture.uOffset;
  17618. texture.vOffset = parsedTexture.vOffset;
  17619. texture.uScale = parsedTexture.uScale;
  17620. texture.vScale = parsedTexture.vScale;
  17621. texture.uAng = parsedTexture.uAng;
  17622. texture.vAng = parsedTexture.vAng;
  17623. texture.wAng = parsedTexture.wAng;
  17624. texture.wrapU = parsedTexture.wrapU;
  17625. texture.wrapV = parsedTexture.wrapV;
  17626. // Animations
  17627. if (parsedTexture.animations) {
  17628. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17629. var parsedAnimation = parsedTexture.animations[animationIndex];
  17630. texture.animations.push(parseAnimation(parsedAnimation));
  17631. }
  17632. }
  17633. return texture;
  17634. };
  17635. var parseSkeleton = function (parsedSkeleton, scene) {
  17636. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17637. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17638. var parsedBone = parsedSkeleton.bones[index];
  17639. var parentBone = null;
  17640. if (parsedBone.parentBoneIndex > -1) {
  17641. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17642. }
  17643. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17644. if (parsedBone.animation) {
  17645. bone.animations.push(parseAnimation(parsedBone.animation));
  17646. }
  17647. }
  17648. return skeleton;
  17649. };
  17650. var parseFresnelParameters = function (parsedFresnelParameters) {
  17651. var fresnelParameters = new BABYLON.FresnelParameters();
  17652. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17653. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17654. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17655. fresnelParameters.bias = parsedFresnelParameters.bias;
  17656. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17657. return fresnelParameters;
  17658. };
  17659. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17660. var material;
  17661. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17662. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17663. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17664. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17665. material.specularPower = parsedMaterial.specularPower;
  17666. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17667. material.alpha = parsedMaterial.alpha;
  17668. material.id = parsedMaterial.id;
  17669. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17670. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17671. material.wireframe = parsedMaterial.wireframe;
  17672. if (parsedMaterial.diffuseTexture) {
  17673. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17674. }
  17675. if (parsedMaterial.diffuseFresnelParameters) {
  17676. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17677. }
  17678. if (parsedMaterial.ambientTexture) {
  17679. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17680. }
  17681. if (parsedMaterial.opacityTexture) {
  17682. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17683. }
  17684. if (parsedMaterial.opacityFresnelParameters) {
  17685. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17686. }
  17687. if (parsedMaterial.reflectionTexture) {
  17688. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17689. }
  17690. if (parsedMaterial.reflectionFresnelParameters) {
  17691. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17692. }
  17693. if (parsedMaterial.emissiveTexture) {
  17694. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17695. }
  17696. if (parsedMaterial.emissiveFresnelParameters) {
  17697. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17698. }
  17699. if (parsedMaterial.specularTexture) {
  17700. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17701. }
  17702. if (parsedMaterial.bumpTexture) {
  17703. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17704. }
  17705. return material;
  17706. };
  17707. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17708. for (var index = 0; index < parsedData.materials.length; index++) {
  17709. var parsedMaterial = parsedData.materials[index];
  17710. if (parsedMaterial.id === id) {
  17711. return parseMaterial(parsedMaterial, scene, rootUrl);
  17712. }
  17713. }
  17714. return null;
  17715. };
  17716. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17717. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17718. multiMaterial.id = parsedMultiMaterial.id;
  17719. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17720. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17721. var subMatId = parsedMultiMaterial.materials[matIndex];
  17722. if (subMatId) {
  17723. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17724. }
  17725. else {
  17726. multiMaterial.subMaterials.push(null);
  17727. }
  17728. }
  17729. return multiMaterial;
  17730. };
  17731. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17732. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17733. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17734. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17735. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17736. var parsedFlare = parsedLensFlareSystem.flares[index];
  17737. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17738. }
  17739. return lensFlareSystem;
  17740. };
  17741. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17742. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17743. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17744. if (parsedParticleSystem.textureName) {
  17745. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17746. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17747. }
  17748. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17749. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17750. particleSystem.minSize = parsedParticleSystem.minSize;
  17751. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17752. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17753. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17754. particleSystem.emitter = emitter;
  17755. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17756. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17757. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17758. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17759. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17760. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17761. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17762. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17763. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17764. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17765. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17766. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17767. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17768. particleSystem.start();
  17769. return particleSystem;
  17770. };
  17771. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17772. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17773. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17774. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17775. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17776. shadowGenerator.getShadowMap().renderList.push(mesh);
  17777. }
  17778. if (parsedShadowGenerator.usePoissonSampling) {
  17779. shadowGenerator.usePoissonSampling = true;
  17780. }
  17781. else if (parsedShadowGenerator.useVarianceShadowMap) {
  17782. shadowGenerator.useVarianceShadowMap = true;
  17783. }
  17784. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  17785. shadowGenerator.useBlurVarianceShadowMap = true;
  17786. if (parsedShadowGenerator.blurScale) {
  17787. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  17788. }
  17789. if (parsedShadowGenerator.blurBoxOffset) {
  17790. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  17791. }
  17792. }
  17793. if (parsedShadowGenerator.bias !== undefined) {
  17794. shadowGenerator.bias = parsedShadowGenerator.bias;
  17795. }
  17796. return shadowGenerator;
  17797. };
  17798. var parseAnimation = function (parsedAnimation) {
  17799. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17800. var dataType = parsedAnimation.dataType;
  17801. var keys = [];
  17802. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17803. var key = parsedAnimation.keys[index];
  17804. var data;
  17805. switch (dataType) {
  17806. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17807. data = key.values[0];
  17808. break;
  17809. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17810. data = BABYLON.Quaternion.FromArray(key.values);
  17811. break;
  17812. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17813. data = BABYLON.Matrix.FromArray(key.values);
  17814. break;
  17815. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17816. default:
  17817. data = BABYLON.Vector3.FromArray(key.values);
  17818. break;
  17819. }
  17820. keys.push({
  17821. frame: key.frame,
  17822. value: data
  17823. });
  17824. }
  17825. animation.setKeys(keys);
  17826. return animation;
  17827. };
  17828. var parseLight = function (parsedLight, scene) {
  17829. var light;
  17830. switch (parsedLight.type) {
  17831. case 0:
  17832. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17833. break;
  17834. case 1:
  17835. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17836. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17837. break;
  17838. case 2:
  17839. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17840. break;
  17841. case 3:
  17842. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17843. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17844. break;
  17845. }
  17846. light.id = parsedLight.id;
  17847. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17848. if (parsedLight.intensity !== undefined) {
  17849. light.intensity = parsedLight.intensity;
  17850. }
  17851. if (parsedLight.range) {
  17852. light.range = parsedLight.range;
  17853. }
  17854. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17855. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17856. if (parsedLight.excludedMeshesIds) {
  17857. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17858. }
  17859. // Parent
  17860. if (parsedLight.parentId) {
  17861. light._waitingParentId = parsedLight.parentId;
  17862. }
  17863. if (parsedLight.includedOnlyMeshesIds) {
  17864. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17865. }
  17866. // Animations
  17867. if (parsedLight.animations) {
  17868. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17869. var parsedAnimation = parsedLight.animations[animationIndex];
  17870. light.animations.push(parseAnimation(parsedAnimation));
  17871. }
  17872. }
  17873. if (parsedLight.autoAnimate) {
  17874. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17875. }
  17876. };
  17877. var parseCamera = function (parsedCamera, scene) {
  17878. var camera;
  17879. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17880. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17881. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17882. var alpha = parsedCamera.alpha;
  17883. var beta = parsedCamera.beta;
  17884. var radius = parsedCamera.radius;
  17885. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17886. var eye_space = parsedCamera.eye_space;
  17887. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17888. }
  17889. else {
  17890. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17891. }
  17892. }
  17893. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17894. eye_space = parsedCamera.eye_space;
  17895. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17896. }
  17897. else if (parsedCamera.type === "DeviceOrientationCamera") {
  17898. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17899. }
  17900. else if (parsedCamera.type === "FollowCamera") {
  17901. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17902. camera.heightOffset = parsedCamera.heightOffset;
  17903. camera.radius = parsedCamera.radius;
  17904. camera.rotationOffset = parsedCamera.rotationOffset;
  17905. if (lockedTargetMesh)
  17906. camera.target = lockedTargetMesh;
  17907. }
  17908. else if (parsedCamera.type === "GamepadCamera") {
  17909. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17910. }
  17911. else if (parsedCamera.type === "OculusCamera") {
  17912. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17913. }
  17914. else if (parsedCamera.type === "OculusGamepadCamera") {
  17915. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17916. }
  17917. else if (parsedCamera.type === "TouchCamera") {
  17918. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17919. }
  17920. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17921. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17922. }
  17923. else if (parsedCamera.type === "WebVRCamera") {
  17924. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17925. }
  17926. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17927. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17928. }
  17929. else {
  17930. // Free Camera is the default value
  17931. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17932. }
  17933. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17934. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17935. camera.lockedTarget = lockedTargetMesh;
  17936. }
  17937. camera.id = parsedCamera.id;
  17938. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17939. // Parent
  17940. if (parsedCamera.parentId) {
  17941. camera._waitingParentId = parsedCamera.parentId;
  17942. }
  17943. // Target
  17944. if (parsedCamera.target) {
  17945. if (camera.setTarget) {
  17946. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17947. }
  17948. else {
  17949. //For ArcRotate
  17950. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  17951. }
  17952. }
  17953. else {
  17954. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17955. }
  17956. camera.fov = parsedCamera.fov;
  17957. camera.minZ = parsedCamera.minZ;
  17958. camera.maxZ = parsedCamera.maxZ;
  17959. camera.speed = parsedCamera.speed;
  17960. camera.inertia = parsedCamera.inertia;
  17961. camera.checkCollisions = parsedCamera.checkCollisions;
  17962. camera.applyGravity = parsedCamera.applyGravity;
  17963. if (parsedCamera.ellipsoid) {
  17964. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17965. }
  17966. // Animations
  17967. if (parsedCamera.animations) {
  17968. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17969. var parsedAnimation = parsedCamera.animations[animationIndex];
  17970. camera.animations.push(parseAnimation(parsedAnimation));
  17971. }
  17972. }
  17973. if (parsedCamera.autoAnimate) {
  17974. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17975. }
  17976. // Layer Mask
  17977. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17978. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17979. }
  17980. else {
  17981. camera.layerMask = 0xFFFFFFFF;
  17982. }
  17983. return camera;
  17984. };
  17985. var parseGeometry = function (parsedGeometry, scene) {
  17986. var id = parsedGeometry.id;
  17987. return scene.getGeometryByID(id);
  17988. };
  17989. var parseBox = function (parsedBox, scene) {
  17990. if (parseGeometry(parsedBox, scene)) {
  17991. return null; // null since geometry could be something else than a box...
  17992. }
  17993. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17994. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17995. scene.pushGeometry(box, true);
  17996. return box;
  17997. };
  17998. var parseSphere = function (parsedSphere, scene) {
  17999. if (parseGeometry(parsedSphere, scene)) {
  18000. return null; // null since geometry could be something else than a sphere...
  18001. }
  18002. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18003. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18004. scene.pushGeometry(sphere, true);
  18005. return sphere;
  18006. };
  18007. var parseCylinder = function (parsedCylinder, scene) {
  18008. if (parseGeometry(parsedCylinder, scene)) {
  18009. return null; // null since geometry could be something else than a cylinder...
  18010. }
  18011. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18012. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18013. scene.pushGeometry(cylinder, true);
  18014. return cylinder;
  18015. };
  18016. var parseTorus = function (parsedTorus, scene) {
  18017. if (parseGeometry(parsedTorus, scene)) {
  18018. return null; // null since geometry could be something else than a torus...
  18019. }
  18020. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18021. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18022. scene.pushGeometry(torus, true);
  18023. return torus;
  18024. };
  18025. var parseGround = function (parsedGround, scene) {
  18026. if (parseGeometry(parsedGround, scene)) {
  18027. return null; // null since geometry could be something else than a ground...
  18028. }
  18029. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18030. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18031. scene.pushGeometry(ground, true);
  18032. return ground;
  18033. };
  18034. var parsePlane = function (parsedPlane, scene) {
  18035. if (parseGeometry(parsedPlane, scene)) {
  18036. return null; // null since geometry could be something else than a plane...
  18037. }
  18038. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18039. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18040. scene.pushGeometry(plane, true);
  18041. return plane;
  18042. };
  18043. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18044. if (parseGeometry(parsedTorusKnot, scene)) {
  18045. return null; // null since geometry could be something else than a torusKnot...
  18046. }
  18047. var torusKnot = new BABYLON.Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  18048. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18049. scene.pushGeometry(torusKnot, true);
  18050. return torusKnot;
  18051. };
  18052. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18053. if (parseGeometry(parsedVertexData, scene)) {
  18054. return null; // null since geometry could be a primitive
  18055. }
  18056. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18057. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18058. if (parsedVertexData.delayLoadingFile) {
  18059. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18060. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18061. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18062. geometry._delayInfo = [];
  18063. if (parsedVertexData.hasUVs) {
  18064. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18065. }
  18066. if (parsedVertexData.hasUVs2) {
  18067. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18068. }
  18069. if (parsedVertexData.hasColors) {
  18070. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18071. }
  18072. if (parsedVertexData.hasMatricesIndices) {
  18073. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18074. }
  18075. if (parsedVertexData.hasMatricesWeights) {
  18076. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18077. }
  18078. geometry._delayLoadingFunction = importVertexData;
  18079. }
  18080. else {
  18081. importVertexData(parsedVertexData, geometry);
  18082. }
  18083. scene.pushGeometry(geometry, true);
  18084. return geometry;
  18085. };
  18086. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18087. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18088. mesh.id = parsedMesh.id;
  18089. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18090. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18091. if (parsedMesh.rotationQuaternion) {
  18092. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18093. }
  18094. else if (parsedMesh.rotation) {
  18095. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18096. }
  18097. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18098. if (parsedMesh.localMatrix) {
  18099. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18100. }
  18101. else if (parsedMesh.pivotMatrix) {
  18102. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18103. }
  18104. mesh.setEnabled(parsedMesh.isEnabled);
  18105. mesh.isVisible = parsedMesh.isVisible;
  18106. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18107. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18108. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18109. if (parsedMesh.applyFog !== undefined) {
  18110. mesh.applyFog = parsedMesh.applyFog;
  18111. }
  18112. if (parsedMesh.pickable !== undefined) {
  18113. mesh.isPickable = parsedMesh.pickable;
  18114. }
  18115. if (parsedMesh.alphaIndex !== undefined) {
  18116. mesh.alphaIndex = parsedMesh.alphaIndex;
  18117. }
  18118. mesh.receiveShadows = parsedMesh.receiveShadows;
  18119. mesh.billboardMode = parsedMesh.billboardMode;
  18120. if (parsedMesh.visibility !== undefined) {
  18121. mesh.visibility = parsedMesh.visibility;
  18122. }
  18123. mesh.checkCollisions = parsedMesh.checkCollisions;
  18124. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18125. // Parent
  18126. if (parsedMesh.parentId) {
  18127. mesh._waitingParentId = parsedMesh.parentId;
  18128. }
  18129. // Actions
  18130. if (parsedMesh.actions !== undefined) {
  18131. mesh._waitingActions = parsedMesh.actions;
  18132. }
  18133. // Geometry
  18134. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18135. if (parsedMesh.delayLoadingFile) {
  18136. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18137. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18138. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18139. if (parsedMesh._binaryInfo) {
  18140. mesh._binaryInfo = parsedMesh._binaryInfo;
  18141. }
  18142. mesh._delayInfo = [];
  18143. if (parsedMesh.hasUVs) {
  18144. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18145. }
  18146. if (parsedMesh.hasUVs2) {
  18147. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18148. }
  18149. if (parsedMesh.hasColors) {
  18150. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18151. }
  18152. if (parsedMesh.hasMatricesIndices) {
  18153. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18154. }
  18155. if (parsedMesh.hasMatricesWeights) {
  18156. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18157. }
  18158. mesh._delayLoadingFunction = importGeometry;
  18159. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18160. mesh._checkDelayState();
  18161. }
  18162. }
  18163. else {
  18164. importGeometry(parsedMesh, mesh);
  18165. }
  18166. // Material
  18167. if (parsedMesh.materialId) {
  18168. mesh.setMaterialByID(parsedMesh.materialId);
  18169. }
  18170. else {
  18171. mesh.material = null;
  18172. }
  18173. // Skeleton
  18174. if (parsedMesh.skeletonId > -1) {
  18175. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18176. }
  18177. // Physics
  18178. if (parsedMesh.physicsImpostor) {
  18179. if (!scene.isPhysicsEnabled()) {
  18180. scene.enablePhysics();
  18181. }
  18182. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18183. }
  18184. // Animations
  18185. if (parsedMesh.animations) {
  18186. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18187. var parsedAnimation = parsedMesh.animations[animationIndex];
  18188. mesh.animations.push(parseAnimation(parsedAnimation));
  18189. }
  18190. }
  18191. if (parsedMesh.autoAnimate) {
  18192. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18193. }
  18194. // Layer Mask
  18195. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18196. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18197. }
  18198. else {
  18199. mesh.layerMask = 0xFFFFFFFF;
  18200. }
  18201. // Instances
  18202. if (parsedMesh.instances) {
  18203. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18204. var parsedInstance = parsedMesh.instances[index];
  18205. var instance = mesh.createInstance(parsedInstance.name);
  18206. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18207. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18208. if (parsedInstance.rotationQuaternion) {
  18209. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18210. }
  18211. else if (parsedInstance.rotation) {
  18212. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18213. }
  18214. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18215. instance.checkCollisions = mesh.checkCollisions;
  18216. if (parsedMesh.animations) {
  18217. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18218. parsedAnimation = parsedMesh.animations[animationIndex];
  18219. instance.animations.push(parseAnimation(parsedAnimation));
  18220. }
  18221. }
  18222. }
  18223. }
  18224. return mesh;
  18225. };
  18226. var parseActions = function (parsedActions, object, scene) {
  18227. var actionManager = new BABYLON.ActionManager(scene);
  18228. if (object === null)
  18229. scene.actionManager = actionManager;
  18230. else
  18231. object.actionManager = actionManager;
  18232. // instanciate a new object
  18233. var instanciate = function (name, params) {
  18234. var newInstance = Object.create(BABYLON[name].prototype);
  18235. newInstance.constructor.apply(newInstance, params);
  18236. return newInstance;
  18237. };
  18238. var parseParameter = function (name, value, target, propertyPath) {
  18239. if (propertyPath === null) {
  18240. // String, boolean or float
  18241. var floatValue = parseFloat(value);
  18242. if (value === "true" || value === "false")
  18243. return value === "true";
  18244. else
  18245. return isNaN(floatValue) ? value : floatValue;
  18246. }
  18247. var effectiveTarget = propertyPath.split(".");
  18248. var values = value.split(",");
  18249. for (var i = 0; i < effectiveTarget.length; i++) {
  18250. target = target[effectiveTarget[i]];
  18251. }
  18252. // Return appropriate value with its type
  18253. if (typeof (target) === "boolean")
  18254. return values[0] === "true";
  18255. if (typeof (target) === "string")
  18256. return values[0];
  18257. // Parameters with multiple values such as Vector3 etc.
  18258. var split = new Array();
  18259. for (var i = 0; i < values.length; i++)
  18260. split.push(parseFloat(values[i]));
  18261. if (target instanceof BABYLON.Vector3)
  18262. return BABYLON.Vector3.FromArray(split);
  18263. if (target instanceof BABYLON.Vector4)
  18264. return BABYLON.Vector4.FromArray(split);
  18265. if (target instanceof BABYLON.Color3)
  18266. return BABYLON.Color3.FromArray(split);
  18267. if (target instanceof BABYLON.Color4)
  18268. return BABYLON.Color4.FromArray(split);
  18269. return parseFloat(values[0]);
  18270. };
  18271. // traverse graph per trigger
  18272. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  18273. if (combineArray === void 0) { combineArray = null; }
  18274. if (parsedAction.detached)
  18275. return;
  18276. var parameters = new Array();
  18277. var target = null;
  18278. var propertyPath = null;
  18279. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  18280. // Parameters
  18281. if (parsedAction.type === 2)
  18282. parameters.push(actionManager);
  18283. else
  18284. parameters.push(trigger);
  18285. if (combine) {
  18286. var actions = new Array();
  18287. for (var j = 0; j < parsedAction.combine.length; j++) {
  18288. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  18289. }
  18290. parameters.push(actions);
  18291. }
  18292. else {
  18293. for (var i = 0; i < parsedAction.properties.length; i++) {
  18294. var value = parsedAction.properties[i].value;
  18295. var name = parsedAction.properties[i].name;
  18296. var targetType = parsedAction.properties[i].targetType;
  18297. if (name === "target")
  18298. if (targetType !== null && targetType === "SceneProperties")
  18299. value = target = scene;
  18300. else
  18301. value = target = scene.getNodeByName(value);
  18302. else if (name === "parent")
  18303. value = scene.getNodeByName(value);
  18304. else if (name === "sound")
  18305. value = scene.getSoundByName(value);
  18306. else if (name !== "propertyPath") {
  18307. if (parsedAction.type === 2 && name === "operator")
  18308. value = BABYLON.ValueCondition[value];
  18309. else
  18310. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18311. }
  18312. else {
  18313. propertyPath = value;
  18314. }
  18315. parameters.push(value);
  18316. }
  18317. }
  18318. if (combineArray === null) {
  18319. parameters.push(condition);
  18320. }
  18321. else {
  18322. parameters.push(null);
  18323. }
  18324. // If interpolate value action
  18325. if (parsedAction.name === "InterpolateValueAction") {
  18326. var param = parameters[parameters.length - 2];
  18327. parameters[parameters.length - 1] = param;
  18328. parameters[parameters.length - 2] = condition;
  18329. }
  18330. // Action or condition(s) and not CombineAction
  18331. var newAction = instanciate(parsedAction.name, parameters);
  18332. if (combineArray === null) {
  18333. if (newAction instanceof BABYLON.Condition) {
  18334. condition = newAction;
  18335. newAction = action;
  18336. }
  18337. else {
  18338. condition = null;
  18339. if (action)
  18340. action.then(newAction);
  18341. else
  18342. actionManager.registerAction(newAction);
  18343. }
  18344. }
  18345. else {
  18346. combineArray.push(newAction);
  18347. }
  18348. for (var i = 0; i < parsedAction.children.length; i++)
  18349. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  18350. };
  18351. for (var i = 0; i < parsedActions.children.length; i++) {
  18352. var triggerParams;
  18353. var trigger = parsedActions.children[i];
  18354. if (trigger.properties.length > 0) {
  18355. var param = trigger.properties[0].value;
  18356. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  18357. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  18358. }
  18359. else
  18360. triggerParams = BABYLON.ActionManager[trigger.name];
  18361. for (var j = 0; j < trigger.children.length; j++) {
  18362. if (!trigger.detached)
  18363. traverse(trigger.children[j], triggerParams, null, null);
  18364. }
  18365. }
  18366. };
  18367. var parseSound = function (parsedSound, scene, rootUrl) {
  18368. var soundName = parsedSound.name;
  18369. var soundUrl = rootUrl + soundName;
  18370. var options = {
  18371. autoplay: parsedSound.autoplay,
  18372. loop: parsedSound.loop,
  18373. volume: parsedSound.volume,
  18374. spatialSound: parsedSound.spatialSound,
  18375. maxDistance: parsedSound.maxDistance,
  18376. rolloffFactor: parsedSound.rolloffFactor,
  18377. refDistance: parsedSound.refDistance,
  18378. distanceModel: parsedSound.distanceModel,
  18379. playbackRate: parsedSound.playbackRate
  18380. };
  18381. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18382. scene._removePendingData(newSound);
  18383. }, options);
  18384. scene._addPendingData(newSound);
  18385. if (parsedSound.position) {
  18386. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18387. newSound.setPosition(soundPosition);
  18388. }
  18389. if (parsedSound.isDirectional) {
  18390. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18391. if (parsedSound.localDirectionToMesh) {
  18392. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18393. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18394. }
  18395. }
  18396. if (parsedSound.connectedMeshId) {
  18397. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18398. if (connectedMesh) {
  18399. newSound.attachToMesh(connectedMesh);
  18400. }
  18401. }
  18402. };
  18403. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18404. names = (names instanceof Array) ? names : [names];
  18405. for (var i in names) {
  18406. if (mesh.name === names[i]) {
  18407. hierarchyIds.push(mesh.id);
  18408. return true;
  18409. }
  18410. }
  18411. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18412. hierarchyIds.push(mesh.id);
  18413. return true;
  18414. }
  18415. return false;
  18416. };
  18417. var importVertexData = function (parsedVertexData, geometry) {
  18418. var vertexData = new BABYLON.VertexData();
  18419. // positions
  18420. var positions = parsedVertexData.positions;
  18421. if (positions) {
  18422. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18423. }
  18424. // normals
  18425. var normals = parsedVertexData.normals;
  18426. if (normals) {
  18427. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18428. }
  18429. // uvs
  18430. var uvs = parsedVertexData.uvs;
  18431. if (uvs) {
  18432. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18433. }
  18434. // uv2s
  18435. var uv2s = parsedVertexData.uv2s;
  18436. if (uv2s) {
  18437. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18438. }
  18439. // colors
  18440. var colors = parsedVertexData.colors;
  18441. if (colors) {
  18442. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18443. }
  18444. // matricesIndices
  18445. var matricesIndices = parsedVertexData.matricesIndices;
  18446. if (matricesIndices) {
  18447. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18448. }
  18449. // matricesWeights
  18450. var matricesWeights = parsedVertexData.matricesWeights;
  18451. if (matricesWeights) {
  18452. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18453. }
  18454. // indices
  18455. var indices = parsedVertexData.indices;
  18456. if (indices) {
  18457. vertexData.indices = indices;
  18458. }
  18459. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18460. };
  18461. var importGeometry = function (parsedGeometry, mesh) {
  18462. var scene = mesh.getScene();
  18463. // Geometry
  18464. var geometryId = parsedGeometry.geometryId;
  18465. if (geometryId) {
  18466. var geometry = scene.getGeometryByID(geometryId);
  18467. if (geometry) {
  18468. geometry.applyToMesh(mesh);
  18469. }
  18470. }
  18471. else if (parsedGeometry instanceof ArrayBuffer) {
  18472. var binaryInfo = mesh._binaryInfo;
  18473. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18474. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18475. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18476. }
  18477. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18478. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18479. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18480. }
  18481. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18482. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18483. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18484. }
  18485. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18486. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18487. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18488. }
  18489. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18490. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18491. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18492. }
  18493. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18494. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18495. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18496. }
  18497. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18498. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18499. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18500. }
  18501. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18502. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18503. mesh.setIndices(indicesData);
  18504. }
  18505. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18506. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18507. mesh.subMeshes = [];
  18508. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18509. var materialIndex = subMeshesData[(i * 5) + 0];
  18510. var verticesStart = subMeshesData[(i * 5) + 1];
  18511. var verticesCount = subMeshesData[(i * 5) + 2];
  18512. var indexStart = subMeshesData[(i * 5) + 3];
  18513. var indexCount = subMeshesData[(i * 5) + 4];
  18514. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18515. }
  18516. }
  18517. }
  18518. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18519. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18520. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18521. if (parsedGeometry.uvs) {
  18522. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18523. }
  18524. if (parsedGeometry.uvs2) {
  18525. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18526. }
  18527. if (parsedGeometry.colors) {
  18528. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18529. }
  18530. if (parsedGeometry.matricesIndices) {
  18531. if (!parsedGeometry.matricesIndices._isExpanded) {
  18532. var floatIndices = [];
  18533. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18534. var matricesIndex = parsedGeometry.matricesIndices[i];
  18535. floatIndices.push(matricesIndex & 0x000000FF);
  18536. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18537. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18538. floatIndices.push(matricesIndex >> 24);
  18539. }
  18540. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18541. }
  18542. else {
  18543. delete parsedGeometry.matricesIndices._isExpanded;
  18544. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18545. }
  18546. }
  18547. if (parsedGeometry.matricesWeights) {
  18548. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18549. }
  18550. mesh.setIndices(parsedGeometry.indices);
  18551. // SubMeshes
  18552. if (parsedGeometry.subMeshes) {
  18553. mesh.subMeshes = [];
  18554. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18555. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18556. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18557. }
  18558. }
  18559. }
  18560. // Flat shading
  18561. if (mesh._shouldGenerateFlatShading) {
  18562. mesh.convertToFlatShadedMesh();
  18563. delete mesh._shouldGenerateFlatShading;
  18564. }
  18565. // Update
  18566. mesh.computeWorldMatrix(true);
  18567. // Octree
  18568. if (scene._selectionOctree) {
  18569. scene._selectionOctree.addMesh(mesh);
  18570. }
  18571. };
  18572. BABYLON.SceneLoader.RegisterPlugin({
  18573. extensions: ".babylon",
  18574. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18575. var parsedData = JSON.parse(data);
  18576. var loadedSkeletonsIds = [];
  18577. var loadedMaterialsIds = [];
  18578. var hierarchyIds = [];
  18579. for (var index = 0; index < parsedData.meshes.length; index++) {
  18580. var parsedMesh = parsedData.meshes[index];
  18581. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18582. if (meshesNames instanceof Array) {
  18583. // Remove found mesh name from list.
  18584. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18585. }
  18586. // Material ?
  18587. if (parsedMesh.materialId) {
  18588. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18589. if (!materialFound) {
  18590. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18591. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18592. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18593. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18594. var subMatId = parsedMultiMaterial.materials[matIndex];
  18595. loadedMaterialsIds.push(subMatId);
  18596. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18597. }
  18598. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18599. parseMultiMaterial(parsedMultiMaterial, scene);
  18600. materialFound = true;
  18601. break;
  18602. }
  18603. }
  18604. }
  18605. if (!materialFound) {
  18606. loadedMaterialsIds.push(parsedMesh.materialId);
  18607. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18608. }
  18609. }
  18610. // Skeleton ?
  18611. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18612. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18613. if (!skeletonAlreadyLoaded) {
  18614. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18615. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18616. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18617. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18618. loadedSkeletonsIds.push(parsedSkeleton.id);
  18619. }
  18620. }
  18621. }
  18622. }
  18623. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18624. meshes.push(mesh);
  18625. }
  18626. }
  18627. for (index = 0; index < scene.meshes.length; index++) {
  18628. var currentMesh = scene.meshes[index];
  18629. if (currentMesh._waitingParentId) {
  18630. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18631. currentMesh._waitingParentId = undefined;
  18632. }
  18633. }
  18634. // Particles
  18635. if (parsedData.particleSystems) {
  18636. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18637. var parsedParticleSystem = parsedData.particleSystems[index];
  18638. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18639. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18640. }
  18641. }
  18642. }
  18643. return true;
  18644. },
  18645. load: function (scene, data, rootUrl) {
  18646. var parsedData = JSON.parse(data);
  18647. // Scene
  18648. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18649. scene.autoClear = parsedData.autoClear;
  18650. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18651. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18652. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18653. // Fog
  18654. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18655. scene.fogMode = parsedData.fogMode;
  18656. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18657. scene.fogStart = parsedData.fogStart;
  18658. scene.fogEnd = parsedData.fogEnd;
  18659. scene.fogDensity = parsedData.fogDensity;
  18660. }
  18661. for (var index = 0; index < parsedData.lights.length; index++) {
  18662. var parsedLight = parsedData.lights[index];
  18663. parseLight(parsedLight, scene);
  18664. }
  18665. // Materials
  18666. if (parsedData.materials) {
  18667. for (index = 0; index < parsedData.materials.length; index++) {
  18668. var parsedMaterial = parsedData.materials[index];
  18669. parseMaterial(parsedMaterial, scene, rootUrl);
  18670. }
  18671. }
  18672. if (parsedData.multiMaterials) {
  18673. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18674. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18675. parseMultiMaterial(parsedMultiMaterial, scene);
  18676. }
  18677. }
  18678. // Skeletons
  18679. if (parsedData.skeletons) {
  18680. for (index = 0; index < parsedData.skeletons.length; index++) {
  18681. var parsedSkeleton = parsedData.skeletons[index];
  18682. parseSkeleton(parsedSkeleton, scene);
  18683. }
  18684. }
  18685. // Geometries
  18686. var geometries = parsedData.geometries;
  18687. if (geometries) {
  18688. // Boxes
  18689. var boxes = geometries.boxes;
  18690. if (boxes) {
  18691. for (index = 0; index < boxes.length; index++) {
  18692. var parsedBox = boxes[index];
  18693. parseBox(parsedBox, scene);
  18694. }
  18695. }
  18696. // Spheres
  18697. var spheres = geometries.spheres;
  18698. if (spheres) {
  18699. for (index = 0; index < spheres.length; index++) {
  18700. var parsedSphere = spheres[index];
  18701. parseSphere(parsedSphere, scene);
  18702. }
  18703. }
  18704. // Cylinders
  18705. var cylinders = geometries.cylinders;
  18706. if (cylinders) {
  18707. for (index = 0; index < cylinders.length; index++) {
  18708. var parsedCylinder = cylinders[index];
  18709. parseCylinder(parsedCylinder, scene);
  18710. }
  18711. }
  18712. // Toruses
  18713. var toruses = geometries.toruses;
  18714. if (toruses) {
  18715. for (index = 0; index < toruses.length; index++) {
  18716. var parsedTorus = toruses[index];
  18717. parseTorus(parsedTorus, scene);
  18718. }
  18719. }
  18720. // Grounds
  18721. var grounds = geometries.grounds;
  18722. if (grounds) {
  18723. for (index = 0; index < grounds.length; index++) {
  18724. var parsedGround = grounds[index];
  18725. parseGround(parsedGround, scene);
  18726. }
  18727. }
  18728. // Planes
  18729. var planes = geometries.planes;
  18730. if (planes) {
  18731. for (index = 0; index < planes.length; index++) {
  18732. var parsedPlane = planes[index];
  18733. parsePlane(parsedPlane, scene);
  18734. }
  18735. }
  18736. // TorusKnots
  18737. var torusKnots = geometries.torusKnots;
  18738. if (torusKnots) {
  18739. for (index = 0; index < torusKnots.length; index++) {
  18740. var parsedTorusKnot = torusKnots[index];
  18741. parseTorusKnot(parsedTorusKnot, scene);
  18742. }
  18743. }
  18744. // VertexData
  18745. var vertexData = geometries.vertexData;
  18746. if (vertexData) {
  18747. for (index = 0; index < vertexData.length; index++) {
  18748. var parsedVertexData = vertexData[index];
  18749. parseVertexData(parsedVertexData, scene, rootUrl);
  18750. }
  18751. }
  18752. }
  18753. for (index = 0; index < parsedData.meshes.length; index++) {
  18754. var parsedMesh = parsedData.meshes[index];
  18755. parseMesh(parsedMesh, scene, rootUrl);
  18756. }
  18757. for (index = 0; index < parsedData.cameras.length; index++) {
  18758. var parsedCamera = parsedData.cameras[index];
  18759. parseCamera(parsedCamera, scene);
  18760. }
  18761. if (parsedData.activeCameraID) {
  18762. scene.setActiveCameraByID(parsedData.activeCameraID);
  18763. }
  18764. for (index = 0; index < scene.cameras.length; index++) {
  18765. var camera = scene.cameras[index];
  18766. if (camera._waitingParentId) {
  18767. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18768. camera._waitingParentId = undefined;
  18769. }
  18770. }
  18771. for (index = 0; index < scene.lights.length; index++) {
  18772. var light = scene.lights[index];
  18773. if (light._waitingParentId) {
  18774. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18775. light._waitingParentId = undefined;
  18776. }
  18777. }
  18778. // Sounds
  18779. if (parsedData.sounds) {
  18780. for (index = 0; index < parsedData.sounds.length; index++) {
  18781. var parsedSound = parsedData.sounds[index];
  18782. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  18783. parseSound(parsedSound, scene, rootUrl);
  18784. }
  18785. else {
  18786. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  18787. }
  18788. }
  18789. }
  18790. for (index = 0; index < scene.meshes.length; index++) {
  18791. var mesh = scene.meshes[index];
  18792. if (mesh._waitingParentId) {
  18793. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18794. mesh._waitingParentId = undefined;
  18795. }
  18796. if (mesh._waitingActions) {
  18797. parseActions(mesh._waitingActions, mesh, scene);
  18798. mesh._waitingActions = undefined;
  18799. }
  18800. }
  18801. // Particles Systems
  18802. if (parsedData.particleSystems) {
  18803. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18804. var parsedParticleSystem = parsedData.particleSystems[index];
  18805. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18806. }
  18807. }
  18808. // Lens flares
  18809. if (parsedData.lensFlareSystems) {
  18810. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18811. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18812. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18813. }
  18814. }
  18815. // Shadows
  18816. if (parsedData.shadowGenerators) {
  18817. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18818. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18819. parseShadowGenerator(parsedShadowGenerator, scene);
  18820. }
  18821. }
  18822. // Actions (scene)
  18823. if (parsedData.actions) {
  18824. parseActions(parsedData.actions, null, scene);
  18825. }
  18826. // Finish
  18827. return true;
  18828. }
  18829. });
  18830. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  18831. })(BABYLON || (BABYLON = {}));
  18832. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18833. var BABYLON;
  18834. (function (BABYLON) {
  18835. var SpriteManager = (function () {
  18836. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  18837. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18838. this.name = name;
  18839. this.cellSize = cellSize;
  18840. this.sprites = new Array();
  18841. this.renderingGroupId = 0;
  18842. this.fogEnabled = true;
  18843. this._vertexDeclaration = [4, 4, 4, 4];
  18844. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  18845. this._capacity = capacity;
  18846. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  18847. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18848. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18849. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  18850. this._scene = scene;
  18851. this._scene.spriteManagers.push(this);
  18852. // VBO
  18853. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  18854. var indices = [];
  18855. var index = 0;
  18856. for (var count = 0; count < capacity; count++) {
  18857. indices.push(index);
  18858. indices.push(index + 1);
  18859. indices.push(index + 2);
  18860. indices.push(index);
  18861. indices.push(index + 2);
  18862. indices.push(index + 3);
  18863. index += 4;
  18864. }
  18865. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18866. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  18867. // Effects
  18868. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  18869. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  18870. }
  18871. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  18872. var arrayOffset = index * 16;
  18873. if (offsetX === 0)
  18874. offsetX = this._epsilon;
  18875. else if (offsetX === 1)
  18876. offsetX = 1 - this._epsilon;
  18877. if (offsetY === 0)
  18878. offsetY = this._epsilon;
  18879. else if (offsetY === 1)
  18880. offsetY = 1 - this._epsilon;
  18881. this._vertices[arrayOffset] = sprite.position.x;
  18882. this._vertices[arrayOffset + 1] = sprite.position.y;
  18883. this._vertices[arrayOffset + 2] = sprite.position.z;
  18884. this._vertices[arrayOffset + 3] = sprite.angle;
  18885. this._vertices[arrayOffset + 4] = sprite.width;
  18886. this._vertices[arrayOffset + 5] = sprite.height;
  18887. this._vertices[arrayOffset + 6] = offsetX;
  18888. this._vertices[arrayOffset + 7] = offsetY;
  18889. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  18890. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  18891. var offset = (sprite.cellIndex / rowSize) >> 0;
  18892. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  18893. this._vertices[arrayOffset + 11] = offset;
  18894. // Color
  18895. this._vertices[arrayOffset + 12] = sprite.color.r;
  18896. this._vertices[arrayOffset + 13] = sprite.color.g;
  18897. this._vertices[arrayOffset + 14] = sprite.color.b;
  18898. this._vertices[arrayOffset + 15] = sprite.color.a;
  18899. };
  18900. SpriteManager.prototype.render = function () {
  18901. // Check
  18902. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  18903. return;
  18904. var engine = this._scene.getEngine();
  18905. var baseSize = this._spriteTexture.getBaseSize();
  18906. // Sprites
  18907. var deltaTime = engine.getDeltaTime();
  18908. var max = Math.min(this._capacity, this.sprites.length);
  18909. var rowSize = baseSize.width / this.cellSize;
  18910. var offset = 0;
  18911. for (var index = 0; index < max; index++) {
  18912. var sprite = this.sprites[index];
  18913. if (!sprite) {
  18914. continue;
  18915. }
  18916. sprite._animate(deltaTime);
  18917. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  18918. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  18919. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  18920. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  18921. }
  18922. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  18923. // Render
  18924. var effect = this._effectBase;
  18925. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18926. effect = this._effectFog;
  18927. }
  18928. engine.enableEffect(effect);
  18929. var viewMatrix = this._scene.getViewMatrix();
  18930. effect.setTexture("diffuseSampler", this._spriteTexture);
  18931. effect.setMatrix("view", viewMatrix);
  18932. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  18933. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  18934. // Fog
  18935. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18936. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  18937. effect.setColor3("vFogColor", this._scene.fogColor);
  18938. }
  18939. // VBOs
  18940. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  18941. // Draw order
  18942. engine.setDepthFunctionToLessOrEqual();
  18943. effect.setBool("alphaTest", true);
  18944. engine.setColorWrite(false);
  18945. engine.draw(true, 0, max * 6);
  18946. engine.setColorWrite(true);
  18947. effect.setBool("alphaTest", false);
  18948. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18949. engine.draw(true, 0, max * 6);
  18950. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18951. };
  18952. SpriteManager.prototype.dispose = function () {
  18953. if (this._vertexBuffer) {
  18954. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18955. this._vertexBuffer = null;
  18956. }
  18957. if (this._indexBuffer) {
  18958. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18959. this._indexBuffer = null;
  18960. }
  18961. if (this._spriteTexture) {
  18962. this._spriteTexture.dispose();
  18963. this._spriteTexture = null;
  18964. }
  18965. // Remove from scene
  18966. var index = this._scene.spriteManagers.indexOf(this);
  18967. this._scene.spriteManagers.splice(index, 1);
  18968. // Callback
  18969. if (this.onDispose) {
  18970. this.onDispose();
  18971. }
  18972. };
  18973. return SpriteManager;
  18974. })();
  18975. BABYLON.SpriteManager = SpriteManager;
  18976. })(BABYLON || (BABYLON = {}));
  18977. //# sourceMappingURL=babylon.spriteManager.js.map
  18978. var BABYLON;
  18979. (function (BABYLON) {
  18980. var Sprite = (function () {
  18981. function Sprite(name, manager) {
  18982. this.name = name;
  18983. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  18984. this.width = 1.0;
  18985. this.height = 1.0;
  18986. this.angle = 0;
  18987. this.cellIndex = 0;
  18988. this.invertU = 0;
  18989. this.invertV = 0;
  18990. this.animations = new Array();
  18991. this._animationStarted = false;
  18992. this._loopAnimation = false;
  18993. this._fromIndex = 0;
  18994. this._toIndex = 0;
  18995. this._delay = 0;
  18996. this._direction = 1;
  18997. this._frameCount = 0;
  18998. this._time = 0;
  18999. this._manager = manager;
  19000. this._manager.sprites.push(this);
  19001. this.position = BABYLON.Vector3.Zero();
  19002. }
  19003. Object.defineProperty(Sprite.prototype, "size", {
  19004. get: function () {
  19005. return this.width;
  19006. },
  19007. set: function (value) {
  19008. this.width = value;
  19009. this.height = value;
  19010. },
  19011. enumerable: true,
  19012. configurable: true
  19013. });
  19014. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  19015. this._fromIndex = from;
  19016. this._toIndex = to;
  19017. this._loopAnimation = loop;
  19018. this._delay = delay;
  19019. this._animationStarted = true;
  19020. this._direction = from < to ? 1 : -1;
  19021. this.cellIndex = from;
  19022. this._time = 0;
  19023. };
  19024. Sprite.prototype.stopAnimation = function () {
  19025. this._animationStarted = false;
  19026. };
  19027. Sprite.prototype._animate = function (deltaTime) {
  19028. if (!this._animationStarted)
  19029. return;
  19030. this._time += deltaTime;
  19031. if (this._time > this._delay) {
  19032. this._time = this._time % this._delay;
  19033. this.cellIndex += this._direction;
  19034. if (this.cellIndex == this._toIndex) {
  19035. if (this._loopAnimation) {
  19036. this.cellIndex = this._fromIndex;
  19037. }
  19038. else {
  19039. this._animationStarted = false;
  19040. if (this.disposeWhenFinishedAnimating) {
  19041. this.dispose();
  19042. }
  19043. }
  19044. }
  19045. }
  19046. };
  19047. Sprite.prototype.dispose = function () {
  19048. for (var i = 0; i < this._manager.sprites.length; i++) {
  19049. if (this._manager.sprites[i] == this) {
  19050. this._manager.sprites.splice(i, 1);
  19051. }
  19052. }
  19053. };
  19054. return Sprite;
  19055. })();
  19056. BABYLON.Sprite = Sprite;
  19057. })(BABYLON || (BABYLON = {}));
  19058. //# sourceMappingURL=babylon.sprite.js.map
  19059. var BABYLON;
  19060. (function (BABYLON) {
  19061. var Layer = (function () {
  19062. function Layer(name, imgUrl, scene, isBackground, color) {
  19063. this.name = name;
  19064. this._vertexDeclaration = [2];
  19065. this._vertexStrideSize = 2 * 4;
  19066. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  19067. this.isBackground = isBackground === undefined ? true : isBackground;
  19068. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  19069. this._scene = scene;
  19070. this._scene.layers.push(this);
  19071. // VBO
  19072. var vertices = [];
  19073. vertices.push(1, 1);
  19074. vertices.push(-1, 1);
  19075. vertices.push(-1, -1);
  19076. vertices.push(1, -1);
  19077. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19078. // Indices
  19079. var indices = [];
  19080. indices.push(0);
  19081. indices.push(1);
  19082. indices.push(2);
  19083. indices.push(0);
  19084. indices.push(2);
  19085. indices.push(3);
  19086. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19087. // Effects
  19088. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  19089. }
  19090. Layer.prototype.render = function () {
  19091. // Check
  19092. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  19093. return;
  19094. var engine = this._scene.getEngine();
  19095. // Render
  19096. engine.enableEffect(this._effect);
  19097. engine.setState(false);
  19098. // Texture
  19099. this._effect.setTexture("textureSampler", this.texture);
  19100. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  19101. // Color
  19102. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  19103. // VBOs
  19104. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19105. // Draw order
  19106. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19107. engine.draw(true, 0, 6);
  19108. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19109. };
  19110. Layer.prototype.dispose = function () {
  19111. if (this._vertexBuffer) {
  19112. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19113. this._vertexBuffer = null;
  19114. }
  19115. if (this._indexBuffer) {
  19116. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19117. this._indexBuffer = null;
  19118. }
  19119. if (this.texture) {
  19120. this.texture.dispose();
  19121. this.texture = null;
  19122. }
  19123. // Remove from scene
  19124. var index = this._scene.layers.indexOf(this);
  19125. this._scene.layers.splice(index, 1);
  19126. // Callback
  19127. if (this.onDispose) {
  19128. this.onDispose();
  19129. }
  19130. };
  19131. return Layer;
  19132. })();
  19133. BABYLON.Layer = Layer;
  19134. })(BABYLON || (BABYLON = {}));
  19135. //# sourceMappingURL=babylon.layer.js.map
  19136. var BABYLON;
  19137. (function (BABYLON) {
  19138. var Particle = (function () {
  19139. function Particle() {
  19140. this.position = BABYLON.Vector3.Zero();
  19141. this.direction = BABYLON.Vector3.Zero();
  19142. this.color = new BABYLON.Color4(0, 0, 0, 0);
  19143. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  19144. this.lifeTime = 1.0;
  19145. this.age = 0;
  19146. this.size = 0;
  19147. this.angle = 0;
  19148. this.angularSpeed = 0;
  19149. }
  19150. Particle.prototype.copyTo = function (other) {
  19151. other.position.copyFrom(this.position);
  19152. other.direction.copyFrom(this.direction);
  19153. other.color.copyFrom(this.color);
  19154. other.colorStep.copyFrom(this.colorStep);
  19155. other.lifeTime = this.lifeTime;
  19156. other.age = this.age;
  19157. other.size = this.size;
  19158. other.angle = this.angle;
  19159. other.angularSpeed = this.angularSpeed;
  19160. };
  19161. return Particle;
  19162. })();
  19163. BABYLON.Particle = Particle;
  19164. })(BABYLON || (BABYLON = {}));
  19165. //# sourceMappingURL=babylon.particle.js.map
  19166. var BABYLON;
  19167. (function (BABYLON) {
  19168. var randomNumber = function (min, max) {
  19169. if (min === max) {
  19170. return (min);
  19171. }
  19172. var random = Math.random();
  19173. return ((random * (max - min)) + min);
  19174. };
  19175. var ParticleSystem = (function () {
  19176. function ParticleSystem(name, capacity, scene, customEffect) {
  19177. var _this = this;
  19178. this.name = name;
  19179. this.renderingGroupId = 0;
  19180. this.emitter = null;
  19181. this.emitRate = 10;
  19182. this.manualEmitCount = -1;
  19183. this.updateSpeed = 0.01;
  19184. this.targetStopDuration = 0;
  19185. this.disposeOnStop = false;
  19186. this.minEmitPower = 1;
  19187. this.maxEmitPower = 1;
  19188. this.minLifeTime = 1;
  19189. this.maxLifeTime = 1;
  19190. this.minSize = 1;
  19191. this.maxSize = 1;
  19192. this.minAngularSpeed = 0;
  19193. this.maxAngularSpeed = 0;
  19194. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  19195. this.forceDepthWrite = false;
  19196. this.gravity = BABYLON.Vector3.Zero();
  19197. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  19198. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  19199. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  19200. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  19201. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19202. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19203. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  19204. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19205. this.particles = new Array();
  19206. this._vertexDeclaration = [3, 4, 4];
  19207. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  19208. this._stockParticles = new Array();
  19209. this._newPartsExcess = 0;
  19210. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  19211. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  19212. this._scaledDirection = BABYLON.Vector3.Zero();
  19213. this._scaledGravity = BABYLON.Vector3.Zero();
  19214. this._currentRenderId = -1;
  19215. this._started = false;
  19216. this._stopped = false;
  19217. this._actualFrame = 0;
  19218. this.id = name;
  19219. this._capacity = capacity;
  19220. this._scene = scene;
  19221. this._customEffect = customEffect;
  19222. scene.particleSystems.push(this);
  19223. // VBO
  19224. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  19225. var indices = [];
  19226. var index = 0;
  19227. for (var count = 0; count < capacity; count++) {
  19228. indices.push(index);
  19229. indices.push(index + 1);
  19230. indices.push(index + 2);
  19231. indices.push(index);
  19232. indices.push(index + 2);
  19233. indices.push(index + 3);
  19234. index += 4;
  19235. }
  19236. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19237. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  19238. // Default behaviors
  19239. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  19240. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  19241. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  19242. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  19243. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  19244. };
  19245. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  19246. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  19247. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  19248. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  19249. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  19250. };
  19251. this.updateFunction = function (particles) {
  19252. for (var index = 0; index < particles.length; index++) {
  19253. var particle = particles[index];
  19254. particle.age += _this._scaledUpdateSpeed;
  19255. if (particle.age >= particle.lifeTime) {
  19256. _this.recycleParticle(particle);
  19257. index--;
  19258. continue;
  19259. }
  19260. else {
  19261. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  19262. particle.color.addInPlace(_this._scaledColorStep);
  19263. if (particle.color.a < 0)
  19264. particle.color.a = 0;
  19265. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  19266. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  19267. particle.position.addInPlace(_this._scaledDirection);
  19268. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  19269. particle.direction.addInPlace(_this._scaledGravity);
  19270. }
  19271. }
  19272. };
  19273. }
  19274. ParticleSystem.prototype.recycleParticle = function (particle) {
  19275. var lastParticle = this.particles.pop();
  19276. if (lastParticle !== particle) {
  19277. lastParticle.copyTo(particle);
  19278. this._stockParticles.push(lastParticle);
  19279. }
  19280. };
  19281. ParticleSystem.prototype.getCapacity = function () {
  19282. return this._capacity;
  19283. };
  19284. ParticleSystem.prototype.isAlive = function () {
  19285. return this._alive;
  19286. };
  19287. ParticleSystem.prototype.isStarted = function () {
  19288. return this._started;
  19289. };
  19290. ParticleSystem.prototype.start = function () {
  19291. this._started = true;
  19292. this._stopped = false;
  19293. this._actualFrame = 0;
  19294. };
  19295. ParticleSystem.prototype.stop = function () {
  19296. this._stopped = true;
  19297. };
  19298. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  19299. var offset = index * 11;
  19300. this._vertices[offset] = particle.position.x;
  19301. this._vertices[offset + 1] = particle.position.y;
  19302. this._vertices[offset + 2] = particle.position.z;
  19303. this._vertices[offset + 3] = particle.color.r;
  19304. this._vertices[offset + 4] = particle.color.g;
  19305. this._vertices[offset + 5] = particle.color.b;
  19306. this._vertices[offset + 6] = particle.color.a;
  19307. this._vertices[offset + 7] = particle.angle;
  19308. this._vertices[offset + 8] = particle.size;
  19309. this._vertices[offset + 9] = offsetX;
  19310. this._vertices[offset + 10] = offsetY;
  19311. };
  19312. ParticleSystem.prototype._update = function (newParticles) {
  19313. // Update current
  19314. this._alive = this.particles.length > 0;
  19315. this.updateFunction(this.particles);
  19316. // Add new ones
  19317. var worldMatrix;
  19318. if (this.emitter.position) {
  19319. worldMatrix = this.emitter.getWorldMatrix();
  19320. }
  19321. else {
  19322. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  19323. }
  19324. for (var index = 0; index < newParticles; index++) {
  19325. if (this.particles.length === this._capacity) {
  19326. break;
  19327. }
  19328. if (this._stockParticles.length !== 0) {
  19329. var particle = this._stockParticles.pop();
  19330. particle.age = 0;
  19331. }
  19332. else {
  19333. particle = new BABYLON.Particle();
  19334. }
  19335. this.particles.push(particle);
  19336. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  19337. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  19338. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  19339. particle.size = randomNumber(this.minSize, this.maxSize);
  19340. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  19341. this.startPositionFunction(worldMatrix, particle.position);
  19342. var step = randomNumber(0, 1.0);
  19343. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  19344. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  19345. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  19346. }
  19347. };
  19348. ParticleSystem.prototype._getEffect = function () {
  19349. if (this._customEffect) {
  19350. return this._customEffect;
  19351. }
  19352. ;
  19353. var defines = [];
  19354. if (this._scene.clipPlane) {
  19355. defines.push("#define CLIPPLANE");
  19356. }
  19357. // Effect
  19358. var join = defines.join("\n");
  19359. if (this._cachedDefines !== join) {
  19360. this._cachedDefines = join;
  19361. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  19362. }
  19363. return this._effect;
  19364. };
  19365. ParticleSystem.prototype.animate = function () {
  19366. if (!this._started)
  19367. return;
  19368. var effect = this._getEffect();
  19369. // Check
  19370. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  19371. return;
  19372. if (this._currentRenderId === this._scene.getRenderId()) {
  19373. return;
  19374. }
  19375. this._currentRenderId = this._scene.getRenderId();
  19376. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  19377. // determine the number of particles we need to create
  19378. var emitCout;
  19379. if (this.manualEmitCount > -1) {
  19380. emitCout = this.manualEmitCount;
  19381. this.manualEmitCount = 0;
  19382. }
  19383. else {
  19384. emitCout = this.emitRate;
  19385. }
  19386. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  19387. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  19388. if (this._newPartsExcess > 1.0) {
  19389. newParticles += this._newPartsExcess >> 0;
  19390. this._newPartsExcess -= this._newPartsExcess >> 0;
  19391. }
  19392. this._alive = false;
  19393. if (!this._stopped) {
  19394. this._actualFrame += this._scaledUpdateSpeed;
  19395. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  19396. this.stop();
  19397. }
  19398. else {
  19399. newParticles = 0;
  19400. }
  19401. this._update(newParticles);
  19402. // Stopped?
  19403. if (this._stopped) {
  19404. if (!this._alive) {
  19405. this._started = false;
  19406. if (this.disposeOnStop) {
  19407. this._scene._toBeDisposed.push(this);
  19408. }
  19409. }
  19410. }
  19411. // Update VBO
  19412. var offset = 0;
  19413. for (var index = 0; index < this.particles.length; index++) {
  19414. var particle = this.particles[index];
  19415. this._appendParticleVertex(offset++, particle, 0, 0);
  19416. this._appendParticleVertex(offset++, particle, 1, 0);
  19417. this._appendParticleVertex(offset++, particle, 1, 1);
  19418. this._appendParticleVertex(offset++, particle, 0, 1);
  19419. }
  19420. var engine = this._scene.getEngine();
  19421. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  19422. };
  19423. ParticleSystem.prototype.render = function () {
  19424. var effect = this._getEffect();
  19425. // Check
  19426. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  19427. return 0;
  19428. var engine = this._scene.getEngine();
  19429. // Render
  19430. engine.enableEffect(effect);
  19431. engine.setState(false);
  19432. var viewMatrix = this._scene.getViewMatrix();
  19433. effect.setTexture("diffuseSampler", this.particleTexture);
  19434. effect.setMatrix("view", viewMatrix);
  19435. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  19436. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  19437. if (this._scene.clipPlane) {
  19438. var clipPlane = this._scene.clipPlane;
  19439. var invView = viewMatrix.clone();
  19440. invView.invert();
  19441. effect.setMatrix("invView", invView);
  19442. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19443. }
  19444. // VBOs
  19445. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  19446. // Draw order
  19447. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  19448. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  19449. }
  19450. else {
  19451. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19452. }
  19453. if (this.forceDepthWrite) {
  19454. engine.setDepthWrite(true);
  19455. }
  19456. engine.draw(true, 0, this.particles.length * 6);
  19457. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19458. return this.particles.length;
  19459. };
  19460. ParticleSystem.prototype.dispose = function () {
  19461. if (this._vertexBuffer) {
  19462. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19463. this._vertexBuffer = null;
  19464. }
  19465. if (this._indexBuffer) {
  19466. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19467. this._indexBuffer = null;
  19468. }
  19469. if (this.particleTexture) {
  19470. this.particleTexture.dispose();
  19471. this.particleTexture = null;
  19472. }
  19473. // Remove from scene
  19474. var index = this._scene.particleSystems.indexOf(this);
  19475. this._scene.particleSystems.splice(index, 1);
  19476. // Callback
  19477. if (this.onDispose) {
  19478. this.onDispose();
  19479. }
  19480. };
  19481. // Clone
  19482. ParticleSystem.prototype.clone = function (name, newEmitter) {
  19483. var result = new ParticleSystem(name, this._capacity, this._scene);
  19484. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  19485. if (newEmitter === undefined) {
  19486. newEmitter = this.emitter;
  19487. }
  19488. result.emitter = newEmitter;
  19489. if (this.particleTexture) {
  19490. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  19491. }
  19492. result.start();
  19493. return result;
  19494. };
  19495. // Statics
  19496. ParticleSystem.BLENDMODE_ONEONE = 0;
  19497. ParticleSystem.BLENDMODE_STANDARD = 1;
  19498. return ParticleSystem;
  19499. })();
  19500. BABYLON.ParticleSystem = ParticleSystem;
  19501. })(BABYLON || (BABYLON = {}));
  19502. //# sourceMappingURL=babylon.particleSystem.js.map
  19503. var BABYLON;
  19504. (function (BABYLON) {
  19505. var Animation = (function () {
  19506. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  19507. this.name = name;
  19508. this.targetProperty = targetProperty;
  19509. this.framePerSecond = framePerSecond;
  19510. this.dataType = dataType;
  19511. this.loopMode = loopMode;
  19512. this._offsetsCache = {};
  19513. this._highLimitsCache = {};
  19514. this._stopped = false;
  19515. this.targetPropertyPath = targetProperty.split(".");
  19516. this.dataType = dataType;
  19517. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  19518. }
  19519. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  19520. var dataType = undefined;
  19521. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  19522. dataType = Animation.ANIMATIONTYPE_FLOAT;
  19523. }
  19524. else if (from instanceof BABYLON.Quaternion) {
  19525. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  19526. }
  19527. else if (from instanceof BABYLON.Vector3) {
  19528. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  19529. }
  19530. else if (from instanceof BABYLON.Vector2) {
  19531. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  19532. }
  19533. else if (from instanceof BABYLON.Color3) {
  19534. dataType = Animation.ANIMATIONTYPE_COLOR3;
  19535. }
  19536. if (dataType == undefined) {
  19537. return null;
  19538. }
  19539. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  19540. var keys = [];
  19541. keys.push({ frame: 0, value: from });
  19542. keys.push({ frame: totalFrame, value: to });
  19543. animation.setKeys(keys);
  19544. mesh.animations.push(animation);
  19545. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  19546. };
  19547. // Methods
  19548. Animation.prototype.isStopped = function () {
  19549. return this._stopped;
  19550. };
  19551. Animation.prototype.getKeys = function () {
  19552. return this._keys;
  19553. };
  19554. Animation.prototype.getEasingFunction = function () {
  19555. return this._easingFunction;
  19556. };
  19557. Animation.prototype.setEasingFunction = function (easingFunction) {
  19558. this._easingFunction = easingFunction;
  19559. };
  19560. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  19561. return startValue + (endValue - startValue) * gradient;
  19562. };
  19563. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  19564. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  19565. };
  19566. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  19567. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  19568. };
  19569. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  19570. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  19571. };
  19572. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  19573. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  19574. };
  19575. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  19576. var startScale = new BABYLON.Vector3(0, 0, 0);
  19577. var startRotation = new BABYLON.Quaternion();
  19578. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  19579. startValue.decompose(startScale, startRotation, startTranslation);
  19580. var endScale = new BABYLON.Vector3(0, 0, 0);
  19581. var endRotation = new BABYLON.Quaternion();
  19582. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  19583. endValue.decompose(endScale, endRotation, endTranslation);
  19584. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  19585. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  19586. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  19587. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  19588. return result;
  19589. };
  19590. Animation.prototype.clone = function () {
  19591. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  19592. clone.setKeys(this._keys);
  19593. return clone;
  19594. };
  19595. Animation.prototype.setKeys = function (values) {
  19596. this._keys = values.slice(0);
  19597. this._offsetsCache = {};
  19598. this._highLimitsCache = {};
  19599. };
  19600. Animation.prototype._getKeyValue = function (value) {
  19601. if (typeof value === "function") {
  19602. return value();
  19603. }
  19604. return value;
  19605. };
  19606. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  19607. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  19608. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  19609. }
  19610. this.currentFrame = currentFrame;
  19611. // Try to get a hash to find the right key
  19612. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  19613. if (this._keys[startKey].frame >= currentFrame) {
  19614. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  19615. startKey--;
  19616. }
  19617. }
  19618. for (var key = startKey; key < this._keys.length; key++) {
  19619. if (this._keys[key + 1].frame >= currentFrame) {
  19620. var startValue = this._getKeyValue(this._keys[key].value);
  19621. var endValue = this._getKeyValue(this._keys[key + 1].value);
  19622. // gradient : percent of currentFrame between the frame inf and the frame sup
  19623. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  19624. // check for easingFunction and correction of gradient
  19625. if (this._easingFunction != null) {
  19626. gradient = this._easingFunction.ease(gradient);
  19627. }
  19628. switch (this.dataType) {
  19629. case Animation.ANIMATIONTYPE_FLOAT:
  19630. switch (loopMode) {
  19631. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19632. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19633. return this.floatInterpolateFunction(startValue, endValue, gradient);
  19634. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19635. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  19636. }
  19637. break;
  19638. case Animation.ANIMATIONTYPE_QUATERNION:
  19639. var quaternion = null;
  19640. switch (loopMode) {
  19641. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19642. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19643. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  19644. break;
  19645. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19646. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19647. break;
  19648. }
  19649. return quaternion;
  19650. case Animation.ANIMATIONTYPE_VECTOR3:
  19651. switch (loopMode) {
  19652. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19653. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19654. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  19655. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19656. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19657. }
  19658. case Animation.ANIMATIONTYPE_VECTOR2:
  19659. switch (loopMode) {
  19660. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19661. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19662. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  19663. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19664. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19665. }
  19666. case Animation.ANIMATIONTYPE_COLOR3:
  19667. switch (loopMode) {
  19668. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19669. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19670. return this.color3InterpolateFunction(startValue, endValue, gradient);
  19671. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19672. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19673. }
  19674. case Animation.ANIMATIONTYPE_MATRIX:
  19675. switch (loopMode) {
  19676. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19677. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19678. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19679. return startValue;
  19680. }
  19681. default:
  19682. break;
  19683. }
  19684. break;
  19685. }
  19686. }
  19687. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  19688. };
  19689. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  19690. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  19691. this._stopped = true;
  19692. return false;
  19693. }
  19694. var returnValue = true;
  19695. // Adding a start key at frame 0 if missing
  19696. if (this._keys[0].frame !== 0) {
  19697. var newKey = { frame: 0, value: this._keys[0].value };
  19698. this._keys.splice(0, 0, newKey);
  19699. }
  19700. // Check limits
  19701. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  19702. from = this._keys[0].frame;
  19703. }
  19704. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  19705. to = this._keys[this._keys.length - 1].frame;
  19706. }
  19707. // Compute ratio
  19708. var range = to - from;
  19709. var offsetValue;
  19710. // ratio represents the frame delta between from and to
  19711. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  19712. var highLimitValue = 0;
  19713. if (ratio > range && !loop) {
  19714. returnValue = false;
  19715. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  19716. }
  19717. else {
  19718. // Get max value if required
  19719. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  19720. var keyOffset = to.toString() + from.toString();
  19721. if (!this._offsetsCache[keyOffset]) {
  19722. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19723. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19724. switch (this.dataType) {
  19725. case Animation.ANIMATIONTYPE_FLOAT:
  19726. this._offsetsCache[keyOffset] = toValue - fromValue;
  19727. break;
  19728. case Animation.ANIMATIONTYPE_QUATERNION:
  19729. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19730. break;
  19731. case Animation.ANIMATIONTYPE_VECTOR3:
  19732. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19733. case Animation.ANIMATIONTYPE_VECTOR2:
  19734. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19735. case Animation.ANIMATIONTYPE_COLOR3:
  19736. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19737. default:
  19738. break;
  19739. }
  19740. this._highLimitsCache[keyOffset] = toValue;
  19741. }
  19742. highLimitValue = this._highLimitsCache[keyOffset];
  19743. offsetValue = this._offsetsCache[keyOffset];
  19744. }
  19745. }
  19746. if (offsetValue === undefined) {
  19747. switch (this.dataType) {
  19748. case Animation.ANIMATIONTYPE_FLOAT:
  19749. offsetValue = 0;
  19750. break;
  19751. case Animation.ANIMATIONTYPE_QUATERNION:
  19752. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  19753. break;
  19754. case Animation.ANIMATIONTYPE_VECTOR3:
  19755. offsetValue = BABYLON.Vector3.Zero();
  19756. break;
  19757. case Animation.ANIMATIONTYPE_VECTOR2:
  19758. offsetValue = BABYLON.Vector2.Zero();
  19759. break;
  19760. case Animation.ANIMATIONTYPE_COLOR3:
  19761. offsetValue = BABYLON.Color3.Black();
  19762. }
  19763. }
  19764. // Compute value
  19765. var repeatCount = (ratio / range) >> 0;
  19766. var currentFrame = returnValue ? from + ratio % range : to;
  19767. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  19768. // Set value
  19769. if (this.targetPropertyPath.length > 1) {
  19770. var property = this._target[this.targetPropertyPath[0]];
  19771. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  19772. property = property[this.targetPropertyPath[index]];
  19773. }
  19774. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  19775. }
  19776. else {
  19777. this._target[this.targetPropertyPath[0]] = currentValue;
  19778. }
  19779. if (this._target.markAsDirty) {
  19780. this._target.markAsDirty(this.targetProperty);
  19781. }
  19782. if (!returnValue) {
  19783. this._stopped = true;
  19784. }
  19785. return returnValue;
  19786. };
  19787. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  19788. get: function () {
  19789. return Animation._ANIMATIONTYPE_FLOAT;
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  19795. get: function () {
  19796. return Animation._ANIMATIONTYPE_VECTOR3;
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  19802. get: function () {
  19803. return Animation._ANIMATIONTYPE_VECTOR2;
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  19809. get: function () {
  19810. return Animation._ANIMATIONTYPE_QUATERNION;
  19811. },
  19812. enumerable: true,
  19813. configurable: true
  19814. });
  19815. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  19816. get: function () {
  19817. return Animation._ANIMATIONTYPE_MATRIX;
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  19823. get: function () {
  19824. return Animation._ANIMATIONTYPE_COLOR3;
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  19830. get: function () {
  19831. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  19837. get: function () {
  19838. return Animation._ANIMATIONLOOPMODE_CYCLE;
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  19844. get: function () {
  19845. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. // Statics
  19851. Animation._ANIMATIONTYPE_FLOAT = 0;
  19852. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  19853. Animation._ANIMATIONTYPE_QUATERNION = 2;
  19854. Animation._ANIMATIONTYPE_MATRIX = 3;
  19855. Animation._ANIMATIONTYPE_COLOR3 = 4;
  19856. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  19857. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  19858. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  19859. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  19860. return Animation;
  19861. })();
  19862. BABYLON.Animation = Animation;
  19863. })(BABYLON || (BABYLON = {}));
  19864. //# sourceMappingURL=babylon.animation.js.map
  19865. var BABYLON;
  19866. (function (BABYLON) {
  19867. var Animatable = (function () {
  19868. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  19869. if (fromFrame === void 0) { fromFrame = 0; }
  19870. if (toFrame === void 0) { toFrame = 100; }
  19871. if (loopAnimation === void 0) { loopAnimation = false; }
  19872. if (speedRatio === void 0) { speedRatio = 1.0; }
  19873. this.target = target;
  19874. this.fromFrame = fromFrame;
  19875. this.toFrame = toFrame;
  19876. this.loopAnimation = loopAnimation;
  19877. this.speedRatio = speedRatio;
  19878. this.onAnimationEnd = onAnimationEnd;
  19879. this._animations = new Array();
  19880. this._paused = false;
  19881. this.animationStarted = false;
  19882. if (animations) {
  19883. this.appendAnimations(target, animations);
  19884. }
  19885. this._scene = scene;
  19886. scene._activeAnimatables.push(this);
  19887. }
  19888. // Methods
  19889. Animatable.prototype.appendAnimations = function (target, animations) {
  19890. for (var index = 0; index < animations.length; index++) {
  19891. var animation = animations[index];
  19892. animation._target = target;
  19893. this._animations.push(animation);
  19894. }
  19895. };
  19896. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  19897. var animations = this._animations;
  19898. for (var index = 0; index < animations.length; index++) {
  19899. if (animations[index].targetProperty === property) {
  19900. return animations[index];
  19901. }
  19902. }
  19903. return null;
  19904. };
  19905. Animatable.prototype.pause = function () {
  19906. if (this._paused) {
  19907. return;
  19908. }
  19909. this._paused = true;
  19910. };
  19911. Animatable.prototype.restart = function () {
  19912. this._paused = false;
  19913. };
  19914. Animatable.prototype.stop = function () {
  19915. var index = this._scene._activeAnimatables.indexOf(this);
  19916. if (index > -1) {
  19917. this._scene._activeAnimatables.splice(index, 1);
  19918. }
  19919. if (this.onAnimationEnd) {
  19920. this.onAnimationEnd();
  19921. }
  19922. };
  19923. Animatable.prototype._animate = function (delay) {
  19924. if (this._paused) {
  19925. if (!this._pausedDelay) {
  19926. this._pausedDelay = delay;
  19927. }
  19928. return true;
  19929. }
  19930. if (!this._localDelayOffset) {
  19931. this._localDelayOffset = delay;
  19932. }
  19933. else if (this._pausedDelay) {
  19934. this._localDelayOffset += delay - this._pausedDelay;
  19935. this._pausedDelay = null;
  19936. }
  19937. // Animating
  19938. var running = false;
  19939. var animations = this._animations;
  19940. for (var index = 0; index < animations.length; index++) {
  19941. var animation = animations[index];
  19942. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  19943. running = running || isRunning;
  19944. }
  19945. if (!running) {
  19946. // Remove from active animatables
  19947. index = this._scene._activeAnimatables.indexOf(this);
  19948. this._scene._activeAnimatables.splice(index, 1);
  19949. }
  19950. if (!running && this.onAnimationEnd) {
  19951. this.onAnimationEnd();
  19952. }
  19953. return running;
  19954. };
  19955. return Animatable;
  19956. })();
  19957. BABYLON.Animatable = Animatable;
  19958. })(BABYLON || (BABYLON = {}));
  19959. //# sourceMappingURL=babylon.animatable.js.map
  19960. var __extends = this.__extends || function (d, b) {
  19961. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19962. function __() { this.constructor = d; }
  19963. __.prototype = b.prototype;
  19964. d.prototype = new __();
  19965. };
  19966. var BABYLON;
  19967. (function (BABYLON) {
  19968. var EasingFunction = (function () {
  19969. function EasingFunction() {
  19970. // Properties
  19971. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  19972. }
  19973. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  19974. get: function () {
  19975. return EasingFunction._EASINGMODE_EASEIN;
  19976. },
  19977. enumerable: true,
  19978. configurable: true
  19979. });
  19980. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  19981. get: function () {
  19982. return EasingFunction._EASINGMODE_EASEOUT;
  19983. },
  19984. enumerable: true,
  19985. configurable: true
  19986. });
  19987. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  19988. get: function () {
  19989. return EasingFunction._EASINGMODE_EASEINOUT;
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. EasingFunction.prototype.setEasingMode = function (easingMode) {
  19995. var n = Math.min(Math.max(easingMode, 0), 2);
  19996. this._easingMode = n;
  19997. };
  19998. EasingFunction.prototype.getEasingMode = function () {
  19999. return this._easingMode;
  20000. };
  20001. EasingFunction.prototype.easeInCore = function (gradient) {
  20002. throw new Error('You must implement this method');
  20003. };
  20004. EasingFunction.prototype.ease = function (gradient) {
  20005. switch (this._easingMode) {
  20006. case EasingFunction.EASINGMODE_EASEIN:
  20007. return this.easeInCore(gradient);
  20008. case EasingFunction.EASINGMODE_EASEOUT:
  20009. return (1 - this.easeInCore(1 - gradient));
  20010. }
  20011. if (gradient >= 0.5) {
  20012. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  20013. }
  20014. return (this.easeInCore(gradient * 2) * 0.5);
  20015. };
  20016. //Statics
  20017. EasingFunction._EASINGMODE_EASEIN = 0;
  20018. EasingFunction._EASINGMODE_EASEOUT = 1;
  20019. EasingFunction._EASINGMODE_EASEINOUT = 2;
  20020. return EasingFunction;
  20021. })();
  20022. BABYLON.EasingFunction = EasingFunction;
  20023. var CircleEase = (function (_super) {
  20024. __extends(CircleEase, _super);
  20025. function CircleEase() {
  20026. _super.apply(this, arguments);
  20027. }
  20028. CircleEase.prototype.easeInCore = function (gradient) {
  20029. gradient = Math.max(0, Math.min(1, gradient));
  20030. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  20031. };
  20032. return CircleEase;
  20033. })(EasingFunction);
  20034. BABYLON.CircleEase = CircleEase;
  20035. var BackEase = (function (_super) {
  20036. __extends(BackEase, _super);
  20037. function BackEase(amplitude) {
  20038. if (amplitude === void 0) { amplitude = 1; }
  20039. _super.call(this);
  20040. this.amplitude = amplitude;
  20041. }
  20042. BackEase.prototype.easeInCore = function (gradient) {
  20043. var num = Math.max(0, this.amplitude);
  20044. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  20045. };
  20046. return BackEase;
  20047. })(EasingFunction);
  20048. BABYLON.BackEase = BackEase;
  20049. var BounceEase = (function (_super) {
  20050. __extends(BounceEase, _super);
  20051. function BounceEase(bounces, bounciness) {
  20052. if (bounces === void 0) { bounces = 3; }
  20053. if (bounciness === void 0) { bounciness = 2; }
  20054. _super.call(this);
  20055. this.bounces = bounces;
  20056. this.bounciness = bounciness;
  20057. }
  20058. BounceEase.prototype.easeInCore = function (gradient) {
  20059. var y = Math.max(0.0, this.bounces);
  20060. var bounciness = this.bounciness;
  20061. if (bounciness <= 1.0) {
  20062. bounciness = 1.001;
  20063. }
  20064. var num9 = Math.pow(bounciness, y);
  20065. var num5 = 1.0 - bounciness;
  20066. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  20067. var num15 = gradient * num4;
  20068. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  20069. var num3 = Math.floor(num65);
  20070. var num13 = num3 + 1.0;
  20071. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  20072. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  20073. var num7 = (num8 + num12) * 0.5;
  20074. var num6 = gradient - num7;
  20075. var num2 = num7 - num8;
  20076. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  20077. };
  20078. return BounceEase;
  20079. })(EasingFunction);
  20080. BABYLON.BounceEase = BounceEase;
  20081. var CubicEase = (function (_super) {
  20082. __extends(CubicEase, _super);
  20083. function CubicEase() {
  20084. _super.apply(this, arguments);
  20085. }
  20086. CubicEase.prototype.easeInCore = function (gradient) {
  20087. return (gradient * gradient * gradient);
  20088. };
  20089. return CubicEase;
  20090. })(EasingFunction);
  20091. BABYLON.CubicEase = CubicEase;
  20092. var ElasticEase = (function (_super) {
  20093. __extends(ElasticEase, _super);
  20094. function ElasticEase(oscillations, springiness) {
  20095. if (oscillations === void 0) { oscillations = 3; }
  20096. if (springiness === void 0) { springiness = 3; }
  20097. _super.call(this);
  20098. this.oscillations = oscillations;
  20099. this.springiness = springiness;
  20100. }
  20101. ElasticEase.prototype.easeInCore = function (gradient) {
  20102. var num2;
  20103. var num3 = Math.max(0.0, this.oscillations);
  20104. var num = Math.max(0.0, this.springiness);
  20105. if (num == 0) {
  20106. num2 = gradient;
  20107. }
  20108. else {
  20109. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  20110. }
  20111. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  20112. };
  20113. return ElasticEase;
  20114. })(EasingFunction);
  20115. BABYLON.ElasticEase = ElasticEase;
  20116. var ExponentialEase = (function (_super) {
  20117. __extends(ExponentialEase, _super);
  20118. function ExponentialEase(exponent) {
  20119. if (exponent === void 0) { exponent = 2; }
  20120. _super.call(this);
  20121. this.exponent = exponent;
  20122. }
  20123. ExponentialEase.prototype.easeInCore = function (gradient) {
  20124. if (this.exponent <= 0) {
  20125. return gradient;
  20126. }
  20127. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  20128. };
  20129. return ExponentialEase;
  20130. })(EasingFunction);
  20131. BABYLON.ExponentialEase = ExponentialEase;
  20132. var PowerEase = (function (_super) {
  20133. __extends(PowerEase, _super);
  20134. function PowerEase(power) {
  20135. if (power === void 0) { power = 2; }
  20136. _super.call(this);
  20137. this.power = power;
  20138. }
  20139. PowerEase.prototype.easeInCore = function (gradient) {
  20140. var y = Math.max(0.0, this.power);
  20141. return Math.pow(gradient, y);
  20142. };
  20143. return PowerEase;
  20144. })(EasingFunction);
  20145. BABYLON.PowerEase = PowerEase;
  20146. var QuadraticEase = (function (_super) {
  20147. __extends(QuadraticEase, _super);
  20148. function QuadraticEase() {
  20149. _super.apply(this, arguments);
  20150. }
  20151. QuadraticEase.prototype.easeInCore = function (gradient) {
  20152. return (gradient * gradient);
  20153. };
  20154. return QuadraticEase;
  20155. })(EasingFunction);
  20156. BABYLON.QuadraticEase = QuadraticEase;
  20157. var QuarticEase = (function (_super) {
  20158. __extends(QuarticEase, _super);
  20159. function QuarticEase() {
  20160. _super.apply(this, arguments);
  20161. }
  20162. QuarticEase.prototype.easeInCore = function (gradient) {
  20163. return (gradient * gradient * gradient * gradient);
  20164. };
  20165. return QuarticEase;
  20166. })(EasingFunction);
  20167. BABYLON.QuarticEase = QuarticEase;
  20168. var QuinticEase = (function (_super) {
  20169. __extends(QuinticEase, _super);
  20170. function QuinticEase() {
  20171. _super.apply(this, arguments);
  20172. }
  20173. QuinticEase.prototype.easeInCore = function (gradient) {
  20174. return (gradient * gradient * gradient * gradient * gradient);
  20175. };
  20176. return QuinticEase;
  20177. })(EasingFunction);
  20178. BABYLON.QuinticEase = QuinticEase;
  20179. var SineEase = (function (_super) {
  20180. __extends(SineEase, _super);
  20181. function SineEase() {
  20182. _super.apply(this, arguments);
  20183. }
  20184. SineEase.prototype.easeInCore = function (gradient) {
  20185. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  20186. };
  20187. return SineEase;
  20188. })(EasingFunction);
  20189. BABYLON.SineEase = SineEase;
  20190. var BezierCurveEase = (function (_super) {
  20191. __extends(BezierCurveEase, _super);
  20192. function BezierCurveEase(x1, y1, x2, y2) {
  20193. if (x1 === void 0) { x1 = 0; }
  20194. if (y1 === void 0) { y1 = 0; }
  20195. if (x2 === void 0) { x2 = 1; }
  20196. if (y2 === void 0) { y2 = 1; }
  20197. _super.call(this);
  20198. this.x1 = x1;
  20199. this.y1 = y1;
  20200. this.x2 = x2;
  20201. this.y2 = y2;
  20202. }
  20203. BezierCurveEase.prototype.easeInCore = function (gradient) {
  20204. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  20205. };
  20206. return BezierCurveEase;
  20207. })(EasingFunction);
  20208. BABYLON.BezierCurveEase = BezierCurveEase;
  20209. })(BABYLON || (BABYLON = {}));
  20210. //# sourceMappingURL=babylon.easing.js.map
  20211. var BABYLON;
  20212. (function (BABYLON) {
  20213. var Octree = (function () {
  20214. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  20215. if (maxDepth === void 0) { maxDepth = 2; }
  20216. this.maxDepth = maxDepth;
  20217. this.dynamicContent = new Array();
  20218. this._maxBlockCapacity = maxBlockCapacity || 64;
  20219. this._selectionContent = new BABYLON.SmartArray(1024);
  20220. this._creationFunc = creationFunc;
  20221. }
  20222. // Methods
  20223. Octree.prototype.update = function (worldMin, worldMax, entries) {
  20224. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  20225. };
  20226. Octree.prototype.addMesh = function (entry) {
  20227. for (var index = 0; index < this.blocks.length; index++) {
  20228. var block = this.blocks[index];
  20229. block.addEntry(entry);
  20230. }
  20231. };
  20232. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  20233. this._selectionContent.reset();
  20234. for (var index = 0; index < this.blocks.length; index++) {
  20235. var block = this.blocks[index];
  20236. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  20237. }
  20238. if (allowDuplicate) {
  20239. this._selectionContent.concat(this.dynamicContent);
  20240. }
  20241. else {
  20242. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20243. }
  20244. return this._selectionContent;
  20245. };
  20246. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  20247. this._selectionContent.reset();
  20248. for (var index = 0; index < this.blocks.length; index++) {
  20249. var block = this.blocks[index];
  20250. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  20251. }
  20252. if (allowDuplicate) {
  20253. this._selectionContent.concat(this.dynamicContent);
  20254. }
  20255. else {
  20256. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20257. }
  20258. return this._selectionContent;
  20259. };
  20260. Octree.prototype.intersectsRay = function (ray) {
  20261. this._selectionContent.reset();
  20262. for (var index = 0; index < this.blocks.length; index++) {
  20263. var block = this.blocks[index];
  20264. block.intersectsRay(ray, this._selectionContent);
  20265. }
  20266. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20267. return this._selectionContent;
  20268. };
  20269. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  20270. target.blocks = new Array();
  20271. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  20272. for (var x = 0; x < 2; x++) {
  20273. for (var y = 0; y < 2; y++) {
  20274. for (var z = 0; z < 2; z++) {
  20275. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  20276. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  20277. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  20278. block.addEntries(entries);
  20279. target.blocks.push(block);
  20280. }
  20281. }
  20282. }
  20283. };
  20284. Octree.CreationFuncForMeshes = function (entry, block) {
  20285. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20286. block.entries.push(entry);
  20287. }
  20288. };
  20289. Octree.CreationFuncForSubMeshes = function (entry, block) {
  20290. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20291. block.entries.push(entry);
  20292. }
  20293. };
  20294. return Octree;
  20295. })();
  20296. BABYLON.Octree = Octree;
  20297. })(BABYLON || (BABYLON = {}));
  20298. //# sourceMappingURL=babylon.octree.js.map
  20299. var BABYLON;
  20300. (function (BABYLON) {
  20301. var OctreeBlock = (function () {
  20302. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  20303. this.entries = new Array();
  20304. this._boundingVectors = new Array();
  20305. this._capacity = capacity;
  20306. this._depth = depth;
  20307. this._maxDepth = maxDepth;
  20308. this._creationFunc = creationFunc;
  20309. this._minPoint = minPoint;
  20310. this._maxPoint = maxPoint;
  20311. this._boundingVectors.push(minPoint.clone());
  20312. this._boundingVectors.push(maxPoint.clone());
  20313. this._boundingVectors.push(minPoint.clone());
  20314. this._boundingVectors[2].x = maxPoint.x;
  20315. this._boundingVectors.push(minPoint.clone());
  20316. this._boundingVectors[3].y = maxPoint.y;
  20317. this._boundingVectors.push(minPoint.clone());
  20318. this._boundingVectors[4].z = maxPoint.z;
  20319. this._boundingVectors.push(maxPoint.clone());
  20320. this._boundingVectors[5].z = minPoint.z;
  20321. this._boundingVectors.push(maxPoint.clone());
  20322. this._boundingVectors[6].x = minPoint.x;
  20323. this._boundingVectors.push(maxPoint.clone());
  20324. this._boundingVectors[7].y = minPoint.y;
  20325. }
  20326. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  20327. // Property
  20328. get: function () {
  20329. return this._capacity;
  20330. },
  20331. enumerable: true,
  20332. configurable: true
  20333. });
  20334. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  20335. get: function () {
  20336. return this._minPoint;
  20337. },
  20338. enumerable: true,
  20339. configurable: true
  20340. });
  20341. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  20342. get: function () {
  20343. return this._maxPoint;
  20344. },
  20345. enumerable: true,
  20346. configurable: true
  20347. });
  20348. // Methods
  20349. OctreeBlock.prototype.addEntry = function (entry) {
  20350. if (this.blocks) {
  20351. for (var index = 0; index < this.blocks.length; index++) {
  20352. var block = this.blocks[index];
  20353. block.addEntry(entry);
  20354. }
  20355. return;
  20356. }
  20357. this._creationFunc(entry, this);
  20358. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  20359. this.createInnerBlocks();
  20360. }
  20361. };
  20362. OctreeBlock.prototype.addEntries = function (entries) {
  20363. for (var index = 0; index < entries.length; index++) {
  20364. var mesh = entries[index];
  20365. this.addEntry(mesh);
  20366. }
  20367. };
  20368. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  20369. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  20370. if (this.blocks) {
  20371. for (var index = 0; index < this.blocks.length; index++) {
  20372. var block = this.blocks[index];
  20373. block.select(frustumPlanes, selection, allowDuplicate);
  20374. }
  20375. return;
  20376. }
  20377. if (allowDuplicate) {
  20378. selection.concat(this.entries);
  20379. }
  20380. else {
  20381. selection.concatWithNoDuplicate(this.entries);
  20382. }
  20383. }
  20384. };
  20385. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  20386. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  20387. if (this.blocks) {
  20388. for (var index = 0; index < this.blocks.length; index++) {
  20389. var block = this.blocks[index];
  20390. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  20391. }
  20392. return;
  20393. }
  20394. if (allowDuplicate) {
  20395. selection.concat(this.entries);
  20396. }
  20397. else {
  20398. selection.concatWithNoDuplicate(this.entries);
  20399. }
  20400. }
  20401. };
  20402. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  20403. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  20404. if (this.blocks) {
  20405. for (var index = 0; index < this.blocks.length; index++) {
  20406. var block = this.blocks[index];
  20407. block.intersectsRay(ray, selection);
  20408. }
  20409. return;
  20410. }
  20411. selection.concatWithNoDuplicate(this.entries);
  20412. }
  20413. };
  20414. OctreeBlock.prototype.createInnerBlocks = function () {
  20415. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  20416. };
  20417. return OctreeBlock;
  20418. })();
  20419. BABYLON.OctreeBlock = OctreeBlock;
  20420. })(BABYLON || (BABYLON = {}));
  20421. //# sourceMappingURL=babylon.octreeBlock.js.map
  20422. var BABYLON;
  20423. (function (BABYLON) {
  20424. var Bone = (function () {
  20425. function Bone(name, skeleton, parentBone, matrix) {
  20426. this.name = name;
  20427. this.children = new Array();
  20428. this.animations = new Array();
  20429. this._worldTransform = new BABYLON.Matrix();
  20430. this._absoluteTransform = new BABYLON.Matrix();
  20431. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  20432. this._skeleton = skeleton;
  20433. this._matrix = matrix;
  20434. this._baseMatrix = matrix;
  20435. skeleton.bones.push(this);
  20436. if (parentBone) {
  20437. this._parent = parentBone;
  20438. parentBone.children.push(this);
  20439. }
  20440. else {
  20441. this._parent = null;
  20442. }
  20443. this._updateDifferenceMatrix();
  20444. }
  20445. // Members
  20446. Bone.prototype.getParent = function () {
  20447. return this._parent;
  20448. };
  20449. Bone.prototype.getLocalMatrix = function () {
  20450. return this._matrix;
  20451. };
  20452. Bone.prototype.getBaseMatrix = function () {
  20453. return this._baseMatrix;
  20454. };
  20455. Bone.prototype.getWorldMatrix = function () {
  20456. return this._worldTransform;
  20457. };
  20458. Bone.prototype.getInvertedAbsoluteTransform = function () {
  20459. return this._invertedAbsoluteTransform;
  20460. };
  20461. Bone.prototype.getAbsoluteMatrix = function () {
  20462. var matrix = this._matrix.clone();
  20463. var parent = this._parent;
  20464. while (parent) {
  20465. matrix = matrix.multiply(parent.getLocalMatrix());
  20466. parent = parent.getParent();
  20467. }
  20468. return matrix;
  20469. };
  20470. // Methods
  20471. Bone.prototype.updateMatrix = function (matrix) {
  20472. this._matrix = matrix;
  20473. this._skeleton._markAsDirty();
  20474. this._updateDifferenceMatrix();
  20475. };
  20476. Bone.prototype._updateDifferenceMatrix = function () {
  20477. if (this._parent) {
  20478. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  20479. }
  20480. else {
  20481. this._absoluteTransform.copyFrom(this._matrix);
  20482. }
  20483. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  20484. for (var index = 0; index < this.children.length; index++) {
  20485. this.children[index]._updateDifferenceMatrix();
  20486. }
  20487. };
  20488. Bone.prototype.markAsDirty = function () {
  20489. this._skeleton._markAsDirty();
  20490. };
  20491. return Bone;
  20492. })();
  20493. BABYLON.Bone = Bone;
  20494. })(BABYLON || (BABYLON = {}));
  20495. //# sourceMappingURL=babylon.bone.js.map
  20496. var BABYLON;
  20497. (function (BABYLON) {
  20498. var Skeleton = (function () {
  20499. function Skeleton(name, id, scene) {
  20500. this.name = name;
  20501. this.id = id;
  20502. this.bones = new Array();
  20503. this._isDirty = true;
  20504. this._identity = BABYLON.Matrix.Identity();
  20505. this.bones = [];
  20506. this._scene = scene;
  20507. scene.skeletons.push(this);
  20508. this.prepare();
  20509. //make sure it will recalculate the matrix next time prepare is called.
  20510. this._isDirty = true;
  20511. }
  20512. // Members
  20513. Skeleton.prototype.getTransformMatrices = function () {
  20514. return this._transformMatrices;
  20515. };
  20516. // Methods
  20517. Skeleton.prototype._markAsDirty = function () {
  20518. this._isDirty = true;
  20519. };
  20520. Skeleton.prototype.prepare = function () {
  20521. if (!this._isDirty) {
  20522. return;
  20523. }
  20524. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  20525. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  20526. }
  20527. for (var index = 0; index < this.bones.length; index++) {
  20528. var bone = this.bones[index];
  20529. var parentBone = bone.getParent();
  20530. if (parentBone) {
  20531. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  20532. }
  20533. else {
  20534. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  20535. }
  20536. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  20537. }
  20538. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  20539. this._isDirty = false;
  20540. this._scene._activeBones += this.bones.length;
  20541. };
  20542. Skeleton.prototype.getAnimatables = function () {
  20543. if (!this._animatables || this._animatables.length !== this.bones.length) {
  20544. this._animatables = [];
  20545. for (var index = 0; index < this.bones.length; index++) {
  20546. this._animatables.push(this.bones[index]);
  20547. }
  20548. }
  20549. return this._animatables;
  20550. };
  20551. Skeleton.prototype.clone = function (name, id) {
  20552. var result = new Skeleton(name, id || name, this._scene);
  20553. for (var index = 0; index < this.bones.length; index++) {
  20554. var source = this.bones[index];
  20555. var parentBone = null;
  20556. if (source.getParent()) {
  20557. var parentIndex = this.bones.indexOf(source.getParent());
  20558. parentBone = result.bones[parentIndex];
  20559. }
  20560. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  20561. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  20562. }
  20563. return result;
  20564. };
  20565. return Skeleton;
  20566. })();
  20567. BABYLON.Skeleton = Skeleton;
  20568. })(BABYLON || (BABYLON = {}));
  20569. //# sourceMappingURL=babylon.skeleton.js.map
  20570. var BABYLON;
  20571. (function (BABYLON) {
  20572. var PostProcess = (function () {
  20573. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  20574. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  20575. this.name = name;
  20576. this.width = -1;
  20577. this.height = -1;
  20578. this._reusable = false;
  20579. this._textures = new BABYLON.SmartArray(2);
  20580. this._currentRenderTextureInd = 0;
  20581. if (camera != null) {
  20582. this._camera = camera;
  20583. this._scene = camera.getScene();
  20584. camera.attachPostProcess(this);
  20585. this._engine = this._scene.getEngine();
  20586. }
  20587. else {
  20588. this._engine = engine;
  20589. }
  20590. this._renderRatio = ratio;
  20591. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  20592. this._reusable = reusable || false;
  20593. samplers = samplers || [];
  20594. samplers.push("textureSampler");
  20595. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  20596. }
  20597. PostProcess.prototype.isReusable = function () {
  20598. return this._reusable;
  20599. };
  20600. PostProcess.prototype.activate = function (camera, sourceTexture) {
  20601. camera = camera || this._camera;
  20602. var scene = camera.getScene();
  20603. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  20604. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  20605. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  20606. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  20607. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  20608. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  20609. if (this._textures.length > 0) {
  20610. for (var i = 0; i < this._textures.length; i++) {
  20611. this._engine._releaseTexture(this._textures.data[i]);
  20612. }
  20613. this._textures.reset();
  20614. }
  20615. this.width = desiredWidth;
  20616. this.height = desiredHeight;
  20617. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  20618. if (this._reusable) {
  20619. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  20620. }
  20621. if (this.onSizeChanged) {
  20622. this.onSizeChanged();
  20623. }
  20624. }
  20625. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  20626. if (this.onActivate) {
  20627. this.onActivate(camera);
  20628. }
  20629. // Clear
  20630. if (this.clearColor) {
  20631. this._engine.clear(this.clearColor, true, true);
  20632. }
  20633. else {
  20634. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  20635. }
  20636. if (this._reusable) {
  20637. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  20638. }
  20639. };
  20640. PostProcess.prototype.apply = function () {
  20641. // Check
  20642. if (!this._effect.isReady())
  20643. return null;
  20644. // States
  20645. this._engine.enableEffect(this._effect);
  20646. this._engine.setState(false);
  20647. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20648. this._engine.setDepthBuffer(false);
  20649. this._engine.setDepthWrite(false);
  20650. // Texture
  20651. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  20652. // Parameters
  20653. if (this.onApply) {
  20654. this.onApply(this._effect);
  20655. }
  20656. return this._effect;
  20657. };
  20658. PostProcess.prototype.dispose = function (camera) {
  20659. camera = camera || this._camera;
  20660. if (this._textures.length > 0) {
  20661. for (var i = 0; i < this._textures.length; i++) {
  20662. this._engine._releaseTexture(this._textures.data[i]);
  20663. }
  20664. this._textures.reset();
  20665. }
  20666. if (!camera) {
  20667. return;
  20668. }
  20669. camera.detachPostProcess(this);
  20670. var index = camera._postProcesses.indexOf(this);
  20671. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  20672. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  20673. }
  20674. };
  20675. return PostProcess;
  20676. })();
  20677. BABYLON.PostProcess = PostProcess;
  20678. })(BABYLON || (BABYLON = {}));
  20679. //# sourceMappingURL=babylon.postProcess.js.map
  20680. var BABYLON;
  20681. (function (BABYLON) {
  20682. var PostProcessManager = (function () {
  20683. function PostProcessManager(scene) {
  20684. this._vertexDeclaration = [2];
  20685. this._vertexStrideSize = 2 * 4;
  20686. this._scene = scene;
  20687. }
  20688. PostProcessManager.prototype._prepareBuffers = function () {
  20689. if (this._vertexBuffer) {
  20690. return;
  20691. }
  20692. // VBO
  20693. var vertices = [];
  20694. vertices.push(1, 1);
  20695. vertices.push(-1, 1);
  20696. vertices.push(-1, -1);
  20697. vertices.push(1, -1);
  20698. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  20699. // Indices
  20700. var indices = [];
  20701. indices.push(0);
  20702. indices.push(1);
  20703. indices.push(2);
  20704. indices.push(0);
  20705. indices.push(2);
  20706. indices.push(3);
  20707. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  20708. };
  20709. // Methods
  20710. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  20711. var postProcesses = this._scene.activeCamera._postProcesses;
  20712. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20713. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20714. return false;
  20715. }
  20716. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  20717. return true;
  20718. };
  20719. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  20720. var engine = this._scene.getEngine();
  20721. for (var index = 0; index < postProcesses.length; index++) {
  20722. if (index < postProcesses.length - 1) {
  20723. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  20724. }
  20725. else {
  20726. if (targetTexture) {
  20727. engine.bindFramebuffer(targetTexture);
  20728. }
  20729. else {
  20730. engine.restoreDefaultFramebuffer();
  20731. }
  20732. }
  20733. var pp = postProcesses[index];
  20734. var effect = pp.apply();
  20735. if (effect) {
  20736. if (pp.onBeforeRender) {
  20737. pp.onBeforeRender(effect);
  20738. }
  20739. // VBOs
  20740. this._prepareBuffers();
  20741. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20742. // Draw order
  20743. engine.draw(true, 0, 6);
  20744. }
  20745. }
  20746. // Restore depth buffer
  20747. engine.setDepthBuffer(true);
  20748. engine.setDepthWrite(true);
  20749. };
  20750. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  20751. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  20752. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20753. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20754. return;
  20755. }
  20756. var engine = this._scene.getEngine();
  20757. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  20758. if (index < postProcessesTakenIndices.length - 1) {
  20759. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  20760. }
  20761. else {
  20762. if (targetTexture) {
  20763. engine.bindFramebuffer(targetTexture);
  20764. }
  20765. else {
  20766. engine.restoreDefaultFramebuffer();
  20767. }
  20768. }
  20769. if (doNotPresent) {
  20770. break;
  20771. }
  20772. var pp = postProcesses[postProcessesTakenIndices[index]];
  20773. var effect = pp.apply();
  20774. if (effect) {
  20775. if (pp.onBeforeRender) {
  20776. pp.onBeforeRender(effect);
  20777. }
  20778. // VBOs
  20779. this._prepareBuffers();
  20780. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20781. // Draw order
  20782. engine.draw(true, 0, 6);
  20783. }
  20784. }
  20785. // Restore depth buffer
  20786. engine.setDepthBuffer(true);
  20787. engine.setDepthWrite(true);
  20788. };
  20789. PostProcessManager.prototype.dispose = function () {
  20790. if (this._vertexBuffer) {
  20791. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20792. this._vertexBuffer = null;
  20793. }
  20794. if (this._indexBuffer) {
  20795. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20796. this._indexBuffer = null;
  20797. }
  20798. };
  20799. return PostProcessManager;
  20800. })();
  20801. BABYLON.PostProcessManager = PostProcessManager;
  20802. })(BABYLON || (BABYLON = {}));
  20803. //# sourceMappingURL=babylon.postProcessManager.js.map
  20804. var __extends = this.__extends || function (d, b) {
  20805. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20806. function __() { this.constructor = d; }
  20807. __.prototype = b.prototype;
  20808. d.prototype = new __();
  20809. };
  20810. var BABYLON;
  20811. (function (BABYLON) {
  20812. var PassPostProcess = (function (_super) {
  20813. __extends(PassPostProcess, _super);
  20814. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20815. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  20816. }
  20817. return PassPostProcess;
  20818. })(BABYLON.PostProcess);
  20819. BABYLON.PassPostProcess = PassPostProcess;
  20820. })(BABYLON || (BABYLON = {}));
  20821. //# sourceMappingURL=babylon.passPostProcess.js.map
  20822. var __extends = this.__extends || function (d, b) {
  20823. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20824. function __() { this.constructor = d; }
  20825. __.prototype = b.prototype;
  20826. d.prototype = new __();
  20827. };
  20828. var BABYLON;
  20829. (function (BABYLON) {
  20830. var BlurPostProcess = (function (_super) {
  20831. __extends(BlurPostProcess, _super);
  20832. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  20833. var _this = this;
  20834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  20835. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  20836. this.direction = direction;
  20837. this.blurWidth = blurWidth;
  20838. this.onApply = function (effect) {
  20839. effect.setFloat2("screenSize", _this.width, _this.height);
  20840. effect.setVector2("direction", _this.direction);
  20841. effect.setFloat("blurWidth", _this.blurWidth);
  20842. };
  20843. }
  20844. return BlurPostProcess;
  20845. })(BABYLON.PostProcess);
  20846. BABYLON.BlurPostProcess = BlurPostProcess;
  20847. })(BABYLON || (BABYLON = {}));
  20848. //# sourceMappingURL=babylon.blurPostProcess.js.map
  20849. var __extends = this.__extends || function (d, b) {
  20850. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20851. function __() { this.constructor = d; }
  20852. __.prototype = b.prototype;
  20853. d.prototype = new __();
  20854. };
  20855. var BABYLON;
  20856. (function (BABYLON) {
  20857. var RefractionPostProcess = (function (_super) {
  20858. __extends(RefractionPostProcess, _super);
  20859. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  20860. var _this = this;
  20861. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  20862. this.color = color;
  20863. this.depth = depth;
  20864. this.colorLevel = colorLevel;
  20865. this.onActivate = function (cam) {
  20866. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  20867. };
  20868. this.onApply = function (effect) {
  20869. effect.setColor3("baseColor", _this.color);
  20870. effect.setFloat("depth", _this.depth);
  20871. effect.setFloat("colorLevel", _this.colorLevel);
  20872. effect.setTexture("refractionSampler", _this._refRexture);
  20873. };
  20874. }
  20875. // Methods
  20876. RefractionPostProcess.prototype.dispose = function (camera) {
  20877. if (this._refRexture) {
  20878. this._refRexture.dispose();
  20879. }
  20880. _super.prototype.dispose.call(this, camera);
  20881. };
  20882. return RefractionPostProcess;
  20883. })(BABYLON.PostProcess);
  20884. BABYLON.RefractionPostProcess = RefractionPostProcess;
  20885. })(BABYLON || (BABYLON = {}));
  20886. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  20887. var __extends = this.__extends || function (d, b) {
  20888. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20889. function __() { this.constructor = d; }
  20890. __.prototype = b.prototype;
  20891. d.prototype = new __();
  20892. };
  20893. var BABYLON;
  20894. (function (BABYLON) {
  20895. var BlackAndWhitePostProcess = (function (_super) {
  20896. __extends(BlackAndWhitePostProcess, _super);
  20897. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20898. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  20899. }
  20900. return BlackAndWhitePostProcess;
  20901. })(BABYLON.PostProcess);
  20902. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  20903. })(BABYLON || (BABYLON = {}));
  20904. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  20905. var __extends = this.__extends || function (d, b) {
  20906. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20907. function __() { this.constructor = d; }
  20908. __.prototype = b.prototype;
  20909. d.prototype = new __();
  20910. };
  20911. var BABYLON;
  20912. (function (BABYLON) {
  20913. var ConvolutionPostProcess = (function (_super) {
  20914. __extends(ConvolutionPostProcess, _super);
  20915. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  20916. var _this = this;
  20917. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  20918. this.kernel = kernel;
  20919. this.onApply = function (effect) {
  20920. effect.setFloat2("screenSize", _this.width, _this.height);
  20921. effect.setArray("kernel", _this.kernel);
  20922. };
  20923. }
  20924. // Statics
  20925. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  20926. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  20927. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  20928. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  20929. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  20930. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  20931. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  20932. return ConvolutionPostProcess;
  20933. })(BABYLON.PostProcess);
  20934. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  20935. })(BABYLON || (BABYLON = {}));
  20936. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  20937. var __extends = this.__extends || function (d, b) {
  20938. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20939. function __() { this.constructor = d; }
  20940. __.prototype = b.prototype;
  20941. d.prototype = new __();
  20942. };
  20943. var BABYLON;
  20944. (function (BABYLON) {
  20945. var FilterPostProcess = (function (_super) {
  20946. __extends(FilterPostProcess, _super);
  20947. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  20948. var _this = this;
  20949. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  20950. this.kernelMatrix = kernelMatrix;
  20951. this.onApply = function (effect) {
  20952. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  20953. };
  20954. }
  20955. return FilterPostProcess;
  20956. })(BABYLON.PostProcess);
  20957. BABYLON.FilterPostProcess = FilterPostProcess;
  20958. })(BABYLON || (BABYLON = {}));
  20959. //# sourceMappingURL=babylon.filterPostProcess.js.map
  20960. var __extends = this.__extends || function (d, b) {
  20961. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20962. function __() { this.constructor = d; }
  20963. __.prototype = b.prototype;
  20964. d.prototype = new __();
  20965. };
  20966. var BABYLON;
  20967. (function (BABYLON) {
  20968. var FxaaPostProcess = (function (_super) {
  20969. __extends(FxaaPostProcess, _super);
  20970. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20971. var _this = this;
  20972. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  20973. this.onSizeChanged = function () {
  20974. _this.texelWidth = 1.0 / _this.width;
  20975. _this.texelHeight = 1.0 / _this.height;
  20976. };
  20977. this.onApply = function (effect) {
  20978. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  20979. };
  20980. }
  20981. return FxaaPostProcess;
  20982. })(BABYLON.PostProcess);
  20983. BABYLON.FxaaPostProcess = FxaaPostProcess;
  20984. })(BABYLON || (BABYLON = {}));
  20985. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  20986. var BABYLON;
  20987. (function (BABYLON) {
  20988. var LensFlare = (function () {
  20989. function LensFlare(size, position, color, imgUrl, system) {
  20990. this.size = size;
  20991. this.position = position;
  20992. this.dispose = function () {
  20993. if (this.texture) {
  20994. this.texture.dispose();
  20995. }
  20996. // Remove from scene
  20997. var index = this._system.lensFlares.indexOf(this);
  20998. this._system.lensFlares.splice(index, 1);
  20999. };
  21000. this.color = color || new BABYLON.Color3(1, 1, 1);
  21001. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  21002. this._system = system;
  21003. system.lensFlares.push(this);
  21004. }
  21005. return LensFlare;
  21006. })();
  21007. BABYLON.LensFlare = LensFlare;
  21008. })(BABYLON || (BABYLON = {}));
  21009. //# sourceMappingURL=babylon.lensFlare.js.map
  21010. var BABYLON;
  21011. (function (BABYLON) {
  21012. var LensFlareSystem = (function () {
  21013. function LensFlareSystem(name, emitter, scene) {
  21014. this.name = name;
  21015. this.lensFlares = new Array();
  21016. this.borderLimit = 300;
  21017. this._vertexDeclaration = [2];
  21018. this._vertexStrideSize = 2 * 4;
  21019. this._isEnabled = true;
  21020. this._scene = scene;
  21021. this._emitter = emitter;
  21022. scene.lensFlareSystems.push(this);
  21023. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  21024. // VBO
  21025. var vertices = [];
  21026. vertices.push(1, 1);
  21027. vertices.push(-1, 1);
  21028. vertices.push(-1, -1);
  21029. vertices.push(1, -1);
  21030. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21031. // Indices
  21032. var indices = [];
  21033. indices.push(0);
  21034. indices.push(1);
  21035. indices.push(2);
  21036. indices.push(0);
  21037. indices.push(2);
  21038. indices.push(3);
  21039. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21040. // Effects
  21041. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  21042. }
  21043. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  21044. get: function () {
  21045. return this._isEnabled;
  21046. },
  21047. set: function (value) {
  21048. this._isEnabled = value;
  21049. },
  21050. enumerable: true,
  21051. configurable: true
  21052. });
  21053. LensFlareSystem.prototype.getScene = function () {
  21054. return this._scene;
  21055. };
  21056. LensFlareSystem.prototype.getEmitter = function () {
  21057. return this._emitter;
  21058. };
  21059. LensFlareSystem.prototype.getEmitterPosition = function () {
  21060. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  21061. };
  21062. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  21063. var position = this.getEmitterPosition();
  21064. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  21065. this._positionX = position.x;
  21066. this._positionY = position.y;
  21067. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  21068. if (position.z > 0) {
  21069. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  21070. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  21071. return true;
  21072. }
  21073. }
  21074. return false;
  21075. };
  21076. LensFlareSystem.prototype._isVisible = function () {
  21077. if (!this._isEnabled) {
  21078. return false;
  21079. }
  21080. var emitterPosition = this.getEmitterPosition();
  21081. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  21082. var distance = direction.length();
  21083. direction.normalize();
  21084. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  21085. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  21086. return !pickInfo.hit || pickInfo.distance > distance;
  21087. };
  21088. LensFlareSystem.prototype.render = function () {
  21089. if (!this._effect.isReady())
  21090. return false;
  21091. var engine = this._scene.getEngine();
  21092. var viewport = this._scene.activeCamera.viewport;
  21093. var globalViewport = viewport.toGlobal(engine);
  21094. // Position
  21095. if (!this.computeEffectivePosition(globalViewport)) {
  21096. return false;
  21097. }
  21098. // Visibility
  21099. if (!this._isVisible()) {
  21100. return false;
  21101. }
  21102. // Intensity
  21103. var awayX;
  21104. var awayY;
  21105. if (this._positionX < this.borderLimit + globalViewport.x) {
  21106. awayX = this.borderLimit + globalViewport.x - this._positionX;
  21107. }
  21108. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  21109. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  21110. }
  21111. else {
  21112. awayX = 0;
  21113. }
  21114. if (this._positionY < this.borderLimit + globalViewport.y) {
  21115. awayY = this.borderLimit + globalViewport.y - this._positionY;
  21116. }
  21117. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  21118. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  21119. }
  21120. else {
  21121. awayY = 0;
  21122. }
  21123. var away = (awayX > awayY) ? awayX : awayY;
  21124. if (away > this.borderLimit) {
  21125. away = this.borderLimit;
  21126. }
  21127. var intensity = 1.0 - (away / this.borderLimit);
  21128. if (intensity < 0) {
  21129. return false;
  21130. }
  21131. if (intensity > 1.0) {
  21132. intensity = 1.0;
  21133. }
  21134. // Position
  21135. var centerX = globalViewport.x + globalViewport.width / 2;
  21136. var centerY = globalViewport.y + globalViewport.height / 2;
  21137. var distX = centerX - this._positionX;
  21138. var distY = centerY - this._positionY;
  21139. // Effects
  21140. engine.enableEffect(this._effect);
  21141. engine.setState(false);
  21142. engine.setDepthBuffer(false);
  21143. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  21144. // VBOs
  21145. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21146. for (var index = 0; index < this.lensFlares.length; index++) {
  21147. var flare = this.lensFlares[index];
  21148. var x = centerX - (distX * flare.position);
  21149. var y = centerY - (distY * flare.position);
  21150. var cw = flare.size;
  21151. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  21152. var cx = 2 * (x / globalViewport.width) - 1.0;
  21153. var cy = 1.0 - 2 * (y / globalViewport.height);
  21154. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  21155. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  21156. // Texture
  21157. this._effect.setTexture("textureSampler", flare.texture);
  21158. // Color
  21159. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  21160. // Draw order
  21161. engine.draw(true, 0, 6);
  21162. }
  21163. engine.setDepthBuffer(true);
  21164. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21165. return true;
  21166. };
  21167. LensFlareSystem.prototype.dispose = function () {
  21168. if (this._vertexBuffer) {
  21169. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21170. this._vertexBuffer = null;
  21171. }
  21172. if (this._indexBuffer) {
  21173. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21174. this._indexBuffer = null;
  21175. }
  21176. while (this.lensFlares.length) {
  21177. this.lensFlares[0].dispose();
  21178. }
  21179. // Remove from scene
  21180. var index = this._scene.lensFlareSystems.indexOf(this);
  21181. this._scene.lensFlareSystems.splice(index, 1);
  21182. };
  21183. return LensFlareSystem;
  21184. })();
  21185. BABYLON.LensFlareSystem = LensFlareSystem;
  21186. })(BABYLON || (BABYLON = {}));
  21187. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  21188. var BABYLON;
  21189. (function (BABYLON) {
  21190. var CannonJSPlugin = (function () {
  21191. function CannonJSPlugin() {
  21192. this._registeredMeshes = [];
  21193. this._physicsMaterials = [];
  21194. this.updateBodyPosition = function (mesh) {
  21195. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21196. var registeredMesh = this._registeredMeshes[index];
  21197. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21198. var body = registeredMesh.body;
  21199. var center = mesh.getBoundingInfo().boundingBox.center;
  21200. body.position.set(center.x, center.z, center.y);
  21201. body.quaternion.x = mesh.rotationQuaternion.x;
  21202. body.quaternion.z = mesh.rotationQuaternion.y;
  21203. body.quaternion.y = mesh.rotationQuaternion.z;
  21204. body.quaternion.w = -mesh.rotationQuaternion.w;
  21205. return;
  21206. }
  21207. }
  21208. };
  21209. }
  21210. CannonJSPlugin.prototype.initialize = function (iterations) {
  21211. if (iterations === void 0) { iterations = 10; }
  21212. this._world = new CANNON.World();
  21213. this._world.broadphase = new CANNON.NaiveBroadphase();
  21214. this._world.solver.iterations = iterations;
  21215. };
  21216. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21217. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21218. };
  21219. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21220. this._world.step(delta);
  21221. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21222. var registeredMesh = this._registeredMeshes[index];
  21223. if (registeredMesh.isChild) {
  21224. continue;
  21225. }
  21226. // Body position
  21227. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21228. var deltaPos = registeredMesh.delta;
  21229. if (deltaPos) {
  21230. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21231. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21232. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21233. }
  21234. else {
  21235. registeredMesh.mesh.position.x = bodyX;
  21236. registeredMesh.mesh.position.y = bodyZ;
  21237. registeredMesh.mesh.position.z = bodyY;
  21238. }
  21239. if (!registeredMesh.mesh.rotationQuaternion) {
  21240. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21241. }
  21242. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21243. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21244. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21245. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21246. }
  21247. };
  21248. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21249. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21250. };
  21251. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21252. this.unregisterMesh(mesh);
  21253. mesh.computeWorldMatrix(true);
  21254. switch (impostor) {
  21255. case BABYLON.PhysicsEngine.SphereImpostor:
  21256. var bbox = mesh.getBoundingInfo().boundingBox;
  21257. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21258. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21259. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21260. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21261. case BABYLON.PhysicsEngine.BoxImpostor:
  21262. bbox = mesh.getBoundingInfo().boundingBox;
  21263. var min = bbox.minimumWorld;
  21264. var max = bbox.maximumWorld;
  21265. var box = max.subtract(min).scale(0.5);
  21266. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21267. case BABYLON.PhysicsEngine.PlaneImpostor:
  21268. return this._createPlane(mesh, options);
  21269. case BABYLON.PhysicsEngine.MeshImpostor:
  21270. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21271. var rawFaces = mesh.getIndices();
  21272. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21273. }
  21274. return null;
  21275. };
  21276. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21277. var shape = new CANNON.Sphere(radius);
  21278. if (!options) {
  21279. return shape;
  21280. }
  21281. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21282. };
  21283. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21284. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21285. if (!options) {
  21286. return shape;
  21287. }
  21288. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21289. };
  21290. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21291. var shape = new CANNON.Plane();
  21292. if (!options) {
  21293. return shape;
  21294. }
  21295. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21296. };
  21297. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21298. var verts = [], faces = [];
  21299. mesh.computeWorldMatrix(true);
  21300. for (var i = 0; i < rawVerts.length; i += 3) {
  21301. var transformed = BABYLON.Vector3.Zero();
  21302. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21303. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21304. }
  21305. for (var j = 0; j < rawFaces.length; j += 3) {
  21306. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21307. }
  21308. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21309. if (!options) {
  21310. return shape;
  21311. }
  21312. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21313. };
  21314. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21315. var index;
  21316. var mat;
  21317. for (index = 0; index < this._physicsMaterials.length; index++) {
  21318. mat = this._physicsMaterials[index];
  21319. if (mat.friction === friction && mat.restitution === restitution) {
  21320. return mat;
  21321. }
  21322. }
  21323. var currentMat = new CANNON.Material();
  21324. currentMat.friction = friction;
  21325. currentMat.restitution = restitution;
  21326. this._physicsMaterials.push(currentMat);
  21327. for (index = 0; index < this._physicsMaterials.length; index++) {
  21328. mat = this._physicsMaterials[index];
  21329. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21330. contactMaterial.contactEquationStiffness = 1e10;
  21331. contactMaterial.contactEquationRegularizationTime = 10;
  21332. this._world.addContactMaterial(contactMaterial);
  21333. }
  21334. return currentMat;
  21335. };
  21336. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21337. var initialRotation = null;
  21338. if (mesh.rotationQuaternion) {
  21339. initialRotation = mesh.rotationQuaternion.clone();
  21340. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21341. }
  21342. // The delta between the mesh position and the mesh bounding box center
  21343. var bbox = mesh.getBoundingInfo().boundingBox;
  21344. var deltaPosition = mesh.position.subtract(bbox.center);
  21345. var material = this._addMaterial(friction, restitution);
  21346. var body = new CANNON.RigidBody(mass, shape, material);
  21347. if (initialRotation) {
  21348. body.quaternion.x = initialRotation.x;
  21349. body.quaternion.z = initialRotation.y;
  21350. body.quaternion.y = initialRotation.z;
  21351. body.quaternion.w = -initialRotation.w;
  21352. }
  21353. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21354. this._world.add(body);
  21355. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21356. return body;
  21357. };
  21358. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21359. var compoundShape = new CANNON.Compound();
  21360. for (var index = 0; index < parts.length; index++) {
  21361. var mesh = parts[index].mesh;
  21362. var shape = this.registerMesh(mesh, parts[index].impostor);
  21363. if (index == 0) {
  21364. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21365. }
  21366. else {
  21367. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21368. }
  21369. }
  21370. var initialMesh = parts[0].mesh;
  21371. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21372. body.parts = parts;
  21373. return body;
  21374. };
  21375. CannonJSPlugin.prototype._unbindBody = function (body) {
  21376. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21377. var registeredMesh = this._registeredMeshes[index];
  21378. if (registeredMesh.body === body) {
  21379. registeredMesh.body = null;
  21380. registeredMesh.delta = 0;
  21381. }
  21382. }
  21383. };
  21384. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21385. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21386. var registeredMesh = this._registeredMeshes[index];
  21387. if (registeredMesh.mesh === mesh) {
  21388. // Remove body
  21389. if (registeredMesh.body) {
  21390. this._world.remove(registeredMesh.body);
  21391. this._unbindBody(registeredMesh.body);
  21392. }
  21393. this._registeredMeshes.splice(index, 1);
  21394. return;
  21395. }
  21396. }
  21397. };
  21398. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21399. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21400. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21401. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21402. var registeredMesh = this._registeredMeshes[index];
  21403. if (registeredMesh.mesh === mesh) {
  21404. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21405. return;
  21406. }
  21407. }
  21408. };
  21409. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21410. var body1 = null, body2 = null;
  21411. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21412. var registeredMesh = this._registeredMeshes[index];
  21413. if (registeredMesh.mesh === mesh1) {
  21414. body1 = registeredMesh.body;
  21415. }
  21416. else if (registeredMesh.mesh === mesh2) {
  21417. body2 = registeredMesh.body;
  21418. }
  21419. }
  21420. if (!body1 || !body2) {
  21421. return false;
  21422. }
  21423. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  21424. this._world.addConstraint(constraint);
  21425. return true;
  21426. };
  21427. CannonJSPlugin.prototype.dispose = function () {
  21428. while (this._registeredMeshes.length) {
  21429. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21430. }
  21431. };
  21432. CannonJSPlugin.prototype.isSupported = function () {
  21433. return window.CANNON !== undefined;
  21434. };
  21435. return CannonJSPlugin;
  21436. })();
  21437. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21438. })(BABYLON || (BABYLON = {}));
  21439. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21440. var BABYLON;
  21441. (function (BABYLON) {
  21442. var OimoJSPlugin = (function () {
  21443. function OimoJSPlugin() {
  21444. this._registeredMeshes = [];
  21445. /**
  21446. * Update the body position according to the mesh position
  21447. * @param mesh
  21448. */
  21449. this.updateBodyPosition = function (mesh) {
  21450. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21451. var registeredMesh = this._registeredMeshes[index];
  21452. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21453. var body = registeredMesh.body.body;
  21454. mesh.computeWorldMatrix(true);
  21455. var center = mesh.getBoundingInfo().boundingBox.center;
  21456. body.setPosition(center.x, center.y, center.z);
  21457. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  21458. return;
  21459. }
  21460. // Case where the parent has been updated
  21461. if (registeredMesh.mesh.parent === mesh) {
  21462. mesh.computeWorldMatrix(true);
  21463. registeredMesh.mesh.computeWorldMatrix(true);
  21464. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  21465. var absoluteRotation = mesh.rotation;
  21466. body = registeredMesh.body.body;
  21467. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  21468. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  21469. return;
  21470. }
  21471. }
  21472. };
  21473. }
  21474. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  21475. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21476. };
  21477. OimoJSPlugin.prototype.initialize = function (iterations) {
  21478. this._world = new OIMO.World();
  21479. this._world.clear();
  21480. };
  21481. OimoJSPlugin.prototype.setGravity = function (gravity) {
  21482. this._world.gravity = gravity;
  21483. };
  21484. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21485. var body = null;
  21486. this.unregisterMesh(mesh);
  21487. mesh.computeWorldMatrix(true);
  21488. var initialRotation = null;
  21489. if (mesh.rotationQuaternion) {
  21490. initialRotation = mesh.rotationQuaternion.clone();
  21491. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21492. mesh.computeWorldMatrix(true);
  21493. }
  21494. var bbox = mesh.getBoundingInfo().boundingBox;
  21495. // The delta between the mesh position and the mesh bounding box center
  21496. var deltaPosition = mesh.position.subtract(bbox.center);
  21497. // Transform delta position with the rotation
  21498. if (initialRotation) {
  21499. var m = new BABYLON.Matrix();
  21500. initialRotation.toRotationMatrix(m);
  21501. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  21502. }
  21503. switch (impostor) {
  21504. case BABYLON.PhysicsEngine.SphereImpostor:
  21505. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21506. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21507. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21508. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21509. body = new OIMO.Body({
  21510. type: 'sphere',
  21511. size: [size],
  21512. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21513. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21514. move: options.mass != 0,
  21515. config: [options.mass, options.friction, options.restitution],
  21516. world: this._world
  21517. });
  21518. break;
  21519. case BABYLON.PhysicsEngine.PlaneImpostor:
  21520. case BABYLON.PhysicsEngine.CylinderImpostor:
  21521. case BABYLON.PhysicsEngine.BoxImpostor:
  21522. var min = bbox.minimumWorld;
  21523. var max = bbox.maximumWorld;
  21524. var box = max.subtract(min);
  21525. var sizeX = this._checkWithEpsilon(box.x);
  21526. var sizeY = this._checkWithEpsilon(box.y);
  21527. var sizeZ = this._checkWithEpsilon(box.z);
  21528. body = new OIMO.Body({
  21529. type: 'box',
  21530. size: [sizeX, sizeY, sizeZ],
  21531. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21532. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21533. move: options.mass != 0,
  21534. config: [options.mass, options.friction, options.restitution],
  21535. world: this._world
  21536. });
  21537. break;
  21538. }
  21539. //If quaternion was set as the rotation of the object
  21540. if (initialRotation) {
  21541. //We have to access the rigid body's properties to set the quaternion.
  21542. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  21543. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  21544. //update the internal rotation matrix
  21545. body.body.syncShapes();
  21546. }
  21547. this._registeredMeshes.push({
  21548. mesh: mesh,
  21549. body: body,
  21550. delta: deltaPosition
  21551. });
  21552. return body;
  21553. };
  21554. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21555. var types = [], sizes = [], positions = [], rotations = [];
  21556. var initialMesh = parts[0].mesh;
  21557. for (var index = 0; index < parts.length; index++) {
  21558. var part = parts[index];
  21559. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  21560. types.push(bodyParameters.type);
  21561. sizes.push.apply(sizes, bodyParameters.size);
  21562. positions.push.apply(positions, bodyParameters.pos);
  21563. rotations.push.apply(rotations, bodyParameters.rot);
  21564. }
  21565. var body = new OIMO.Body({
  21566. type: types,
  21567. size: sizes,
  21568. pos: positions,
  21569. rot: rotations,
  21570. move: options.mass != 0,
  21571. config: [options.mass, options.friction, options.restitution],
  21572. world: this._world
  21573. });
  21574. this._registeredMeshes.push({
  21575. mesh: initialMesh,
  21576. body: body
  21577. });
  21578. return body;
  21579. };
  21580. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  21581. var bodyParameters = null;
  21582. var mesh = part.mesh;
  21583. // We need the bounding box/sphere info to compute the physics body
  21584. mesh.computeWorldMatrix();
  21585. switch (part.impostor) {
  21586. case BABYLON.PhysicsEngine.SphereImpostor:
  21587. var bbox = mesh.getBoundingInfo().boundingBox;
  21588. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21589. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21590. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21591. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21592. bodyParameters = {
  21593. type: 'sphere',
  21594. /* bug with oimo : sphere needs 3 sizes in this case */
  21595. size: [size, -1, -1],
  21596. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  21597. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  21598. };
  21599. break;
  21600. case BABYLON.PhysicsEngine.PlaneImpostor:
  21601. case BABYLON.PhysicsEngine.BoxImpostor:
  21602. bbox = mesh.getBoundingInfo().boundingBox;
  21603. var min = bbox.minimumWorld;
  21604. var max = bbox.maximumWorld;
  21605. var box = max.subtract(min);
  21606. var sizeX = this._checkWithEpsilon(box.x);
  21607. var sizeY = this._checkWithEpsilon(box.y);
  21608. var sizeZ = this._checkWithEpsilon(box.z);
  21609. var relativePosition = mesh.position;
  21610. bodyParameters = {
  21611. type: 'box',
  21612. size: [sizeX, sizeY, sizeZ],
  21613. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  21614. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  21615. };
  21616. break;
  21617. }
  21618. return bodyParameters;
  21619. };
  21620. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  21621. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21622. var registeredMesh = this._registeredMeshes[index];
  21623. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21624. if (registeredMesh.body) {
  21625. this._world.removeRigidBody(registeredMesh.body.body);
  21626. this._unbindBody(registeredMesh.body);
  21627. }
  21628. this._registeredMeshes.splice(index, 1);
  21629. return;
  21630. }
  21631. }
  21632. };
  21633. OimoJSPlugin.prototype._unbindBody = function (body) {
  21634. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21635. var registeredMesh = this._registeredMeshes[index];
  21636. if (registeredMesh.body === body) {
  21637. registeredMesh.body = null;
  21638. }
  21639. }
  21640. };
  21641. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21642. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21643. var registeredMesh = this._registeredMeshes[index];
  21644. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21645. // Get object mass to have a behaviour similar to cannon.js
  21646. var mass = registeredMesh.body.body.massInfo.mass;
  21647. // The force is scaled with the mass of object
  21648. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  21649. return;
  21650. }
  21651. }
  21652. };
  21653. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21654. var body1 = null, body2 = null;
  21655. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21656. var registeredMesh = this._registeredMeshes[index];
  21657. if (registeredMesh.mesh === mesh1) {
  21658. body1 = registeredMesh.body.body;
  21659. }
  21660. else if (registeredMesh.mesh === mesh2) {
  21661. body2 = registeredMesh.body.body;
  21662. }
  21663. }
  21664. if (!body1 || !body2) {
  21665. return false;
  21666. }
  21667. if (!options) {
  21668. options = {};
  21669. }
  21670. new OIMO.Link({
  21671. type: options.type,
  21672. body1: body1,
  21673. body2: body2,
  21674. min: options.min,
  21675. max: options.max,
  21676. axe1: options.axe1,
  21677. axe2: options.axe2,
  21678. pos1: [pivot1.x, pivot1.y, pivot1.z],
  21679. pos2: [pivot2.x, pivot2.y, pivot2.z],
  21680. collision: options.collision,
  21681. spring: options.spring,
  21682. world: this._world
  21683. });
  21684. return true;
  21685. };
  21686. OimoJSPlugin.prototype.dispose = function () {
  21687. this._world.clear();
  21688. while (this._registeredMeshes.length) {
  21689. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21690. }
  21691. };
  21692. OimoJSPlugin.prototype.isSupported = function () {
  21693. return OIMO !== undefined;
  21694. };
  21695. OimoJSPlugin.prototype._getLastShape = function (body) {
  21696. var lastShape = body.shapes;
  21697. while (lastShape.next) {
  21698. lastShape = lastShape.next;
  21699. }
  21700. return lastShape;
  21701. };
  21702. OimoJSPlugin.prototype.runOneStep = function (time) {
  21703. this._world.step();
  21704. // Update the position of all registered meshes
  21705. var i = this._registeredMeshes.length;
  21706. var m;
  21707. while (i--) {
  21708. var body = this._registeredMeshes[i].body.body;
  21709. var mesh = this._registeredMeshes[i].mesh;
  21710. var delta = this._registeredMeshes[i].delta;
  21711. if (!body.sleeping) {
  21712. if (body.shapes.next) {
  21713. var parentShape = this._getLastShape(body);
  21714. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  21715. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  21716. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  21717. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  21718. if (!mesh.rotationQuaternion) {
  21719. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21720. }
  21721. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  21722. mesh.computeWorldMatrix();
  21723. }
  21724. else {
  21725. m = body.getMatrix();
  21726. mtx = BABYLON.Matrix.FromArray(m);
  21727. // Body position
  21728. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  21729. if (!delta) {
  21730. mesh.position.x = bodyX;
  21731. mesh.position.y = bodyY;
  21732. mesh.position.z = bodyZ;
  21733. }
  21734. else {
  21735. mesh.position.x = bodyX + delta.x;
  21736. mesh.position.y = bodyY + delta.y;
  21737. mesh.position.z = bodyZ + delta.z;
  21738. }
  21739. if (!mesh.rotationQuaternion) {
  21740. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21741. }
  21742. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  21743. mesh.computeWorldMatrix();
  21744. }
  21745. }
  21746. }
  21747. };
  21748. return OimoJSPlugin;
  21749. })();
  21750. BABYLON.OimoJSPlugin = OimoJSPlugin;
  21751. })(BABYLON || (BABYLON = {}));
  21752. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  21753. var BABYLON;
  21754. (function (BABYLON) {
  21755. var PhysicsEngine = (function () {
  21756. function PhysicsEngine(plugin) {
  21757. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  21758. }
  21759. PhysicsEngine.prototype._initialize = function (gravity) {
  21760. this._currentPlugin.initialize();
  21761. this._setGravity(gravity);
  21762. };
  21763. PhysicsEngine.prototype._runOneStep = function (delta) {
  21764. if (delta > 0.1) {
  21765. delta = 0.1;
  21766. }
  21767. else if (delta <= 0) {
  21768. delta = 1.0 / 60.0;
  21769. }
  21770. this._currentPlugin.runOneStep(delta);
  21771. };
  21772. PhysicsEngine.prototype._setGravity = function (gravity) {
  21773. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  21774. this._currentPlugin.setGravity(this.gravity);
  21775. };
  21776. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  21777. return this._currentPlugin.registerMesh(mesh, impostor, options);
  21778. };
  21779. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  21780. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  21781. };
  21782. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  21783. this._currentPlugin.unregisterMesh(mesh);
  21784. };
  21785. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  21786. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  21787. };
  21788. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21789. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  21790. };
  21791. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  21792. this._currentPlugin.updateBodyPosition(mesh);
  21793. };
  21794. PhysicsEngine.prototype.dispose = function () {
  21795. this._currentPlugin.dispose();
  21796. };
  21797. PhysicsEngine.prototype.isSupported = function () {
  21798. return this._currentPlugin.isSupported();
  21799. };
  21800. // Statics
  21801. PhysicsEngine.NoImpostor = 0;
  21802. PhysicsEngine.SphereImpostor = 1;
  21803. PhysicsEngine.BoxImpostor = 2;
  21804. PhysicsEngine.PlaneImpostor = 3;
  21805. PhysicsEngine.MeshImpostor = 4;
  21806. PhysicsEngine.CapsuleImpostor = 5;
  21807. PhysicsEngine.ConeImpostor = 6;
  21808. PhysicsEngine.CylinderImpostor = 7;
  21809. PhysicsEngine.ConvexHullImpostor = 8;
  21810. PhysicsEngine.Epsilon = 0.001;
  21811. return PhysicsEngine;
  21812. })();
  21813. BABYLON.PhysicsEngine = PhysicsEngine;
  21814. })(BABYLON || (BABYLON = {}));
  21815. //# sourceMappingURL=babylon.physicsEngine.js.map
  21816. var BABYLON;
  21817. (function (BABYLON) {
  21818. var serializeLight = function (light) {
  21819. var serializationObject = {};
  21820. serializationObject.name = light.name;
  21821. serializationObject.id = light.id;
  21822. serializationObject.tags = BABYLON.Tags.GetTags(light);
  21823. if (light instanceof BABYLON.PointLight) {
  21824. serializationObject.type = 0;
  21825. serializationObject.position = light.position.asArray();
  21826. }
  21827. else if (light instanceof BABYLON.DirectionalLight) {
  21828. serializationObject.type = 1;
  21829. var directionalLight = light;
  21830. serializationObject.position = directionalLight.position.asArray();
  21831. serializationObject.direction = directionalLight.direction.asArray();
  21832. }
  21833. else if (light instanceof BABYLON.SpotLight) {
  21834. serializationObject.type = 2;
  21835. var spotLight = light;
  21836. serializationObject.position = spotLight.position.asArray();
  21837. serializationObject.direction = spotLight.position.asArray();
  21838. serializationObject.angle = spotLight.angle;
  21839. serializationObject.exponent = spotLight.exponent;
  21840. }
  21841. else if (light instanceof BABYLON.HemisphericLight) {
  21842. serializationObject.type = 3;
  21843. var hemisphericLight = light;
  21844. serializationObject.direction = hemisphericLight.direction.asArray();
  21845. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  21846. }
  21847. if (light.intensity) {
  21848. serializationObject.intensity = light.intensity;
  21849. }
  21850. serializationObject.range = light.range;
  21851. serializationObject.diffuse = light.diffuse.asArray();
  21852. serializationObject.specular = light.specular.asArray();
  21853. return serializationObject;
  21854. };
  21855. var serializeFresnelParameter = function (fresnelParameter) {
  21856. var serializationObject = {};
  21857. serializationObject.isEnabled = fresnelParameter.isEnabled;
  21858. serializationObject.leftColor = fresnelParameter.leftColor;
  21859. serializationObject.rightColor = fresnelParameter.rightColor;
  21860. serializationObject.bias = fresnelParameter.bias;
  21861. serializationObject.power = fresnelParameter.power;
  21862. return serializationObject;
  21863. };
  21864. var appendAnimations = function (source, destination) {
  21865. if (source.animations) {
  21866. destination.animations = [];
  21867. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21868. var animation = source.animations[animationIndex];
  21869. destination.animations.push(serializeAnimation(animation));
  21870. }
  21871. }
  21872. };
  21873. var serializeCamera = function (camera) {
  21874. var serializationObject = {};
  21875. serializationObject.name = camera.name;
  21876. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  21877. serializationObject.id = camera.id;
  21878. serializationObject.position = camera.position.asArray();
  21879. // Parent
  21880. if (camera.parent) {
  21881. serializationObject.parentId = camera.parent.id;
  21882. }
  21883. serializationObject.fov = camera.fov;
  21884. serializationObject.minZ = camera.minZ;
  21885. serializationObject.maxZ = camera.maxZ;
  21886. serializationObject.inertia = camera.inertia;
  21887. //setting the type
  21888. if (camera instanceof BABYLON.FreeCamera) {
  21889. serializationObject.type = "FreeCamera";
  21890. }
  21891. else if (camera instanceof BABYLON.ArcRotateCamera) {
  21892. serializationObject.type = "ArcRotateCamera";
  21893. }
  21894. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21895. serializationObject.type = "AnaglyphArcRotateCamera";
  21896. }
  21897. else if (camera instanceof BABYLON.GamepadCamera) {
  21898. serializationObject.type = "GamepadCamera";
  21899. }
  21900. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  21901. serializationObject.type = "AnaglyphFreeCamera";
  21902. }
  21903. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  21904. serializationObject.type = "DeviceOrientationCamera";
  21905. }
  21906. else if (camera instanceof BABYLON.FollowCamera) {
  21907. serializationObject.type = "FollowCamera";
  21908. }
  21909. else if (camera instanceof BABYLON.OculusCamera) {
  21910. serializationObject.type = "OculusCamera";
  21911. }
  21912. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  21913. serializationObject.type = "OculusGamepadCamera";
  21914. }
  21915. else if (camera instanceof BABYLON.TouchCamera) {
  21916. serializationObject.type = "TouchCamera";
  21917. }
  21918. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  21919. serializationObject.type = "VirtualJoysticksCamera";
  21920. }
  21921. else if (camera instanceof BABYLON.WebVRCamera) {
  21922. serializationObject.type = "WebVRCamera";
  21923. }
  21924. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  21925. serializationObject.type = "VRDeviceOrientationCamera";
  21926. }
  21927. //special properties of specific cameras
  21928. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21929. var arcCamera = camera;
  21930. serializationObject.alpha = arcCamera.alpha;
  21931. serializationObject.beta = arcCamera.beta;
  21932. serializationObject.radius = arcCamera.radius;
  21933. if (arcCamera.target && arcCamera.target.id) {
  21934. serializationObject.lockedTargetId = arcCamera.target.id;
  21935. }
  21936. }
  21937. else if (camera instanceof BABYLON.FollowCamera) {
  21938. var followCam = camera;
  21939. serializationObject.radius = followCam.radius;
  21940. serializationObject.heightOffset = followCam.heightOffset;
  21941. serializationObject.rotationOffset = followCam.rotationOffset;
  21942. }
  21943. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21944. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  21945. if (camera['_eyeSpace'] !== undefined) {
  21946. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  21947. }
  21948. }
  21949. //general properties that not all cameras have. The [] is due to typescript's type safety
  21950. if (camera['speed'] !== undefined) {
  21951. serializationObject.speed = camera['speed'];
  21952. }
  21953. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  21954. serializationObject.target = camera['target'].asArray();
  21955. }
  21956. // Target
  21957. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  21958. serializationObject.rotation = camera['rotation'].asArray();
  21959. }
  21960. // Locked target
  21961. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  21962. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  21963. }
  21964. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  21965. serializationObject.applyGravity = camera['applyGravity'] || false;
  21966. if (camera['ellipsoid']) {
  21967. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  21968. }
  21969. // Animations
  21970. appendAnimations(camera, serializationObject);
  21971. // Layer mask
  21972. serializationObject.layerMask = camera.layerMask;
  21973. return serializationObject;
  21974. };
  21975. var serializeAnimation = function (animation) {
  21976. var serializationObject = {};
  21977. serializationObject.name = animation.name;
  21978. serializationObject.property = animation.targetProperty;
  21979. serializationObject.framePerSecond = animation.framePerSecond;
  21980. serializationObject.dataType = animation.dataType;
  21981. serializationObject.loopBehavior = animation.loopMode;
  21982. var dataType = animation.dataType;
  21983. serializationObject.keys = [];
  21984. var keys = animation.getKeys();
  21985. for (var index = 0; index < keys.length; index++) {
  21986. var animationKey = keys[index];
  21987. var key = {};
  21988. key.frame = animationKey.frame;
  21989. switch (dataType) {
  21990. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  21991. key.values = [animationKey.value];
  21992. break;
  21993. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  21994. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  21995. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  21996. key.values = animationKey.value.asArray();
  21997. break;
  21998. }
  21999. serializationObject.keys.push(key);
  22000. }
  22001. return serializationObject;
  22002. };
  22003. var serializeMultiMaterial = function (material) {
  22004. var serializationObject = {};
  22005. serializationObject.name = material.name;
  22006. serializationObject.id = material.id;
  22007. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22008. serializationObject.materials = [];
  22009. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  22010. var subMat = material.subMaterials[matIndex];
  22011. if (subMat) {
  22012. serializationObject.materials.push(subMat.id);
  22013. }
  22014. else {
  22015. serializationObject.materials.push(null);
  22016. }
  22017. }
  22018. return serializationObject;
  22019. };
  22020. var serializeMaterial = function (material) {
  22021. var serializationObject = {};
  22022. serializationObject.name = material.name;
  22023. serializationObject.ambient = material.ambientColor.asArray();
  22024. serializationObject.diffuse = material.diffuseColor.asArray();
  22025. serializationObject.specular = material.specularColor.asArray();
  22026. serializationObject.specularPower = material.specularPower;
  22027. serializationObject.emissive = material.emissiveColor.asArray();
  22028. serializationObject.alpha = material.alpha;
  22029. serializationObject.id = material.id;
  22030. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22031. serializationObject.backFaceCulling = material.backFaceCulling;
  22032. if (material.diffuseTexture) {
  22033. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  22034. }
  22035. if (material.diffuseFresnelParameters) {
  22036. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  22037. }
  22038. if (material.ambientTexture) {
  22039. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  22040. }
  22041. if (material.opacityTexture) {
  22042. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  22043. }
  22044. if (material.opacityFresnelParameters) {
  22045. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  22046. }
  22047. if (material.reflectionTexture) {
  22048. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  22049. }
  22050. if (material.reflectionFresnelParameters) {
  22051. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  22052. }
  22053. if (material.emissiveTexture) {
  22054. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  22055. }
  22056. if (material.emissiveFresnelParameters) {
  22057. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  22058. }
  22059. if (material.specularTexture) {
  22060. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  22061. }
  22062. if (material.bumpTexture) {
  22063. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  22064. }
  22065. return serializationObject;
  22066. };
  22067. var serializeTexture = function (texture) {
  22068. var serializationObject = {};
  22069. if (!texture.name) {
  22070. return null;
  22071. }
  22072. if (texture instanceof BABYLON.CubeTexture) {
  22073. serializationObject.name = texture.name;
  22074. serializationObject.hasAlpha = texture.hasAlpha;
  22075. serializationObject.level = texture.level;
  22076. serializationObject.coordinatesMode = texture.coordinatesMode;
  22077. return serializationObject;
  22078. }
  22079. if (texture instanceof BABYLON.MirrorTexture) {
  22080. var mirrorTexture = texture;
  22081. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  22082. serializationObject.renderList = [];
  22083. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  22084. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  22085. }
  22086. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  22087. }
  22088. else if (texture instanceof BABYLON.RenderTargetTexture) {
  22089. var renderTargetTexture = texture;
  22090. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  22091. serializationObject.renderList = [];
  22092. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  22093. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  22094. }
  22095. }
  22096. var regularTexture = texture;
  22097. serializationObject.name = texture.name;
  22098. serializationObject.hasAlpha = texture.hasAlpha;
  22099. serializationObject.level = texture.level;
  22100. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  22101. serializationObject.coordinatesMode = texture.coordinatesMode;
  22102. serializationObject.uOffset = regularTexture.uOffset;
  22103. serializationObject.vOffset = regularTexture.vOffset;
  22104. serializationObject.uScale = regularTexture.uScale;
  22105. serializationObject.vScale = regularTexture.vScale;
  22106. serializationObject.uAng = regularTexture.uAng;
  22107. serializationObject.vAng = regularTexture.vAng;
  22108. serializationObject.wAng = regularTexture.wAng;
  22109. serializationObject.wrapU = texture.wrapU;
  22110. serializationObject.wrapV = texture.wrapV;
  22111. // Animations
  22112. appendAnimations(texture, serializationObject);
  22113. return serializationObject;
  22114. };
  22115. var serializeSkeleton = function (skeleton) {
  22116. var serializationObject = {};
  22117. serializationObject.name = skeleton.name;
  22118. serializationObject.id = skeleton.id;
  22119. serializationObject.bones = [];
  22120. for (var index = 0; index < skeleton.bones.length; index++) {
  22121. var bone = skeleton.bones[index];
  22122. var serializedBone = {
  22123. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  22124. name: bone.name,
  22125. matrix: bone.getLocalMatrix().toArray()
  22126. };
  22127. serializationObject.bones.push(serializedBone);
  22128. if (bone.animations && bone.animations.length > 0) {
  22129. serializedBone.animation = serializeAnimation(bone.animations[0]);
  22130. }
  22131. }
  22132. return serializationObject;
  22133. };
  22134. var serializeParticleSystem = function (particleSystem) {
  22135. var serializationObject = {};
  22136. serializationObject.emitterId = particleSystem.emitter.id;
  22137. serializationObject.capacity = particleSystem.getCapacity();
  22138. if (particleSystem.particleTexture) {
  22139. serializationObject.textureName = particleSystem.particleTexture.name;
  22140. }
  22141. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  22142. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  22143. serializationObject.minSize = particleSystem.minSize;
  22144. serializationObject.maxSize = particleSystem.maxSize;
  22145. serializationObject.minLifeTime = particleSystem.minLifeTime;
  22146. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  22147. serializationObject.emitRate = particleSystem.emitRate;
  22148. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  22149. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  22150. serializationObject.gravity = particleSystem.gravity.asArray();
  22151. serializationObject.direction1 = particleSystem.direction1.asArray();
  22152. serializationObject.direction2 = particleSystem.direction2.asArray();
  22153. serializationObject.color1 = particleSystem.color1.asArray();
  22154. serializationObject.color2 = particleSystem.color2.asArray();
  22155. serializationObject.colorDead = particleSystem.colorDead.asArray();
  22156. serializationObject.updateSpeed = particleSystem.updateSpeed;
  22157. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  22158. serializationObject.textureMask = particleSystem.textureMask.asArray();
  22159. serializationObject.blendMode = particleSystem.blendMode;
  22160. return serializationObject;
  22161. };
  22162. var serializeLensFlareSystem = function (lensFlareSystem) {
  22163. var serializationObject = {};
  22164. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  22165. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  22166. serializationObject.flares = [];
  22167. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  22168. var flare = lensFlareSystem.lensFlares[index];
  22169. serializationObject.flares.push({
  22170. size: flare.size,
  22171. position: flare.position,
  22172. color: flare.color.asArray(),
  22173. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  22174. });
  22175. }
  22176. return serializationObject;
  22177. };
  22178. var serializeShadowGenerator = function (light) {
  22179. var serializationObject = {};
  22180. var shadowGenerator = light.getShadowGenerator();
  22181. serializationObject.lightId = light.id;
  22182. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  22183. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  22184. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  22185. serializationObject.renderList = [];
  22186. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  22187. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  22188. serializationObject.renderList.push(mesh.id);
  22189. }
  22190. return serializationObject;
  22191. };
  22192. var serializedGeometries = [];
  22193. var serializeGeometry = function (geometry, serializationGeometries) {
  22194. if (serializedGeometries[geometry.id]) {
  22195. return;
  22196. }
  22197. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  22198. serializationGeometries.boxes.push(serializeBox(geometry));
  22199. }
  22200. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  22201. serializationGeometries.spheres.push(serializeSphere(geometry));
  22202. }
  22203. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  22204. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  22205. }
  22206. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  22207. serializationGeometries.toruses.push(serializeTorus(geometry));
  22208. }
  22209. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  22210. serializationGeometries.grounds.push(serializeGround(geometry));
  22211. }
  22212. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  22213. serializationGeometries.planes.push(serializePlane(geometry));
  22214. }
  22215. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  22216. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  22217. }
  22218. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  22219. throw new Error("Unknow primitive type");
  22220. }
  22221. else {
  22222. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  22223. }
  22224. serializedGeometries[geometry.id] = true;
  22225. };
  22226. var serializeGeometryBase = function (geometry) {
  22227. var serializationObject = {};
  22228. serializationObject.id = geometry.id;
  22229. if (BABYLON.Tags.HasTags(geometry)) {
  22230. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  22231. }
  22232. return serializationObject;
  22233. };
  22234. var serializeVertexData = function (vertexData) {
  22235. var serializationObject = serializeGeometryBase(vertexData);
  22236. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22237. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22238. }
  22239. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22240. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22241. }
  22242. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22243. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22244. }
  22245. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22246. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22247. }
  22248. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22249. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22250. }
  22251. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22252. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22253. serializationObject.matricesIndices._isExpanded = true;
  22254. }
  22255. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22256. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22257. }
  22258. serializationObject.indices = vertexData.getIndices();
  22259. return serializationObject;
  22260. };
  22261. var serializePrimitive = function (primitive) {
  22262. var serializationObject = serializeGeometryBase(primitive);
  22263. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  22264. return serializationObject;
  22265. };
  22266. var serializeBox = function (box) {
  22267. var serializationObject = serializePrimitive(box);
  22268. serializationObject.size = box.size;
  22269. return serializationObject;
  22270. };
  22271. var serializeSphere = function (sphere) {
  22272. var serializationObject = serializePrimitive(sphere);
  22273. serializationObject.segments = sphere.segments;
  22274. serializationObject.diameter = sphere.diameter;
  22275. return serializationObject;
  22276. };
  22277. var serializeCylinder = function (cylinder) {
  22278. var serializationObject = serializePrimitive(cylinder);
  22279. serializationObject.height = cylinder.height;
  22280. serializationObject.diameterTop = cylinder.diameterTop;
  22281. serializationObject.diameterBottom = cylinder.diameterBottom;
  22282. serializationObject.tessellation = cylinder.tessellation;
  22283. return serializationObject;
  22284. };
  22285. var serializeTorus = function (torus) {
  22286. var serializationObject = serializePrimitive(torus);
  22287. serializationObject.diameter = torus.diameter;
  22288. serializationObject.thickness = torus.thickness;
  22289. serializationObject.tessellation = torus.tessellation;
  22290. return serializationObject;
  22291. };
  22292. var serializeGround = function (ground) {
  22293. var serializationObject = serializePrimitive(ground);
  22294. serializationObject.width = ground.width;
  22295. serializationObject.height = ground.height;
  22296. serializationObject.subdivisions = ground.subdivisions;
  22297. return serializationObject;
  22298. };
  22299. var serializePlane = function (plane) {
  22300. var serializationObject = serializePrimitive(plane);
  22301. serializationObject.size = plane.size;
  22302. return serializationObject;
  22303. };
  22304. var serializeTorusKnot = function (torusKnot) {
  22305. var serializationObject = serializePrimitive(torusKnot);
  22306. serializationObject.radius = torusKnot.radius;
  22307. serializationObject.tube = torusKnot.tube;
  22308. serializationObject.radialSegments = torusKnot.radialSegments;
  22309. serializationObject.tubularSegments = torusKnot.tubularSegments;
  22310. serializationObject.p = torusKnot.p;
  22311. serializationObject.q = torusKnot.q;
  22312. return serializationObject;
  22313. };
  22314. var serializeMesh = function (mesh, serializationScene) {
  22315. var serializationObject = {};
  22316. serializationObject.name = mesh.name;
  22317. serializationObject.id = mesh.id;
  22318. if (BABYLON.Tags.HasTags(mesh)) {
  22319. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  22320. }
  22321. serializationObject.position = mesh.position.asArray();
  22322. if (mesh.rotationQuaternion) {
  22323. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  22324. }
  22325. else if (mesh.rotation) {
  22326. serializationObject.rotation = mesh.rotation.asArray();
  22327. }
  22328. serializationObject.scaling = mesh.scaling.asArray();
  22329. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  22330. serializationObject.isEnabled = mesh.isEnabled();
  22331. serializationObject.isVisible = mesh.isVisible;
  22332. serializationObject.infiniteDistance = mesh.infiniteDistance;
  22333. serializationObject.pickable = mesh.isPickable;
  22334. serializationObject.receiveShadows = mesh.receiveShadows;
  22335. serializationObject.billboardMode = mesh.billboardMode;
  22336. serializationObject.visibility = mesh.visibility;
  22337. serializationObject.checkCollisions = mesh.checkCollisions;
  22338. // Parent
  22339. if (mesh.parent) {
  22340. serializationObject.parentId = mesh.parent.id;
  22341. }
  22342. // Geometry
  22343. var geometry = mesh._geometry;
  22344. if (geometry) {
  22345. var geometryId = geometry.id;
  22346. serializationObject.geometryId = geometryId;
  22347. if (!mesh.getScene().getGeometryByID(geometryId)) {
  22348. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize too be able to reload the mesh with its geometry
  22349. serializeGeometry(geometry, serializationScene.geometries);
  22350. }
  22351. // SubMeshes
  22352. serializationObject.subMeshes = [];
  22353. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22354. var subMesh = mesh.subMeshes[subIndex];
  22355. serializationObject.subMeshes.push({
  22356. materialIndex: subMesh.materialIndex,
  22357. verticesStart: subMesh.verticesStart,
  22358. verticesCount: subMesh.verticesCount,
  22359. indexStart: subMesh.indexStart,
  22360. indexCount: subMesh.indexCount
  22361. });
  22362. }
  22363. }
  22364. // Material
  22365. if (mesh.material) {
  22366. serializationObject.materialId = mesh.material.id;
  22367. }
  22368. else {
  22369. mesh.material = null;
  22370. }
  22371. // Skeleton
  22372. if (mesh.skeleton) {
  22373. serializationObject.skeletonId = mesh.skeleton.id;
  22374. }
  22375. // Physics
  22376. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  22377. serializationObject.physicsMass = mesh.getPhysicsMass();
  22378. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  22379. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  22380. switch (mesh.getPhysicsImpostor()) {
  22381. case BABYLON.PhysicsEngine.BoxImpostor:
  22382. serializationObject.physicsImpostor = 1;
  22383. break;
  22384. case BABYLON.PhysicsEngine.SphereImpostor:
  22385. serializationObject.physicsImpostor = 2;
  22386. break;
  22387. }
  22388. }
  22389. // Instances
  22390. serializationObject.instances = [];
  22391. for (var index = 0; index < mesh.instances.length; index++) {
  22392. var instance = mesh.instances[index];
  22393. var serializationInstance = {
  22394. name: instance.name,
  22395. position: instance.position,
  22396. rotation: instance.rotation,
  22397. rotationQuaternion: instance.rotationQuaternion,
  22398. scaling: instance.scaling
  22399. };
  22400. serializationObject.instances.push(serializationInstance);
  22401. // Animations
  22402. appendAnimations(instance, serializationInstance);
  22403. }
  22404. // Animations
  22405. appendAnimations(mesh, serializationObject);
  22406. // Layer mask
  22407. serializationObject.layerMask = mesh.layerMask;
  22408. return serializationObject;
  22409. };
  22410. var SceneSerializer = (function () {
  22411. function SceneSerializer() {
  22412. }
  22413. SceneSerializer.Serialize = function (scene) {
  22414. var serializationObject = {};
  22415. // Scene
  22416. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  22417. serializationObject.autoClear = scene.autoClear;
  22418. serializationObject.clearColor = scene.clearColor.asArray();
  22419. serializationObject.ambientColor = scene.ambientColor.asArray();
  22420. serializationObject.gravity = scene.gravity.asArray();
  22421. // Fog
  22422. if (scene.fogMode && scene.fogMode !== 0) {
  22423. serializationObject.fogMode = scene.fogMode;
  22424. serializationObject.fogColor = scene.fogColor.asArray();
  22425. serializationObject.fogStart = scene.fogStart;
  22426. serializationObject.fogEnd = scene.fogEnd;
  22427. serializationObject.fogDensity = scene.fogDensity;
  22428. }
  22429. // Lights
  22430. serializationObject.lights = [];
  22431. for (var index = 0; index < scene.lights.length; index++) {
  22432. var light = scene.lights[index];
  22433. serializationObject.lights.push(serializeLight(light));
  22434. }
  22435. // Cameras
  22436. serializationObject.cameras = [];
  22437. for (index = 0; index < scene.cameras.length; index++) {
  22438. var camera = scene.cameras[index];
  22439. serializationObject.cameras.push(serializeCamera(camera));
  22440. }
  22441. if (scene.activeCamera) {
  22442. serializationObject.activeCameraID = scene.activeCamera.id;
  22443. }
  22444. // Materials
  22445. serializationObject.materials = [];
  22446. serializationObject.multiMaterials = [];
  22447. for (index = 0; index < scene.materials.length; index++) {
  22448. var material = scene.materials[index];
  22449. if (material instanceof BABYLON.StandardMaterial) {
  22450. serializationObject.materials.push(serializeMaterial(material));
  22451. }
  22452. else if (material instanceof BABYLON.MultiMaterial) {
  22453. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  22454. }
  22455. }
  22456. // Skeletons
  22457. serializationObject.skeletons = [];
  22458. for (index = 0; index < scene.skeletons.length; index++) {
  22459. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  22460. }
  22461. // Geometries
  22462. serializationObject.geometries = {};
  22463. serializationObject.geometries.boxes = [];
  22464. serializationObject.geometries.spheres = [];
  22465. serializationObject.geometries.cylinders = [];
  22466. serializationObject.geometries.toruses = [];
  22467. serializationObject.geometries.grounds = [];
  22468. serializationObject.geometries.planes = [];
  22469. serializationObject.geometries.torusKnots = [];
  22470. serializationObject.geometries.vertexData = [];
  22471. serializedGeometries = [];
  22472. var geometries = scene.getGeometries();
  22473. for (index = 0; index < geometries.length; index++) {
  22474. var geometry = geometries[index];
  22475. if (geometry.isReady()) {
  22476. serializeGeometry(geometry, serializationObject.geometries);
  22477. }
  22478. }
  22479. // Meshes
  22480. serializationObject.meshes = [];
  22481. for (index = 0; index < scene.meshes.length; index++) {
  22482. var abstractMesh = scene.meshes[index];
  22483. if (abstractMesh instanceof BABYLON.Mesh) {
  22484. var mesh = abstractMesh;
  22485. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  22486. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  22487. }
  22488. }
  22489. }
  22490. // Particles Systems
  22491. serializationObject.particleSystems = [];
  22492. for (index = 0; index < scene.particleSystems.length; index++) {
  22493. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  22494. }
  22495. // Lens flares
  22496. serializationObject.lensFlareSystems = [];
  22497. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  22498. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  22499. }
  22500. // Shadows
  22501. serializationObject.shadowGenerators = [];
  22502. for (index = 0; index < scene.lights.length; index++) {
  22503. light = scene.lights[index];
  22504. if (light.getShadowGenerator()) {
  22505. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  22506. }
  22507. }
  22508. return serializationObject;
  22509. };
  22510. return SceneSerializer;
  22511. })();
  22512. BABYLON.SceneSerializer = SceneSerializer;
  22513. })(BABYLON || (BABYLON = {}));
  22514. //# sourceMappingURL=babylon.sceneSerializer.js.map
  22515. var BABYLON;
  22516. (function (BABYLON) {
  22517. // Unique ID when we import meshes from Babylon to CSG
  22518. var currentCSGMeshId = 0;
  22519. // # class Vertex
  22520. // Represents a vertex of a polygon. Use your own vertex class instead of this
  22521. // one to provide additional features like texture coordinates and vertex
  22522. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  22523. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  22524. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  22525. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  22526. // is not used anywhere else.
  22527. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  22528. var Vertex = (function () {
  22529. function Vertex(pos, normal, uv) {
  22530. this.pos = pos;
  22531. this.normal = normal;
  22532. this.uv = uv;
  22533. }
  22534. Vertex.prototype.clone = function () {
  22535. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  22536. };
  22537. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  22538. // orientation of a polygon is flipped.
  22539. Vertex.prototype.flip = function () {
  22540. this.normal = this.normal.scale(-1);
  22541. };
  22542. // Create a new vertex between this vertex and `other` by linearly
  22543. // interpolating all properties using a parameter of `t`. Subclasses should
  22544. // override this to interpolate additional properties.
  22545. Vertex.prototype.interpolate = function (other, t) {
  22546. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  22547. };
  22548. return Vertex;
  22549. })();
  22550. // # class Plane
  22551. // Represents a plane in 3D space.
  22552. var Plane = (function () {
  22553. function Plane(normal, w) {
  22554. this.normal = normal;
  22555. this.w = w;
  22556. }
  22557. Plane.FromPoints = function (a, b, c) {
  22558. var v0 = c.subtract(a);
  22559. var v1 = b.subtract(a);
  22560. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  22561. return null;
  22562. }
  22563. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  22564. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  22565. };
  22566. Plane.prototype.clone = function () {
  22567. return new Plane(this.normal.clone(), this.w);
  22568. };
  22569. Plane.prototype.flip = function () {
  22570. this.normal.scaleInPlace(-1);
  22571. this.w = -this.w;
  22572. };
  22573. // Split `polygon` by this plane if needed, then put the polygon or polygon
  22574. // fragments in the appropriate lists. Coplanar polygons go into either
  22575. // `coplanarFront` or `coplanarBack` depending on their orientation with
  22576. // respect to this plane. Polygons in front or in back of this plane go into
  22577. // either `front` or `back`.
  22578. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  22579. var COPLANAR = 0;
  22580. var FRONT = 1;
  22581. var BACK = 2;
  22582. var SPANNING = 3;
  22583. // Classify each point as well as the entire polygon into one of the above
  22584. // four classes.
  22585. var polygonType = 0;
  22586. var types = [];
  22587. for (var i = 0; i < polygon.vertices.length; i++) {
  22588. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  22589. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  22590. polygonType |= type;
  22591. types.push(type);
  22592. }
  22593. switch (polygonType) {
  22594. case COPLANAR:
  22595. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  22596. break;
  22597. case FRONT:
  22598. front.push(polygon);
  22599. break;
  22600. case BACK:
  22601. back.push(polygon);
  22602. break;
  22603. case SPANNING:
  22604. var f = [], b = [];
  22605. for (i = 0; i < polygon.vertices.length; i++) {
  22606. var j = (i + 1) % polygon.vertices.length;
  22607. var ti = types[i], tj = types[j];
  22608. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  22609. if (ti != BACK)
  22610. f.push(vi);
  22611. if (ti != FRONT)
  22612. b.push(ti != BACK ? vi.clone() : vi);
  22613. if ((ti | tj) == SPANNING) {
  22614. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  22615. var v = vi.interpolate(vj, t);
  22616. f.push(v);
  22617. b.push(v.clone());
  22618. }
  22619. }
  22620. if (f.length >= 3) {
  22621. var poly = new Polygon(f, polygon.shared);
  22622. if (poly.plane)
  22623. front.push(poly);
  22624. }
  22625. if (b.length >= 3) {
  22626. poly = new Polygon(b, polygon.shared);
  22627. if (poly.plane)
  22628. back.push(poly);
  22629. }
  22630. break;
  22631. }
  22632. };
  22633. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  22634. // point is on the plane.
  22635. Plane.EPSILON = 1e-5;
  22636. return Plane;
  22637. })();
  22638. // # class Polygon
  22639. // Represents a convex polygon. The vertices used to initialize a polygon must
  22640. // be coplanar and form a convex loop.
  22641. //
  22642. // Each convex polygon has a `shared` property, which is shared between all
  22643. // polygons that are clones of each other or were split from the same polygon.
  22644. // This can be used to define per-polygon properties (such as surface color).
  22645. var Polygon = (function () {
  22646. function Polygon(vertices, shared) {
  22647. this.vertices = vertices;
  22648. this.shared = shared;
  22649. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  22650. }
  22651. Polygon.prototype.clone = function () {
  22652. var vertices = this.vertices.map(function (v) { return v.clone(); });
  22653. return new Polygon(vertices, this.shared);
  22654. };
  22655. Polygon.prototype.flip = function () {
  22656. this.vertices.reverse().map(function (v) {
  22657. v.flip();
  22658. });
  22659. this.plane.flip();
  22660. };
  22661. return Polygon;
  22662. })();
  22663. // # class Node
  22664. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  22665. // by picking a polygon to split along. That polygon (and all other coplanar
  22666. // polygons) are added directly to that node and the other polygons are added to
  22667. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  22668. // no distinction between internal and leaf nodes.
  22669. var Node = (function () {
  22670. function Node(polygons) {
  22671. this.plane = null;
  22672. this.front = null;
  22673. this.back = null;
  22674. this.polygons = [];
  22675. if (polygons) {
  22676. this.build(polygons);
  22677. }
  22678. }
  22679. Node.prototype.clone = function () {
  22680. var node = new Node();
  22681. node.plane = this.plane && this.plane.clone();
  22682. node.front = this.front && this.front.clone();
  22683. node.back = this.back && this.back.clone();
  22684. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  22685. return node;
  22686. };
  22687. // Convert solid space to empty space and empty space to solid space.
  22688. Node.prototype.invert = function () {
  22689. for (var i = 0; i < this.polygons.length; i++) {
  22690. this.polygons[i].flip();
  22691. }
  22692. if (this.plane) {
  22693. this.plane.flip();
  22694. }
  22695. if (this.front) {
  22696. this.front.invert();
  22697. }
  22698. if (this.back) {
  22699. this.back.invert();
  22700. }
  22701. var temp = this.front;
  22702. this.front = this.back;
  22703. this.back = temp;
  22704. };
  22705. // Recursively remove all polygons in `polygons` that are inside this BSP
  22706. // tree.
  22707. Node.prototype.clipPolygons = function (polygons) {
  22708. if (!this.plane)
  22709. return polygons.slice();
  22710. var front = [], back = [];
  22711. for (var i = 0; i < polygons.length; i++) {
  22712. this.plane.splitPolygon(polygons[i], front, back, front, back);
  22713. }
  22714. if (this.front) {
  22715. front = this.front.clipPolygons(front);
  22716. }
  22717. if (this.back) {
  22718. back = this.back.clipPolygons(back);
  22719. }
  22720. else {
  22721. back = [];
  22722. }
  22723. return front.concat(back);
  22724. };
  22725. // Remove all polygons in this BSP tree that are inside the other BSP tree
  22726. // `bsp`.
  22727. Node.prototype.clipTo = function (bsp) {
  22728. this.polygons = bsp.clipPolygons(this.polygons);
  22729. if (this.front)
  22730. this.front.clipTo(bsp);
  22731. if (this.back)
  22732. this.back.clipTo(bsp);
  22733. };
  22734. // Return a list of all polygons in this BSP tree.
  22735. Node.prototype.allPolygons = function () {
  22736. var polygons = this.polygons.slice();
  22737. if (this.front)
  22738. polygons = polygons.concat(this.front.allPolygons());
  22739. if (this.back)
  22740. polygons = polygons.concat(this.back.allPolygons());
  22741. return polygons;
  22742. };
  22743. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  22744. // new polygons are filtered down to the bottom of the tree and become new
  22745. // nodes there. Each set of polygons is partitioned using the first polygon
  22746. // (no heuristic is used to pick a good split).
  22747. Node.prototype.build = function (polygons) {
  22748. if (!polygons.length)
  22749. return;
  22750. if (!this.plane)
  22751. this.plane = polygons[0].plane.clone();
  22752. var front = [], back = [];
  22753. for (var i = 0; i < polygons.length; i++) {
  22754. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  22755. }
  22756. if (front.length) {
  22757. if (!this.front)
  22758. this.front = new Node();
  22759. this.front.build(front);
  22760. }
  22761. if (back.length) {
  22762. if (!this.back)
  22763. this.back = new Node();
  22764. this.back.build(back);
  22765. }
  22766. };
  22767. return Node;
  22768. })();
  22769. var CSG = (function () {
  22770. function CSG() {
  22771. this.polygons = new Array();
  22772. }
  22773. // Convert BABYLON.Mesh to BABYLON.CSG
  22774. CSG.FromMesh = function (mesh) {
  22775. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  22776. if (mesh instanceof BABYLON.Mesh) {
  22777. mesh.computeWorldMatrix(true);
  22778. var matrix = mesh.getWorldMatrix();
  22779. var meshPosition = mesh.position.clone();
  22780. var meshRotation = mesh.rotation.clone();
  22781. var meshScaling = mesh.scaling.clone();
  22782. }
  22783. else {
  22784. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  22785. }
  22786. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22787. var subMeshes = mesh.subMeshes;
  22788. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  22789. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  22790. vertices = [];
  22791. for (var j = 0; j < 3; j++) {
  22792. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  22793. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  22794. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  22795. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  22796. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  22797. vertex = new Vertex(position, normal, uv);
  22798. vertices.push(vertex);
  22799. }
  22800. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  22801. // To handle the case of degenerated triangle
  22802. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  22803. if (polygon.plane)
  22804. polygons.push(polygon);
  22805. }
  22806. }
  22807. var csg = CSG.FromPolygons(polygons);
  22808. csg.matrix = matrix;
  22809. csg.position = meshPosition;
  22810. csg.rotation = meshRotation;
  22811. csg.scaling = meshScaling;
  22812. currentCSGMeshId++;
  22813. return csg;
  22814. };
  22815. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  22816. CSG.FromPolygons = function (polygons) {
  22817. var csg = new BABYLON.CSG();
  22818. csg.polygons = polygons;
  22819. return csg;
  22820. };
  22821. CSG.prototype.clone = function () {
  22822. var csg = new BABYLON.CSG();
  22823. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  22824. csg.copyTransformAttributes(this);
  22825. return csg;
  22826. };
  22827. CSG.prototype.toPolygons = function () {
  22828. return this.polygons;
  22829. };
  22830. CSG.prototype.union = function (csg) {
  22831. var a = new Node(this.clone().polygons);
  22832. var b = new Node(csg.clone().polygons);
  22833. a.clipTo(b);
  22834. b.clipTo(a);
  22835. b.invert();
  22836. b.clipTo(a);
  22837. b.invert();
  22838. a.build(b.allPolygons());
  22839. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22840. };
  22841. CSG.prototype.unionInPlace = function (csg) {
  22842. var a = new Node(this.polygons);
  22843. var b = new Node(csg.polygons);
  22844. a.clipTo(b);
  22845. b.clipTo(a);
  22846. b.invert();
  22847. b.clipTo(a);
  22848. b.invert();
  22849. a.build(b.allPolygons());
  22850. this.polygons = a.allPolygons();
  22851. };
  22852. CSG.prototype.subtract = function (csg) {
  22853. var a = new Node(this.clone().polygons);
  22854. var b = new Node(csg.clone().polygons);
  22855. a.invert();
  22856. a.clipTo(b);
  22857. b.clipTo(a);
  22858. b.invert();
  22859. b.clipTo(a);
  22860. b.invert();
  22861. a.build(b.allPolygons());
  22862. a.invert();
  22863. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22864. };
  22865. CSG.prototype.subtractInPlace = function (csg) {
  22866. var a = new Node(this.polygons);
  22867. var b = new Node(csg.polygons);
  22868. a.invert();
  22869. a.clipTo(b);
  22870. b.clipTo(a);
  22871. b.invert();
  22872. b.clipTo(a);
  22873. b.invert();
  22874. a.build(b.allPolygons());
  22875. a.invert();
  22876. this.polygons = a.allPolygons();
  22877. };
  22878. CSG.prototype.intersect = function (csg) {
  22879. var a = new Node(this.clone().polygons);
  22880. var b = new Node(csg.clone().polygons);
  22881. a.invert();
  22882. b.clipTo(a);
  22883. b.invert();
  22884. a.clipTo(b);
  22885. b.clipTo(a);
  22886. a.build(b.allPolygons());
  22887. a.invert();
  22888. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22889. };
  22890. CSG.prototype.intersectInPlace = function (csg) {
  22891. var a = new Node(this.polygons);
  22892. var b = new Node(csg.polygons);
  22893. a.invert();
  22894. b.clipTo(a);
  22895. b.invert();
  22896. a.clipTo(b);
  22897. b.clipTo(a);
  22898. a.build(b.allPolygons());
  22899. a.invert();
  22900. this.polygons = a.allPolygons();
  22901. };
  22902. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  22903. // not modified.
  22904. CSG.prototype.inverse = function () {
  22905. var csg = this.clone();
  22906. csg.inverseInPlace();
  22907. return csg;
  22908. };
  22909. CSG.prototype.inverseInPlace = function () {
  22910. this.polygons.map(function (p) {
  22911. p.flip();
  22912. });
  22913. };
  22914. // This is used to keep meshes transformations so they can be restored
  22915. // when we build back a Babylon Mesh
  22916. // NB : All CSG operations are performed in world coordinates
  22917. CSG.prototype.copyTransformAttributes = function (csg) {
  22918. this.matrix = csg.matrix;
  22919. this.position = csg.position;
  22920. this.rotation = csg.rotation;
  22921. this.scaling = csg.scaling;
  22922. return this;
  22923. };
  22924. // Build Raw mesh from CSG
  22925. // Coordinates here are in world space
  22926. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  22927. var matrix = this.matrix.clone();
  22928. matrix.invert();
  22929. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  22930. if (keepSubMeshes) {
  22931. // Sort Polygons, since subMeshes are indices range
  22932. polygons.sort(function (a, b) {
  22933. if (a.shared.meshId === b.shared.meshId) {
  22934. return a.shared.subMeshId - b.shared.subMeshId;
  22935. }
  22936. else {
  22937. return a.shared.meshId - b.shared.meshId;
  22938. }
  22939. });
  22940. }
  22941. for (var i = 0, il = polygons.length; i < il; i++) {
  22942. polygon = polygons[i];
  22943. // Building SubMeshes
  22944. if (!subMesh_dict[polygon.shared.meshId]) {
  22945. subMesh_dict[polygon.shared.meshId] = {};
  22946. }
  22947. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  22948. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  22949. indexStart: +Infinity,
  22950. indexEnd: -Infinity,
  22951. materialIndex: polygon.shared.materialIndex
  22952. };
  22953. }
  22954. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  22955. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  22956. polygonIndices[0] = 0;
  22957. polygonIndices[1] = j - 1;
  22958. polygonIndices[2] = j;
  22959. for (var k = 0; k < 3; k++) {
  22960. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  22961. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  22962. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  22963. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  22964. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  22965. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  22966. // Check if 2 points can be merged
  22967. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  22968. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  22969. uvs.push(uv.x, uv.y);
  22970. normals.push(normal.x, normal.y, normal.z);
  22971. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  22972. }
  22973. indices.push(vertex_idx);
  22974. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  22975. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  22976. currentIndex++;
  22977. }
  22978. }
  22979. }
  22980. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  22981. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22982. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  22983. mesh.setIndices(indices);
  22984. if (keepSubMeshes) {
  22985. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  22986. var materialIndexOffset = 0, materialMaxIndex;
  22987. mesh.subMeshes.length = 0;
  22988. for (var m in subMesh_dict) {
  22989. materialMaxIndex = -1;
  22990. for (var sm in subMesh_dict[m]) {
  22991. subMesh_obj = subMesh_dict[m][sm];
  22992. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  22993. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  22994. }
  22995. materialIndexOffset += ++materialMaxIndex;
  22996. }
  22997. }
  22998. return mesh;
  22999. };
  23000. // Build Mesh from CSG taking material and transforms into account
  23001. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  23002. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  23003. mesh.material = material;
  23004. mesh.position.copyFrom(this.position);
  23005. mesh.rotation.copyFrom(this.rotation);
  23006. mesh.scaling.copyFrom(this.scaling);
  23007. mesh.computeWorldMatrix(true);
  23008. return mesh;
  23009. };
  23010. return CSG;
  23011. })();
  23012. BABYLON.CSG = CSG;
  23013. })(BABYLON || (BABYLON = {}));
  23014. //# sourceMappingURL=babylon.csg.js.map
  23015. var __extends = this.__extends || function (d, b) {
  23016. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23017. function __() { this.constructor = d; }
  23018. __.prototype = b.prototype;
  23019. d.prototype = new __();
  23020. };
  23021. var BABYLON;
  23022. (function (BABYLON) {
  23023. var OculusDistortionCorrectionPostProcess = (function (_super) {
  23024. __extends(OculusDistortionCorrectionPostProcess, _super);
  23025. //ANY
  23026. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  23027. var _this = this;
  23028. _super.call(this, name, "oculusDistortionCorrection", [
  23029. 'LensCenter',
  23030. 'Scale',
  23031. 'ScaleIn',
  23032. 'HmdWarpParam'
  23033. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  23034. this._isRightEye = isRightEye;
  23035. this._distortionFactors = cameraSettings.DistortionK;
  23036. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  23037. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  23038. this.onSizeChanged = function () {
  23039. _this.aspectRatio = _this.width * .5 / _this.height;
  23040. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  23041. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  23042. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  23043. };
  23044. this.onApply = function (effect) {
  23045. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  23046. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  23047. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  23048. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  23049. };
  23050. }
  23051. return OculusDistortionCorrectionPostProcess;
  23052. })(BABYLON.PostProcess);
  23053. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  23054. })(BABYLON || (BABYLON = {}));
  23055. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  23056. // Mainly based on these 2 articles :
  23057. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  23058. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  23059. var BABYLON;
  23060. (function (BABYLON) {
  23061. (function (JoystickAxis) {
  23062. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  23063. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  23064. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  23065. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  23066. var JoystickAxis = BABYLON.JoystickAxis;
  23067. var VirtualJoystick = (function () {
  23068. function VirtualJoystick(leftJoystick) {
  23069. var _this = this;
  23070. if (leftJoystick) {
  23071. this._leftJoystick = true;
  23072. }
  23073. else {
  23074. this._leftJoystick = false;
  23075. }
  23076. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  23077. VirtualJoystick._globalJoystickIndex++;
  23078. // By default left & right arrow keys are moving the X
  23079. // and up & down keys are moving the Y
  23080. this._axisTargetedByLeftAndRight = 0 /* X */;
  23081. this._axisTargetedByUpAndDown = 1 /* Y */;
  23082. this.reverseLeftRight = false;
  23083. this.reverseUpDown = false;
  23084. // collections of pointers
  23085. this._touches = new BABYLON.SmartCollection();
  23086. this.deltaPosition = BABYLON.Vector3.Zero();
  23087. this._joystickSensibility = 25;
  23088. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23089. this._rotationSpeed = 25;
  23090. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  23091. this._rotateOnAxisRelativeToMesh = false;
  23092. // injecting a canvas element on top of the canvas 3D game
  23093. if (!VirtualJoystick.vjCanvas) {
  23094. window.addEventListener("resize", function () {
  23095. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23096. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23097. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  23098. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  23099. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  23100. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  23101. }, false);
  23102. VirtualJoystick.vjCanvas = document.createElement("canvas");
  23103. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23104. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23105. VirtualJoystick.vjCanvas.width = window.innerWidth;
  23106. VirtualJoystick.vjCanvas.height = window.innerHeight;
  23107. VirtualJoystick.vjCanvas.style.width = "100%";
  23108. VirtualJoystick.vjCanvas.style.height = "100%";
  23109. VirtualJoystick.vjCanvas.style.position = "absolute";
  23110. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  23111. VirtualJoystick.vjCanvas.style.top = "0px";
  23112. VirtualJoystick.vjCanvas.style.left = "0px";
  23113. VirtualJoystick.vjCanvas.style.zIndex = "5";
  23114. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  23115. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  23116. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  23117. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23118. document.body.appendChild(VirtualJoystick.vjCanvas);
  23119. }
  23120. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  23121. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  23122. this.pressed = false;
  23123. // default joystick color
  23124. this._joystickColor = "cyan";
  23125. this._joystickPointerID = -1;
  23126. // current joystick position
  23127. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  23128. // origin joystick position
  23129. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  23130. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  23131. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  23132. _this._onPointerDown(evt);
  23133. }, false);
  23134. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  23135. _this._onPointerMove(evt);
  23136. }, false);
  23137. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  23138. _this._onPointerUp(evt);
  23139. }, false);
  23140. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  23141. _this._onPointerUp(evt);
  23142. }, false);
  23143. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  23144. evt.preventDefault(); // Disables system menu
  23145. }, false);
  23146. requestAnimationFrame(function () {
  23147. _this._drawVirtualJoystick();
  23148. });
  23149. }
  23150. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  23151. this._joystickSensibility = newJoystickSensibility;
  23152. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23153. };
  23154. VirtualJoystick.prototype._onPointerDown = function (e) {
  23155. var positionOnScreenCondition;
  23156. e.preventDefault();
  23157. if (this._leftJoystick === true) {
  23158. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  23159. }
  23160. else {
  23161. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  23162. }
  23163. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  23164. // First contact will be dedicated to the virtual joystick
  23165. this._joystickPointerID = e.pointerId;
  23166. this._joystickPointerStartPos.x = e.clientX;
  23167. this._joystickPointerStartPos.y = e.clientY;
  23168. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  23169. this._deltaJoystickVector.x = 0;
  23170. this._deltaJoystickVector.y = 0;
  23171. this.pressed = true;
  23172. this._touches.add(e.pointerId.toString(), e);
  23173. }
  23174. else {
  23175. // You can only trigger the action buttons with a joystick declared
  23176. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  23177. this._action();
  23178. this._touches.add(e.pointerId.toString(), e);
  23179. }
  23180. }
  23181. };
  23182. VirtualJoystick.prototype._onPointerMove = function (e) {
  23183. // If the current pointer is the one associated to the joystick (first touch contact)
  23184. if (this._joystickPointerID == e.pointerId) {
  23185. this._joystickPointerPos.x = e.clientX;
  23186. this._joystickPointerPos.y = e.clientY;
  23187. this._deltaJoystickVector = this._joystickPointerPos.clone();
  23188. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  23189. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  23190. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  23191. switch (this._axisTargetedByLeftAndRight) {
  23192. case 0 /* X */:
  23193. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  23194. break;
  23195. case 1 /* Y */:
  23196. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  23197. break;
  23198. case 2 /* Z */:
  23199. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  23200. break;
  23201. }
  23202. var directionUpDown = this.reverseUpDown ? 1 : -1;
  23203. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  23204. switch (this._axisTargetedByUpAndDown) {
  23205. case 0 /* X */:
  23206. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  23207. break;
  23208. case 1 /* Y */:
  23209. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  23210. break;
  23211. case 2 /* Z */:
  23212. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  23213. break;
  23214. }
  23215. }
  23216. else {
  23217. if (this._touches.item(e.pointerId.toString())) {
  23218. this._touches.item(e.pointerId.toString()).x = e.clientX;
  23219. this._touches.item(e.pointerId.toString()).y = e.clientY;
  23220. }
  23221. }
  23222. };
  23223. VirtualJoystick.prototype._onPointerUp = function (e) {
  23224. this._clearCanvas();
  23225. if (this._joystickPointerID == e.pointerId) {
  23226. this._joystickPointerID = -1;
  23227. this.pressed = false;
  23228. }
  23229. this._deltaJoystickVector.x = 0;
  23230. this._deltaJoystickVector.y = 0;
  23231. this._touches.remove(e.pointerId.toString());
  23232. };
  23233. /**
  23234. * Change the color of the virtual joystick
  23235. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  23236. */
  23237. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  23238. this._joystickColor = newColor;
  23239. };
  23240. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  23241. this._action = action;
  23242. };
  23243. // Define which axis you'd like to control for left & right
  23244. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  23245. switch (axis) {
  23246. case 0 /* X */:
  23247. case 1 /* Y */:
  23248. case 2 /* Z */:
  23249. this._axisTargetedByLeftAndRight = axis;
  23250. break;
  23251. default:
  23252. this._axisTargetedByLeftAndRight = 0 /* X */;
  23253. break;
  23254. }
  23255. };
  23256. // Define which axis you'd like to control for up & down
  23257. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  23258. switch (axis) {
  23259. case 0 /* X */:
  23260. case 1 /* Y */:
  23261. case 2 /* Z */:
  23262. this._axisTargetedByUpAndDown = axis;
  23263. break;
  23264. default:
  23265. this._axisTargetedByUpAndDown = 1 /* Y */;
  23266. break;
  23267. }
  23268. };
  23269. VirtualJoystick.prototype._clearCanvas = function () {
  23270. if (this._leftJoystick) {
  23271. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  23272. }
  23273. else {
  23274. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  23275. }
  23276. };
  23277. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  23278. var _this = this;
  23279. if (this.pressed) {
  23280. this._clearCanvas();
  23281. this._touches.forEach(function (touch) {
  23282. if (touch.pointerId === _this._joystickPointerID) {
  23283. VirtualJoystick.vjCanvasContext.beginPath();
  23284. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23285. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23286. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  23287. VirtualJoystick.vjCanvasContext.stroke();
  23288. VirtualJoystick.vjCanvasContext.beginPath();
  23289. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23290. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23291. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  23292. VirtualJoystick.vjCanvasContext.stroke();
  23293. VirtualJoystick.vjCanvasContext.beginPath();
  23294. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23295. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  23296. VirtualJoystick.vjCanvasContext.stroke();
  23297. }
  23298. else {
  23299. VirtualJoystick.vjCanvasContext.beginPath();
  23300. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  23301. VirtualJoystick.vjCanvasContext.beginPath();
  23302. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  23303. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23304. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  23305. VirtualJoystick.vjCanvasContext.stroke();
  23306. }
  23307. ;
  23308. });
  23309. }
  23310. requestAnimationFrame(function () {
  23311. _this._drawVirtualJoystick();
  23312. });
  23313. };
  23314. VirtualJoystick.prototype.releaseCanvas = function () {
  23315. if (VirtualJoystick.vjCanvas) {
  23316. document.body.removeChild(VirtualJoystick.vjCanvas);
  23317. VirtualJoystick.vjCanvas = null;
  23318. }
  23319. };
  23320. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  23321. VirtualJoystick._globalJoystickIndex = 0;
  23322. return VirtualJoystick;
  23323. })();
  23324. BABYLON.VirtualJoystick = VirtualJoystick;
  23325. })(BABYLON || (BABYLON = {}));
  23326. //# sourceMappingURL=babylon.virtualJoystick.js.map
  23327. var __extends = this.__extends || function (d, b) {
  23328. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23329. function __() { this.constructor = d; }
  23330. __.prototype = b.prototype;
  23331. d.prototype = new __();
  23332. };
  23333. var BABYLON;
  23334. (function (BABYLON) {
  23335. var OculusRiftDevKit2013_Metric = {
  23336. HResolution: 1280,
  23337. VResolution: 800,
  23338. HScreenSize: 0.149759993,
  23339. VScreenSize: 0.0935999975,
  23340. VScreenCenter: 0.0467999987,
  23341. EyeToScreenDistance: 0.0410000011,
  23342. LensSeparationDistance: 0.0635000020,
  23343. InterpupillaryDistance: 0.0640000030,
  23344. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  23345. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  23346. PostProcessScaleFactor: 1.714605507808412,
  23347. LensCenterOffset: 0.151976421
  23348. };
  23349. var _OculusInnerCamera = (function (_super) {
  23350. __extends(_OculusInnerCamera, _super);
  23351. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  23352. _super.call(this, name, position, scene);
  23353. this._workMatrix = new BABYLON.Matrix();
  23354. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  23355. // Constants
  23356. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  23357. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  23358. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  23359. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  23360. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  23361. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  23362. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  23363. // Postprocess
  23364. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  23365. }
  23366. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  23367. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  23368. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  23369. return this._projectionMatrix;
  23370. };
  23371. _OculusInnerCamera.prototype._getViewMatrix = function () {
  23372. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  23373. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  23374. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  23375. // Computing target and final matrix
  23376. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  23377. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  23378. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  23379. return this._viewMatrix;
  23380. };
  23381. return _OculusInnerCamera;
  23382. })(BABYLON.FreeCamera);
  23383. var OculusCamera = (function (_super) {
  23384. __extends(OculusCamera, _super);
  23385. function OculusCamera(name, position, scene) {
  23386. _super.call(this, name, position, scene);
  23387. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  23388. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  23389. this.subCameras.push(this._leftCamera);
  23390. this.subCameras.push(this._rightCamera);
  23391. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  23392. }
  23393. OculusCamera.prototype._update = function () {
  23394. this._leftCamera.position.copyFrom(this.position);
  23395. this._rightCamera.position.copyFrom(this.position);
  23396. this._updateCamera(this._leftCamera);
  23397. this._updateCamera(this._rightCamera);
  23398. _super.prototype._update.call(this);
  23399. };
  23400. OculusCamera.prototype._updateCamera = function (camera) {
  23401. camera.minZ = this.minZ;
  23402. camera.maxZ = this.maxZ;
  23403. camera.rotation.x = this.rotation.x;
  23404. camera.rotation.y = this.rotation.y;
  23405. camera.rotation.z = this.rotation.z;
  23406. };
  23407. // Oculus events
  23408. OculusCamera.prototype._onOrientationEvent = function (evt) {
  23409. var yaw = evt.alpha / 180 * Math.PI;
  23410. var pitch = evt.beta / 180 * Math.PI;
  23411. var roll = evt.gamma / 180 * Math.PI;
  23412. if (!this._offsetOrientation) {
  23413. this._offsetOrientation = {
  23414. yaw: yaw,
  23415. pitch: pitch,
  23416. roll: roll
  23417. };
  23418. return;
  23419. }
  23420. else {
  23421. this.rotation.y += yaw - this._offsetOrientation.yaw;
  23422. this.rotation.x += pitch - this._offsetOrientation.pitch;
  23423. this.rotation.z += this._offsetOrientation.roll - roll;
  23424. this._offsetOrientation.yaw = yaw;
  23425. this._offsetOrientation.pitch = pitch;
  23426. this._offsetOrientation.roll = roll;
  23427. }
  23428. };
  23429. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  23430. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23431. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  23432. };
  23433. OculusCamera.prototype.detachControl = function (element) {
  23434. _super.prototype.detachControl.call(this, element);
  23435. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  23436. };
  23437. return OculusCamera;
  23438. })(BABYLON.FreeCamera);
  23439. BABYLON.OculusCamera = OculusCamera;
  23440. })(BABYLON || (BABYLON = {}));
  23441. //# sourceMappingURL=babylon.oculusCamera.js.map
  23442. var __extends = this.__extends || function (d, b) {
  23443. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23444. function __() { this.constructor = d; }
  23445. __.prototype = b.prototype;
  23446. d.prototype = new __();
  23447. };
  23448. var BABYLON;
  23449. (function (BABYLON) {
  23450. var OculusRiftDevKit2013_Metric = {
  23451. HResolution: 1280,
  23452. VResolution: 800,
  23453. HScreenSize: 0.149759993,
  23454. VScreenSize: 0.0935999975,
  23455. VScreenCenter: 0.0467999987,
  23456. EyeToScreenDistance: 0.0410000011,
  23457. LensSeparationDistance: 0.0635000020,
  23458. InterpupillaryDistance: 0.0640000030,
  23459. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  23460. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  23461. PostProcessScaleFactor: 1.714605507808412,
  23462. LensCenterOffset: 0.151976421
  23463. };
  23464. var _OculusInnerGamepadCamera = (function (_super) {
  23465. __extends(_OculusInnerGamepadCamera, _super);
  23466. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  23467. _super.call(this, name, position, scene);
  23468. this._workMatrix = new BABYLON.Matrix();
  23469. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  23470. // Constants
  23471. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  23472. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  23473. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  23474. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  23475. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  23476. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  23477. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  23478. // Postprocess
  23479. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  23480. }
  23481. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  23482. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  23483. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  23484. return this._projectionMatrix;
  23485. };
  23486. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  23487. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  23488. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  23489. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  23490. // Computing target and final matrix
  23491. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  23492. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  23493. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  23494. return this._viewMatrix;
  23495. };
  23496. return _OculusInnerGamepadCamera;
  23497. })(BABYLON.FreeCamera);
  23498. var OculusGamepadCamera = (function (_super) {
  23499. __extends(OculusGamepadCamera, _super);
  23500. function OculusGamepadCamera(name, position, scene) {
  23501. var _this = this;
  23502. _super.call(this, name, position, scene);
  23503. this.angularSensibility = 200;
  23504. this.moveSensibility = 75;
  23505. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  23506. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  23507. this.subCameras.push(this._leftCamera);
  23508. this.subCameras.push(this._rightCamera);
  23509. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  23510. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23511. _this._onNewGameConnected(gamepad);
  23512. });
  23513. }
  23514. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23515. // Only the first gamepad can control the camera
  23516. if (gamepad.index === 0) {
  23517. this._gamepad = gamepad;
  23518. }
  23519. };
  23520. OculusGamepadCamera.prototype._update = function () {
  23521. this._leftCamera.position.copyFrom(this.position);
  23522. this._rightCamera.position.copyFrom(this.position);
  23523. this._updateCamera(this._leftCamera);
  23524. this._updateCamera(this._rightCamera);
  23525. _super.prototype._update.call(this);
  23526. };
  23527. OculusGamepadCamera.prototype._checkInputs = function () {
  23528. if (!this._gamepad) {
  23529. return;
  23530. }
  23531. var LSValues = this._gamepad.leftStick;
  23532. var normalizedLX = LSValues.x / this.moveSensibility;
  23533. var normalizedLY = LSValues.y / this.moveSensibility;
  23534. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23535. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23536. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23537. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23538. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23539. };
  23540. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  23541. camera.minZ = this.minZ;
  23542. camera.maxZ = this.maxZ;
  23543. camera.rotation.x = this.rotation.x;
  23544. camera.rotation.y = this.rotation.y;
  23545. camera.rotation.z = this.rotation.z;
  23546. };
  23547. // Oculus events
  23548. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  23549. var yaw = evt.alpha / 180 * Math.PI;
  23550. var pitch = evt.beta / 180 * Math.PI;
  23551. var roll = evt.gamma / 180 * Math.PI;
  23552. if (!this._offsetOrientation) {
  23553. this._offsetOrientation = {
  23554. yaw: yaw,
  23555. pitch: pitch,
  23556. roll: roll
  23557. };
  23558. return;
  23559. }
  23560. else {
  23561. this.rotation.y += yaw - this._offsetOrientation.yaw;
  23562. this.rotation.x += pitch - this._offsetOrientation.pitch;
  23563. this.rotation.z += this._offsetOrientation.roll - roll;
  23564. this._offsetOrientation.yaw = yaw;
  23565. this._offsetOrientation.pitch = pitch;
  23566. this._offsetOrientation.roll = roll;
  23567. }
  23568. };
  23569. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  23570. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23571. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  23572. };
  23573. OculusGamepadCamera.prototype.detachControl = function (element) {
  23574. _super.prototype.detachControl.call(this, element);
  23575. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  23576. };
  23577. OculusGamepadCamera.prototype.dispose = function () {
  23578. this._gamepads.dispose();
  23579. _super.prototype.dispose.call(this);
  23580. };
  23581. return OculusGamepadCamera;
  23582. })(BABYLON.FreeCamera);
  23583. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  23584. })(BABYLON || (BABYLON = {}));
  23585. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  23586. var __extends = this.__extends || function (d, b) {
  23587. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23588. function __() { this.constructor = d; }
  23589. __.prototype = b.prototype;
  23590. d.prototype = new __();
  23591. };
  23592. var BABYLON;
  23593. (function (BABYLON) {
  23594. // We're mainly based on the logic defined into the FreeCamera code
  23595. var VirtualJoysticksCamera = (function (_super) {
  23596. __extends(VirtualJoysticksCamera, _super);
  23597. function VirtualJoysticksCamera(name, position, scene) {
  23598. _super.call(this, name, position, scene);
  23599. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  23600. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  23601. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  23602. this._leftjoystick.setJoystickSensibility(0.15);
  23603. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  23604. this._rightjoystick.setAxisForUpDown(0 /* X */);
  23605. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  23606. this._rightjoystick.reverseUpDown = true;
  23607. this._rightjoystick.setJoystickSensibility(0.05);
  23608. this._rightjoystick.setJoystickColor("yellow");
  23609. }
  23610. VirtualJoysticksCamera.prototype._checkInputs = function () {
  23611. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23612. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  23613. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23614. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  23615. if (!this._leftjoystick.pressed) {
  23616. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  23617. }
  23618. if (!this._rightjoystick.pressed) {
  23619. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  23620. }
  23621. };
  23622. VirtualJoysticksCamera.prototype.dispose = function () {
  23623. this._leftjoystick.releaseCanvas();
  23624. _super.prototype.dispose.call(this);
  23625. };
  23626. return VirtualJoysticksCamera;
  23627. })(BABYLON.FreeCamera);
  23628. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  23629. })(BABYLON || (BABYLON = {}));
  23630. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  23631. var __extends = this.__extends || function (d, b) {
  23632. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23633. function __() { this.constructor = d; }
  23634. __.prototype = b.prototype;
  23635. d.prototype = new __();
  23636. };
  23637. var BABYLON;
  23638. (function (BABYLON) {
  23639. var ShaderMaterial = (function (_super) {
  23640. __extends(ShaderMaterial, _super);
  23641. function ShaderMaterial(name, scene, shaderPath, options) {
  23642. _super.call(this, name, scene);
  23643. this._textures = new Array();
  23644. this._floats = new Array();
  23645. this._floatsArrays = {};
  23646. this._colors3 = new Array();
  23647. this._colors4 = new Array();
  23648. this._vectors2 = new Array();
  23649. this._vectors3 = new Array();
  23650. this._matrices = new Array();
  23651. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  23652. this._shaderPath = shaderPath;
  23653. options.needAlphaBlending = options.needAlphaBlending || false;
  23654. options.needAlphaTesting = options.needAlphaTesting || false;
  23655. options.attributes = options.attributes || ["position", "normal", "uv"];
  23656. options.uniforms = options.uniforms || ["worldViewProjection"];
  23657. options.samplers = options.samplers || [];
  23658. this._options = options;
  23659. }
  23660. ShaderMaterial.prototype.needAlphaBlending = function () {
  23661. return this._options.needAlphaBlending;
  23662. };
  23663. ShaderMaterial.prototype.needAlphaTesting = function () {
  23664. return this._options.needAlphaTesting;
  23665. };
  23666. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  23667. if (this._options.uniforms.indexOf(uniformName) === -1) {
  23668. this._options.uniforms.push(uniformName);
  23669. }
  23670. };
  23671. ShaderMaterial.prototype.setTexture = function (name, texture) {
  23672. if (this._options.samplers.indexOf(name) === -1) {
  23673. this._options.samplers.push(name);
  23674. }
  23675. this._textures[name] = texture;
  23676. return this;
  23677. };
  23678. ShaderMaterial.prototype.setFloat = function (name, value) {
  23679. this._checkUniform(name);
  23680. this._floats[name] = value;
  23681. return this;
  23682. };
  23683. ShaderMaterial.prototype.setFloats = function (name, value) {
  23684. this._checkUniform(name);
  23685. this._floatsArrays[name] = value;
  23686. return this;
  23687. };
  23688. ShaderMaterial.prototype.setColor3 = function (name, value) {
  23689. this._checkUniform(name);
  23690. this._colors3[name] = value;
  23691. return this;
  23692. };
  23693. ShaderMaterial.prototype.setColor4 = function (name, value) {
  23694. this._checkUniform(name);
  23695. this._colors4[name] = value;
  23696. return this;
  23697. };
  23698. ShaderMaterial.prototype.setVector2 = function (name, value) {
  23699. this._checkUniform(name);
  23700. this._vectors2[name] = value;
  23701. return this;
  23702. };
  23703. ShaderMaterial.prototype.setVector3 = function (name, value) {
  23704. this._checkUniform(name);
  23705. this._vectors3[name] = value;
  23706. return this;
  23707. };
  23708. ShaderMaterial.prototype.setMatrix = function (name, value) {
  23709. this._checkUniform(name);
  23710. this._matrices[name] = value;
  23711. return this;
  23712. };
  23713. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  23714. var scene = this.getScene();
  23715. var engine = scene.getEngine();
  23716. if (!this.checkReadyOnEveryCall) {
  23717. if (this._renderId === scene.getRenderId()) {
  23718. return true;
  23719. }
  23720. }
  23721. // Instances
  23722. var defines = [];
  23723. var fallbacks = new BABYLON.EffectFallbacks();
  23724. if (useInstances) {
  23725. defines.push("#define INSTANCES");
  23726. }
  23727. // Bones
  23728. if (mesh && mesh.useBones) {
  23729. defines.push("#define BONES");
  23730. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23731. defines.push("#define BONES4");
  23732. fallbacks.addFallback(0, "BONES4");
  23733. }
  23734. // Alpha test
  23735. if (engine.getAlphaTesting()) {
  23736. defines.push("#define ALPHATEST");
  23737. }
  23738. var previousEffect = this._effect;
  23739. var join = defines.join("\n");
  23740. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  23741. if (!this._effect.isReady()) {
  23742. return false;
  23743. }
  23744. if (previousEffect !== this._effect) {
  23745. scene.resetCachedMaterial();
  23746. }
  23747. this._renderId = scene.getRenderId();
  23748. return true;
  23749. };
  23750. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23751. var scene = this.getScene();
  23752. if (this._options.uniforms.indexOf("world") !== -1) {
  23753. this._effect.setMatrix("world", world);
  23754. }
  23755. if (this._options.uniforms.indexOf("worldView") !== -1) {
  23756. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  23757. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  23758. }
  23759. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  23760. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  23761. }
  23762. };
  23763. ShaderMaterial.prototype.bind = function (world, mesh) {
  23764. // Std values
  23765. this.bindOnlyWorldMatrix(world);
  23766. if (this.getScene().getCachedMaterial() !== this) {
  23767. if (this._options.uniforms.indexOf("view") !== -1) {
  23768. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  23769. }
  23770. if (this._options.uniforms.indexOf("projection") !== -1) {
  23771. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  23772. }
  23773. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  23774. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23775. }
  23776. // Bones
  23777. if (mesh && mesh.useBones) {
  23778. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23779. }
  23780. for (var name in this._textures) {
  23781. this._effect.setTexture(name, this._textures[name]);
  23782. }
  23783. for (name in this._floats) {
  23784. this._effect.setFloat(name, this._floats[name]);
  23785. }
  23786. for (name in this._floatsArrays) {
  23787. this._effect.setArray(name, this._floatsArrays[name]);
  23788. }
  23789. for (name in this._colors3) {
  23790. this._effect.setColor3(name, this._colors3[name]);
  23791. }
  23792. for (name in this._colors4) {
  23793. var color = this._colors4[name];
  23794. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23795. }
  23796. for (name in this._vectors2) {
  23797. this._effect.setVector2(name, this._vectors2[name]);
  23798. }
  23799. for (name in this._vectors3) {
  23800. this._effect.setVector3(name, this._vectors3[name]);
  23801. }
  23802. for (name in this._matrices) {
  23803. this._effect.setMatrix(name, this._matrices[name]);
  23804. }
  23805. }
  23806. _super.prototype.bind.call(this, world, mesh);
  23807. };
  23808. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  23809. for (var name in this._textures) {
  23810. this._textures[name].dispose();
  23811. }
  23812. this._textures = [];
  23813. _super.prototype.dispose.call(this, forceDisposeEffect);
  23814. };
  23815. return ShaderMaterial;
  23816. })(BABYLON.Material);
  23817. BABYLON.ShaderMaterial = ShaderMaterial;
  23818. })(BABYLON || (BABYLON = {}));
  23819. //# sourceMappingURL=babylon.shaderMaterial.js.map
  23820. var BABYLON;
  23821. (function (BABYLON) {
  23822. var VertexData = (function () {
  23823. function VertexData() {
  23824. }
  23825. VertexData.prototype.set = function (data, kind) {
  23826. switch (kind) {
  23827. case BABYLON.VertexBuffer.PositionKind:
  23828. this.positions = data;
  23829. break;
  23830. case BABYLON.VertexBuffer.NormalKind:
  23831. this.normals = data;
  23832. break;
  23833. case BABYLON.VertexBuffer.UVKind:
  23834. this.uvs = data;
  23835. break;
  23836. case BABYLON.VertexBuffer.UV2Kind:
  23837. this.uv2s = data;
  23838. break;
  23839. case BABYLON.VertexBuffer.ColorKind:
  23840. this.colors = data;
  23841. break;
  23842. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23843. this.matricesIndices = data;
  23844. break;
  23845. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23846. this.matricesWeights = data;
  23847. break;
  23848. }
  23849. };
  23850. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23851. this._applyTo(mesh, updatable);
  23852. };
  23853. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23854. this._applyTo(geometry, updatable);
  23855. };
  23856. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23857. this._update(mesh);
  23858. };
  23859. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23860. this._update(geometry);
  23861. };
  23862. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23863. if (this.positions) {
  23864. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23865. }
  23866. if (this.normals) {
  23867. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23868. }
  23869. if (this.uvs) {
  23870. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23871. }
  23872. if (this.uv2s) {
  23873. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  23874. }
  23875. if (this.colors) {
  23876. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23877. }
  23878. if (this.matricesIndices) {
  23879. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23880. }
  23881. if (this.matricesWeights) {
  23882. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23883. }
  23884. if (this.indices) {
  23885. meshOrGeometry.setIndices(this.indices);
  23886. }
  23887. };
  23888. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23889. if (this.positions) {
  23890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23891. }
  23892. if (this.normals) {
  23893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23894. }
  23895. if (this.uvs) {
  23896. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23897. }
  23898. if (this.uv2s) {
  23899. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  23900. }
  23901. if (this.colors) {
  23902. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23903. }
  23904. if (this.matricesIndices) {
  23905. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23906. }
  23907. if (this.matricesWeights) {
  23908. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23909. }
  23910. if (this.indices) {
  23911. meshOrGeometry.setIndices(this.indices);
  23912. }
  23913. };
  23914. VertexData.prototype.transform = function (matrix) {
  23915. var transformed = BABYLON.Vector3.Zero();
  23916. if (this.positions) {
  23917. var position = BABYLON.Vector3.Zero();
  23918. for (var index = 0; index < this.positions.length; index += 3) {
  23919. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23920. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23921. this.positions[index] = transformed.x;
  23922. this.positions[index + 1] = transformed.y;
  23923. this.positions[index + 2] = transformed.z;
  23924. }
  23925. }
  23926. if (this.normals) {
  23927. var normal = BABYLON.Vector3.Zero();
  23928. for (index = 0; index < this.normals.length; index += 3) {
  23929. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23930. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23931. this.normals[index] = transformed.x;
  23932. this.normals[index + 1] = transformed.y;
  23933. this.normals[index + 2] = transformed.z;
  23934. }
  23935. }
  23936. };
  23937. VertexData.prototype.merge = function (other) {
  23938. if (other.indices) {
  23939. if (!this.indices) {
  23940. this.indices = [];
  23941. }
  23942. var offset = this.positions ? this.positions.length / 3 : 0;
  23943. for (var index = 0; index < other.indices.length; index++) {
  23944. this.indices.push(other.indices[index] + offset);
  23945. }
  23946. }
  23947. if (other.positions) {
  23948. if (!this.positions) {
  23949. this.positions = [];
  23950. }
  23951. for (index = 0; index < other.positions.length; index++) {
  23952. this.positions.push(other.positions[index]);
  23953. }
  23954. }
  23955. if (other.normals) {
  23956. if (!this.normals) {
  23957. this.normals = [];
  23958. }
  23959. for (index = 0; index < other.normals.length; index++) {
  23960. this.normals.push(other.normals[index]);
  23961. }
  23962. }
  23963. if (other.uvs) {
  23964. if (!this.uvs) {
  23965. this.uvs = [];
  23966. }
  23967. for (index = 0; index < other.uvs.length; index++) {
  23968. this.uvs.push(other.uvs[index]);
  23969. }
  23970. }
  23971. if (other.uv2s) {
  23972. if (!this.uv2s) {
  23973. this.uv2s = [];
  23974. }
  23975. for (index = 0; index < other.uv2s.length; index++) {
  23976. this.uv2s.push(other.uv2s[index]);
  23977. }
  23978. }
  23979. if (other.matricesIndices) {
  23980. if (!this.matricesIndices) {
  23981. this.matricesIndices = [];
  23982. }
  23983. for (index = 0; index < other.matricesIndices.length; index++) {
  23984. this.matricesIndices.push(other.matricesIndices[index]);
  23985. }
  23986. }
  23987. if (other.matricesWeights) {
  23988. if (!this.matricesWeights) {
  23989. this.matricesWeights = [];
  23990. }
  23991. for (index = 0; index < other.matricesWeights.length; index++) {
  23992. this.matricesWeights.push(other.matricesWeights[index]);
  23993. }
  23994. }
  23995. if (other.colors) {
  23996. if (!this.colors) {
  23997. this.colors = [];
  23998. }
  23999. for (index = 0; index < other.colors.length; index++) {
  24000. this.colors.push(other.colors[index]);
  24001. }
  24002. }
  24003. };
  24004. // Statics
  24005. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24006. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24007. };
  24008. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24009. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24010. };
  24011. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24012. var result = new VertexData();
  24013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24014. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24015. }
  24016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24017. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24018. }
  24019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24020. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24021. }
  24022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24023. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24024. }
  24025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24026. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24027. }
  24028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24029. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24030. }
  24031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24032. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24033. }
  24034. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24035. return result;
  24036. };
  24037. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24038. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24039. closeArray = closeArray || false;
  24040. closePath = closePath || false;
  24041. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24042. offset = offset || defaultOffset;
  24043. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24044. var positions = [];
  24045. var indices = [];
  24046. var normals = [];
  24047. var uvs = [];
  24048. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24049. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24050. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24051. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24052. var minlg; // minimal length among all paths from pathArray
  24053. var lg = []; // array of path lengths : nb of vertex per path
  24054. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24055. var p; // path iterator
  24056. var i; // point iterator
  24057. var j; // point iterator
  24058. // if single path in pathArray
  24059. if (pathArray.length < 2) {
  24060. var ar1 = [];
  24061. var ar2 = [];
  24062. for (i = 0; i < pathArray[0].length - offset; i++) {
  24063. ar1.push(pathArray[0][i]);
  24064. ar2.push(pathArray[0][i + offset]);
  24065. }
  24066. pathArray = [ar1, ar2];
  24067. }
  24068. // positions and horizontal distances (u)
  24069. var idc = 0;
  24070. minlg = pathArray[0].length;
  24071. for (p = 0; p < pathArray.length; p++) {
  24072. uTotalDistance[p] = 0;
  24073. us[p] = [0];
  24074. var path = pathArray[p];
  24075. var l = path.length;
  24076. minlg = (minlg < l) ? minlg : l;
  24077. lg[p] = l;
  24078. idx[p] = idc;
  24079. j = 0;
  24080. while (j < l) {
  24081. positions.push(path[j].x, path[j].y, path[j].z);
  24082. if (j > 0) {
  24083. var vectlg = path[j].subtract(path[j - 1]).length();
  24084. var dist = vectlg + uTotalDistance[p];
  24085. us[p].push(dist);
  24086. uTotalDistance[p] = dist;
  24087. }
  24088. j++;
  24089. }
  24090. if (closePath) {
  24091. vectlg = path[0].subtract(path[j - 1]).length();
  24092. dist = vectlg + uTotalDistance[p];
  24093. uTotalDistance[p] = dist;
  24094. }
  24095. idc += l;
  24096. }
  24097. for (i = 0; i < minlg; i++) {
  24098. vTotalDistance[i] = 0;
  24099. vs[i] = [0];
  24100. var path1;
  24101. var path2;
  24102. for (p = 0; p < pathArray.length - 1; p++) {
  24103. path1 = pathArray[p];
  24104. path2 = pathArray[p + 1];
  24105. vectlg = path2[i].subtract(path1[i]).length();
  24106. dist = vectlg + vTotalDistance[i];
  24107. vs[i].push(dist);
  24108. vTotalDistance[i] = dist;
  24109. }
  24110. if (closeArray) {
  24111. path1 = pathArray[p];
  24112. path2 = pathArray[0];
  24113. vectlg = path2[i].subtract(path1[i]).length();
  24114. dist = vectlg + vTotalDistance[i];
  24115. vTotalDistance[i] = dist;
  24116. }
  24117. }
  24118. // uvs
  24119. var u;
  24120. var v;
  24121. for (p = 0; p < pathArray.length; p++) {
  24122. for (i = 0; i < minlg; i++) {
  24123. u = us[p][i] / uTotalDistance[p];
  24124. v = vs[i][p] / vTotalDistance[i];
  24125. uvs.push(u, v);
  24126. }
  24127. }
  24128. // indices
  24129. p = 0; // path index
  24130. var pi = 0; // positions array index
  24131. var l1 = lg[p] - 1; // path1 length
  24132. var l2 = lg[p + 1] - 1; // path2 length
  24133. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24134. var shft = idx[1] - idx[0]; // shift
  24135. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  24136. var t1; // two consecutive triangles, so 4 points : point1
  24137. var t2; // point2
  24138. var t3; // point3
  24139. var t4; // point4
  24140. while (pi <= min && p < path1nb) {
  24141. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  24142. t1 = pi;
  24143. t2 = pi + shft;
  24144. t3 = pi + 1;
  24145. t4 = pi + shft + 1;
  24146. indices.push(pi, pi + shft, pi + 1);
  24147. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24148. pi += 1;
  24149. if (pi === min) {
  24150. if (closePath) {
  24151. indices.push(pi, pi + shft, idx[p]);
  24152. indices.push(idx[p] + shft, idx[p], pi + shft);
  24153. t3 = idx[p];
  24154. t4 = idx[p] + shft;
  24155. }
  24156. p++;
  24157. if (p === lg.length - 1) {
  24158. shft = idx[0] - idx[p];
  24159. l1 = lg[p] - 1;
  24160. l2 = lg[0] - 1;
  24161. }
  24162. else {
  24163. shft = idx[p + 1] - idx[p];
  24164. l1 = lg[p] - 1;
  24165. l2 = lg[p + 1] - 1;
  24166. }
  24167. pi = idx[p];
  24168. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24169. }
  24170. }
  24171. // normals
  24172. VertexData.ComputeNormals(positions, indices, normals);
  24173. // sides
  24174. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24175. // Result
  24176. var vertexData = new VertexData();
  24177. vertexData.indices = indices;
  24178. vertexData.positions = positions;
  24179. vertexData.normals = normals;
  24180. vertexData.uvs = uvs;
  24181. return vertexData;
  24182. };
  24183. VertexData.CreateBox = function (size, sideOrientation) {
  24184. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24185. var normalsSource = [
  24186. new BABYLON.Vector3(0, 0, 1),
  24187. new BABYLON.Vector3(0, 0, -1),
  24188. new BABYLON.Vector3(1, 0, 0),
  24189. new BABYLON.Vector3(-1, 0, 0),
  24190. new BABYLON.Vector3(0, 1, 0),
  24191. new BABYLON.Vector3(0, -1, 0)
  24192. ];
  24193. var indices = [];
  24194. var positions = [];
  24195. var normals = [];
  24196. var uvs = [];
  24197. size = size || 1;
  24198. for (var index = 0; index < normalsSource.length; index++) {
  24199. var normal = normalsSource[index];
  24200. // Get two vectors perpendicular to the face normal and to each other.
  24201. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24202. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24203. // Six indices (two triangles) per face.
  24204. var verticesLength = positions.length / 3;
  24205. indices.push(verticesLength);
  24206. indices.push(verticesLength + 1);
  24207. indices.push(verticesLength + 2);
  24208. indices.push(verticesLength);
  24209. indices.push(verticesLength + 2);
  24210. indices.push(verticesLength + 3);
  24211. // Four vertices per face.
  24212. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  24213. positions.push(vertex.x, vertex.y, vertex.z);
  24214. normals.push(normal.x, normal.y, normal.z);
  24215. uvs.push(1.0, 1.0);
  24216. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  24217. positions.push(vertex.x, vertex.y, vertex.z);
  24218. normals.push(normal.x, normal.y, normal.z);
  24219. uvs.push(0.0, 1.0);
  24220. vertex = normal.add(side1).add(side2).scale(size / 2);
  24221. positions.push(vertex.x, vertex.y, vertex.z);
  24222. normals.push(normal.x, normal.y, normal.z);
  24223. uvs.push(0.0, 0.0);
  24224. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  24225. positions.push(vertex.x, vertex.y, vertex.z);
  24226. normals.push(normal.x, normal.y, normal.z);
  24227. uvs.push(1.0, 0.0);
  24228. }
  24229. // sides
  24230. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24231. // Result
  24232. var vertexData = new VertexData();
  24233. vertexData.indices = indices;
  24234. vertexData.positions = positions;
  24235. vertexData.normals = normals;
  24236. vertexData.uvs = uvs;
  24237. return vertexData;
  24238. };
  24239. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  24240. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24241. segments = segments || 32;
  24242. diameter = diameter || 1;
  24243. var radius = diameter / 2;
  24244. var totalZRotationSteps = 2 + segments;
  24245. var totalYRotationSteps = 2 * totalZRotationSteps;
  24246. var indices = [];
  24247. var positions = [];
  24248. var normals = [];
  24249. var uvs = [];
  24250. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24251. var normalizedZ = zRotationStep / totalZRotationSteps;
  24252. var angleZ = (normalizedZ * Math.PI);
  24253. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24254. var normalizedY = yRotationStep / totalYRotationSteps;
  24255. var angleY = normalizedY * Math.PI * 2;
  24256. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24257. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24258. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24259. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24260. var vertex = complete.scale(radius);
  24261. var normal = BABYLON.Vector3.Normalize(vertex);
  24262. positions.push(vertex.x, vertex.y, vertex.z);
  24263. normals.push(normal.x, normal.y, normal.z);
  24264. uvs.push(normalizedZ, normalizedY);
  24265. }
  24266. if (zRotationStep > 0) {
  24267. var verticesCount = positions.length / 3;
  24268. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24269. indices.push((firstIndex));
  24270. indices.push((firstIndex + 1));
  24271. indices.push(firstIndex + totalYRotationSteps + 1);
  24272. indices.push((firstIndex + totalYRotationSteps + 1));
  24273. indices.push((firstIndex + 1));
  24274. indices.push((firstIndex + totalYRotationSteps + 2));
  24275. }
  24276. }
  24277. }
  24278. // Sides
  24279. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24280. // Result
  24281. var vertexData = new VertexData();
  24282. vertexData.indices = indices;
  24283. vertexData.positions = positions;
  24284. vertexData.normals = normals;
  24285. vertexData.uvs = uvs;
  24286. return vertexData;
  24287. };
  24288. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  24289. if (subdivisions === void 0) { subdivisions = 1; }
  24290. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24291. var radiusTop = diameterTop / 2;
  24292. var radiusBottom = diameterBottom / 2;
  24293. var indices = [];
  24294. var positions = [];
  24295. var normals = [];
  24296. var uvs = [];
  24297. height = height || 1;
  24298. diameterTop = diameterTop || 0.5;
  24299. diameterBottom = diameterBottom || 1;
  24300. tessellation = tessellation || 16;
  24301. subdivisions = subdivisions || 1;
  24302. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  24303. var getCircleVector = function (i) {
  24304. var angle = (i * 2.0 * Math.PI / tessellation);
  24305. var dx = Math.cos(angle);
  24306. var dz = Math.sin(angle);
  24307. return new BABYLON.Vector3(dx, 0, dz);
  24308. };
  24309. var createCylinderCap = function (isTop) {
  24310. var radius = isTop ? radiusTop : radiusBottom;
  24311. if (radius === 0) {
  24312. return;
  24313. }
  24314. var vbase = positions.length / 3;
  24315. var offset = new BABYLON.Vector3(0, height / 2, 0);
  24316. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24317. if (!isTop) {
  24318. offset.scaleInPlace(-1);
  24319. textureScale.x = -textureScale.x;
  24320. }
  24321. for (var i = 0; i < tessellation; i++) {
  24322. var circleVector = getCircleVector(i);
  24323. var position = circleVector.scale(radius).add(offset);
  24324. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  24325. positions.push(position.x, position.y, position.z);
  24326. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24327. }
  24328. for (i = 0; i < tessellation - 2; i++) {
  24329. if (!isTop) {
  24330. indices.push(vbase);
  24331. indices.push(vbase + (i + 2) % tessellation);
  24332. indices.push(vbase + (i + 1) % tessellation);
  24333. }
  24334. else {
  24335. indices.push(vbase);
  24336. indices.push(vbase + (i + 1) % tessellation);
  24337. indices.push(vbase + (i + 2) % tessellation);
  24338. }
  24339. }
  24340. };
  24341. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  24342. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  24343. var stride = tessellation + 1;
  24344. for (var i = 0; i <= tessellation; i++) {
  24345. var circleVector = getCircleVector(i);
  24346. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  24347. var position, radius = radiusBottom;
  24348. for (var s = 0; s <= subdivisions; s++) {
  24349. // Update variables
  24350. position = circleVector.scale(radius);
  24351. position.addInPlace(base.add(offset.scale(s)));
  24352. textureCoordinate.y += 1 / subdivisions;
  24353. radius += (radiusTop - radiusBottom) / subdivisions;
  24354. // Push in arrays
  24355. positions.push(position.x, position.y, position.z);
  24356. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24357. }
  24358. }
  24359. subdivisions += 1;
  24360. for (s = 0; s < subdivisions - 1; s++) {
  24361. for (i = 0; i <= tessellation; i++) {
  24362. indices.push(i * subdivisions + s);
  24363. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24364. indices.push(i * subdivisions + (s + 1));
  24365. indices.push(i * subdivisions + (s + 1));
  24366. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24367. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  24368. }
  24369. }
  24370. // Create flat triangle fan caps to seal the top and bottom.
  24371. createCylinderCap(true);
  24372. createCylinderCap(false);
  24373. // Normals
  24374. VertexData.ComputeNormals(positions, indices, normals);
  24375. // Sides
  24376. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24377. // Result
  24378. var vertexData = new VertexData();
  24379. vertexData.indices = indices;
  24380. vertexData.positions = positions;
  24381. vertexData.normals = normals;
  24382. vertexData.uvs = uvs;
  24383. return vertexData;
  24384. };
  24385. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  24386. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24387. var indices = [];
  24388. var positions = [];
  24389. var normals = [];
  24390. var uvs = [];
  24391. diameter = diameter || 1;
  24392. thickness = thickness || 0.5;
  24393. tessellation = tessellation || 16;
  24394. var stride = tessellation + 1;
  24395. for (var i = 0; i <= tessellation; i++) {
  24396. var u = i / tessellation;
  24397. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24398. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24399. for (var j = 0; j <= tessellation; j++) {
  24400. var v = 1 - j / tessellation;
  24401. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24402. var dx = Math.cos(innerAngle);
  24403. var dy = Math.sin(innerAngle);
  24404. // Create a vertex.
  24405. var normal = new BABYLON.Vector3(dx, dy, 0);
  24406. var position = normal.scale(thickness / 2);
  24407. var textureCoordinate = new BABYLON.Vector2(u, v);
  24408. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24409. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24410. positions.push(position.x, position.y, position.z);
  24411. normals.push(normal.x, normal.y, normal.z);
  24412. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24413. // And create indices for two triangles.
  24414. var nextI = (i + 1) % stride;
  24415. var nextJ = (j + 1) % stride;
  24416. indices.push(i * stride + j);
  24417. indices.push(i * stride + nextJ);
  24418. indices.push(nextI * stride + j);
  24419. indices.push(i * stride + nextJ);
  24420. indices.push(nextI * stride + nextJ);
  24421. indices.push(nextI * stride + j);
  24422. }
  24423. }
  24424. // Sides
  24425. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24426. // Result
  24427. var vertexData = new VertexData();
  24428. vertexData.indices = indices;
  24429. vertexData.positions = positions;
  24430. vertexData.normals = normals;
  24431. vertexData.uvs = uvs;
  24432. return vertexData;
  24433. };
  24434. VertexData.CreateLines = function (points) {
  24435. var indices = [];
  24436. var positions = [];
  24437. for (var index = 0; index < points.length; index++) {
  24438. positions.push(points[index].x, points[index].y, points[index].z);
  24439. if (index > 0) {
  24440. indices.push(index - 1);
  24441. indices.push(index);
  24442. }
  24443. }
  24444. // Result
  24445. var vertexData = new VertexData();
  24446. vertexData.indices = indices;
  24447. vertexData.positions = positions;
  24448. return vertexData;
  24449. };
  24450. VertexData.CreateGround = function (width, height, subdivisions) {
  24451. var indices = [];
  24452. var positions = [];
  24453. var normals = [];
  24454. var uvs = [];
  24455. var row, col;
  24456. width = width || 1;
  24457. height = height || 1;
  24458. subdivisions = subdivisions || 1;
  24459. for (row = 0; row <= subdivisions; row++) {
  24460. for (col = 0; col <= subdivisions; col++) {
  24461. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24462. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24463. positions.push(position.x, position.y, position.z);
  24464. normals.push(normal.x, normal.y, normal.z);
  24465. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24466. }
  24467. }
  24468. for (row = 0; row < subdivisions; row++) {
  24469. for (col = 0; col < subdivisions; col++) {
  24470. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24471. indices.push(col + 1 + row * (subdivisions + 1));
  24472. indices.push(col + row * (subdivisions + 1));
  24473. indices.push(col + (row + 1) * (subdivisions + 1));
  24474. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24475. indices.push(col + row * (subdivisions + 1));
  24476. }
  24477. }
  24478. // Result
  24479. var vertexData = new VertexData();
  24480. vertexData.indices = indices;
  24481. vertexData.positions = positions;
  24482. vertexData.normals = normals;
  24483. vertexData.uvs = uvs;
  24484. return vertexData;
  24485. };
  24486. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  24487. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  24488. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  24489. var indices = [];
  24490. var positions = [];
  24491. var normals = [];
  24492. var uvs = [];
  24493. var row, col, tileRow, tileCol;
  24494. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24495. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24496. precision.w = (precision.w < 1) ? 1 : precision.w;
  24497. precision.h = (precision.h < 1) ? 1 : precision.h;
  24498. var tileSize = {
  24499. 'w': (xmax - xmin) / subdivisions.w,
  24500. 'h': (zmax - zmin) / subdivisions.h
  24501. };
  24502. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24503. // Indices
  24504. var base = positions.length / 3;
  24505. var rowLength = precision.w + 1;
  24506. for (row = 0; row < precision.h; row++) {
  24507. for (col = 0; col < precision.w; col++) {
  24508. var square = [
  24509. base + col + row * rowLength,
  24510. base + (col + 1) + row * rowLength,
  24511. base + (col + 1) + (row + 1) * rowLength,
  24512. base + col + (row + 1) * rowLength
  24513. ];
  24514. indices.push(square[1]);
  24515. indices.push(square[2]);
  24516. indices.push(square[3]);
  24517. indices.push(square[0]);
  24518. indices.push(square[1]);
  24519. indices.push(square[3]);
  24520. }
  24521. }
  24522. // Position, normals and uvs
  24523. var position = BABYLON.Vector3.Zero();
  24524. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24525. for (row = 0; row <= precision.h; row++) {
  24526. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24527. for (col = 0; col <= precision.w; col++) {
  24528. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24529. position.y = 0;
  24530. positions.push(position.x, position.y, position.z);
  24531. normals.push(normal.x, normal.y, normal.z);
  24532. uvs.push(col / precision.w, row / precision.h);
  24533. }
  24534. }
  24535. }
  24536. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24537. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24538. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24539. }
  24540. }
  24541. // Result
  24542. var vertexData = new VertexData();
  24543. vertexData.indices = indices;
  24544. vertexData.positions = positions;
  24545. vertexData.normals = normals;
  24546. vertexData.uvs = uvs;
  24547. return vertexData;
  24548. };
  24549. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  24550. var indices = [];
  24551. var positions = [];
  24552. var normals = [];
  24553. var uvs = [];
  24554. var row, col;
  24555. for (row = 0; row <= subdivisions; row++) {
  24556. for (col = 0; col <= subdivisions; col++) {
  24557. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24558. // Compute height
  24559. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  24560. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  24561. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  24562. var r = buffer[pos] / 255.0;
  24563. var g = buffer[pos + 1] / 255.0;
  24564. var b = buffer[pos + 2] / 255.0;
  24565. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24566. position.y = minHeight + (maxHeight - minHeight) * gradient;
  24567. // Add vertex
  24568. positions.push(position.x, position.y, position.z);
  24569. normals.push(0, 0, 0);
  24570. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24571. }
  24572. }
  24573. for (row = 0; row < subdivisions; row++) {
  24574. for (col = 0; col < subdivisions; col++) {
  24575. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24576. indices.push(col + 1 + row * (subdivisions + 1));
  24577. indices.push(col + row * (subdivisions + 1));
  24578. indices.push(col + (row + 1) * (subdivisions + 1));
  24579. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24580. indices.push(col + row * (subdivisions + 1));
  24581. }
  24582. }
  24583. // Normals
  24584. VertexData.ComputeNormals(positions, indices, normals);
  24585. // Result
  24586. var vertexData = new VertexData();
  24587. vertexData.indices = indices;
  24588. vertexData.positions = positions;
  24589. vertexData.normals = normals;
  24590. vertexData.uvs = uvs;
  24591. return vertexData;
  24592. };
  24593. VertexData.CreatePlane = function (size, sideOrientation) {
  24594. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24595. var indices = [];
  24596. var positions = [];
  24597. var normals = [];
  24598. var uvs = [];
  24599. size = size || 1;
  24600. // Vertices
  24601. var halfSize = size / 2.0;
  24602. positions.push(-halfSize, -halfSize, 0);
  24603. normals.push(0, 0, -1.0);
  24604. uvs.push(0.0, 0.0);
  24605. positions.push(halfSize, -halfSize, 0);
  24606. normals.push(0, 0, -1.0);
  24607. uvs.push(1.0, 0.0);
  24608. positions.push(halfSize, halfSize, 0);
  24609. normals.push(0, 0, -1.0);
  24610. uvs.push(1.0, 1.0);
  24611. positions.push(-halfSize, halfSize, 0);
  24612. normals.push(0, 0, -1.0);
  24613. uvs.push(0.0, 1.0);
  24614. // Indices
  24615. indices.push(0);
  24616. indices.push(1);
  24617. indices.push(2);
  24618. indices.push(0);
  24619. indices.push(2);
  24620. indices.push(3);
  24621. // Sides
  24622. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24623. // Result
  24624. var vertexData = new VertexData();
  24625. vertexData.indices = indices;
  24626. vertexData.positions = positions;
  24627. vertexData.normals = normals;
  24628. vertexData.uvs = uvs;
  24629. return vertexData;
  24630. };
  24631. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  24632. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24633. var positions = [];
  24634. var indices = [];
  24635. var normals = [];
  24636. var uvs = [];
  24637. // positions and uvs
  24638. positions.push(0, 0, 0); // disc center first
  24639. uvs.push(0.5, 0.5);
  24640. var step = Math.PI * 2 / tessellation;
  24641. for (var a = 0; a < Math.PI * 2; a += step) {
  24642. var x = Math.cos(a);
  24643. var y = Math.sin(a);
  24644. var u = (x + 1) / 2;
  24645. var v = (1 - y) / 2;
  24646. positions.push(radius * x, radius * y, 0);
  24647. uvs.push(u, v);
  24648. }
  24649. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24650. uvs.push(uvs[2], uvs[3]);
  24651. //indices
  24652. var vertexNb = positions.length / 3;
  24653. for (var i = 1; i < vertexNb - 1; i++) {
  24654. indices.push(i + 1, 0, i);
  24655. }
  24656. // result
  24657. VertexData.ComputeNormals(positions, indices, normals);
  24658. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24659. var vertexData = new VertexData();
  24660. vertexData.indices = indices;
  24661. vertexData.positions = positions;
  24662. vertexData.normals = normals;
  24663. vertexData.uvs = uvs;
  24664. return vertexData;
  24665. };
  24666. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24667. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  24668. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24669. var indices = [];
  24670. var positions = [];
  24671. var normals = [];
  24672. var uvs = [];
  24673. radius = radius || 2;
  24674. tube = tube || 0.5;
  24675. radialSegments = radialSegments || 32;
  24676. tubularSegments = tubularSegments || 32;
  24677. p = p || 2;
  24678. q = q || 3;
  24679. // Helper
  24680. var getPos = function (angle) {
  24681. var cu = Math.cos(angle);
  24682. var su = Math.sin(angle);
  24683. var quOverP = q / p * angle;
  24684. var cs = Math.cos(quOverP);
  24685. var tx = radius * (2 + cs) * 0.5 * cu;
  24686. var ty = radius * (2 + cs) * su * 0.5;
  24687. var tz = radius * Math.sin(quOverP) * 0.5;
  24688. return new BABYLON.Vector3(tx, ty, tz);
  24689. };
  24690. for (var i = 0; i <= radialSegments; i++) {
  24691. var modI = i % radialSegments;
  24692. var u = modI / radialSegments * 2 * p * Math.PI;
  24693. var p1 = getPos(u);
  24694. var p2 = getPos(u + 0.01);
  24695. var tang = p2.subtract(p1);
  24696. var n = p2.add(p1);
  24697. var bitan = BABYLON.Vector3.Cross(tang, n);
  24698. n = BABYLON.Vector3.Cross(bitan, tang);
  24699. bitan.normalize();
  24700. n.normalize();
  24701. for (var j = 0; j < tubularSegments; j++) {
  24702. var modJ = j % tubularSegments;
  24703. var v = modJ / tubularSegments * 2 * Math.PI;
  24704. var cx = -tube * Math.cos(v);
  24705. var cy = tube * Math.sin(v);
  24706. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24707. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24708. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24709. uvs.push(i / radialSegments);
  24710. uvs.push(j / tubularSegments);
  24711. }
  24712. }
  24713. for (i = 0; i < radialSegments; i++) {
  24714. for (j = 0; j < tubularSegments; j++) {
  24715. var jNext = (j + 1) % tubularSegments;
  24716. var a = i * tubularSegments + j;
  24717. var b = (i + 1) * tubularSegments + j;
  24718. var c = (i + 1) * tubularSegments + jNext;
  24719. var d = i * tubularSegments + jNext;
  24720. indices.push(d);
  24721. indices.push(b);
  24722. indices.push(a);
  24723. indices.push(d);
  24724. indices.push(c);
  24725. indices.push(b);
  24726. }
  24727. }
  24728. // Normals
  24729. VertexData.ComputeNormals(positions, indices, normals);
  24730. // Sides
  24731. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24732. // Result
  24733. var vertexData = new VertexData();
  24734. vertexData.indices = indices;
  24735. vertexData.positions = positions;
  24736. vertexData.normals = normals;
  24737. vertexData.uvs = uvs;
  24738. return vertexData;
  24739. };
  24740. // Tools
  24741. /**
  24742. * @param {any} - positions (number[] or Float32Array)
  24743. * @param {any} - indices (number[] or Uint16Array)
  24744. * @param {any} - normals (number[] or Float32Array)
  24745. */
  24746. VertexData.ComputeNormals = function (positions, indices, normals) {
  24747. var index = 0;
  24748. // temp Vector3
  24749. var p1 = BABYLON.Vector3.Zero();
  24750. var p2 = BABYLON.Vector3.Zero();
  24751. var p3 = BABYLON.Vector3.Zero();
  24752. var p1p2 = BABYLON.Vector3.Zero();
  24753. var p3p2 = BABYLON.Vector3.Zero();
  24754. var faceNormal = BABYLON.Vector3.Zero();
  24755. var vertexNormali1 = BABYLON.Vector3.Zero();
  24756. var vertexNormali2 = BABYLON.Vector3.Zero();
  24757. var vertexNormali3 = BABYLON.Vector3.Zero();
  24758. // indice triplet = 1 face
  24759. var nbFaces = indices.length / 3;
  24760. for (index = 0; index < nbFaces; index++) {
  24761. var i1 = indices[index * 3];
  24762. var i2 = indices[index * 3 + 1];
  24763. var i3 = indices[index * 3 + 2];
  24764. // setting the temp V3
  24765. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  24766. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  24767. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  24768. p1.subtractToRef(p2, p1p2);
  24769. p3.subtractToRef(p2, p3p2);
  24770. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24771. faceNormal.normalize();
  24772. // All intermediate results are stored in the normals array :
  24773. // get the normals at i1, i2 and i3 indexes
  24774. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  24775. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  24776. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  24777. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  24778. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  24779. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  24780. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  24781. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  24782. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  24783. // make intermediate vectors3 from normals values
  24784. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  24785. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  24786. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  24787. // add the current face normals to these intermediate vectors3
  24788. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  24789. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  24790. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  24791. // store back intermediate vectors3 into the normals array
  24792. normals[i1 * 3] = vertexNormali1.x;
  24793. normals[i1 * 3 + 1] = vertexNormali1.y;
  24794. normals[i1 * 3 + 2] = vertexNormali1.z;
  24795. normals[i2 * 3] = vertexNormali2.x;
  24796. normals[i2 * 3 + 1] = vertexNormali2.y;
  24797. normals[i2 * 3 + 2] = vertexNormali2.z;
  24798. normals[i3 * 3] = vertexNormali3.x;
  24799. normals[i3 * 3 + 1] = vertexNormali3.y;
  24800. normals[i3 * 3 + 2] = vertexNormali3.z;
  24801. }
  24802. for (index = 0; index < normals.length / 3; index++) {
  24803. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24804. vertexNormali1.normalize();
  24805. normals[index * 3] = vertexNormali1.x;
  24806. normals[index * 3 + 1] = vertexNormali1.y;
  24807. normals[index * 3 + 2] = vertexNormali1.z;
  24808. }
  24809. };
  24810. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24811. var li = indices.length;
  24812. var ln = normals.length;
  24813. var i;
  24814. var n;
  24815. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24816. switch (sideOrientation) {
  24817. case BABYLON.Mesh.FRONTSIDE:
  24818. break;
  24819. case BABYLON.Mesh.BACKSIDE:
  24820. var tmp;
  24821. for (i = 0; i < li; i += 3) {
  24822. tmp = indices[i];
  24823. indices[i] = indices[i + 2];
  24824. indices[i + 2] = tmp;
  24825. }
  24826. for (n = 0; n < ln; n++) {
  24827. normals[n] = -normals[n];
  24828. }
  24829. break;
  24830. case BABYLON.Mesh.DOUBLESIDE:
  24831. // positions
  24832. var lp = positions.length;
  24833. var l = lp / 3;
  24834. for (var p = 0; p < lp; p++) {
  24835. positions[lp + p] = positions[p];
  24836. }
  24837. for (i = 0; i < li; i += 3) {
  24838. indices[i + li] = indices[i + 2] + l;
  24839. indices[i + 1 + li] = indices[i + 1] + l;
  24840. indices[i + 2 + li] = indices[i] + l;
  24841. }
  24842. for (n = 0; n < ln; n++) {
  24843. normals[ln + n] = -normals[n];
  24844. }
  24845. // uvs
  24846. var lu = uvs.length;
  24847. for (var u = 0; u < lu; u++) {
  24848. uvs[u + lu] = uvs[u];
  24849. }
  24850. break;
  24851. }
  24852. };
  24853. return VertexData;
  24854. })();
  24855. BABYLON.VertexData = VertexData;
  24856. })(BABYLON || (BABYLON = {}));
  24857. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  24858. var __extends = this.__extends || function (d, b) {
  24859. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24860. function __() { this.constructor = d; }
  24861. __.prototype = b.prototype;
  24862. d.prototype = new __();
  24863. };
  24864. var BABYLON;
  24865. (function (BABYLON) {
  24866. var buildCamera = function (that, name) {
  24867. that._leftCamera.isIntermediate = true;
  24868. that.subCameras.push(that._leftCamera);
  24869. that.subCameras.push(that._rightCamera);
  24870. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  24871. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  24872. that._anaglyphPostProcess.onApply = function (effect) {
  24873. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  24874. };
  24875. that._update();
  24876. };
  24877. var AnaglyphArcRotateCamera = (function (_super) {
  24878. __extends(AnaglyphArcRotateCamera, _super);
  24879. // ANY
  24880. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  24881. _super.call(this, name, alpha, beta, radius, target, scene);
  24882. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24883. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  24884. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  24885. buildCamera(this, name);
  24886. }
  24887. AnaglyphArcRotateCamera.prototype._update = function () {
  24888. this._updateCamera(this._leftCamera);
  24889. this._updateCamera(this._rightCamera);
  24890. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  24891. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  24892. _super.prototype._update.call(this);
  24893. };
  24894. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  24895. camera.beta = this.beta;
  24896. camera.radius = this.radius;
  24897. camera.minZ = this.minZ;
  24898. camera.maxZ = this.maxZ;
  24899. camera.fov = this.fov;
  24900. camera.target = this.target;
  24901. };
  24902. return AnaglyphArcRotateCamera;
  24903. })(BABYLON.ArcRotateCamera);
  24904. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  24905. var AnaglyphFreeCamera = (function (_super) {
  24906. __extends(AnaglyphFreeCamera, _super);
  24907. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  24908. _super.call(this, name, position, scene);
  24909. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24910. this._transformMatrix = new BABYLON.Matrix();
  24911. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  24912. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  24913. buildCamera(this, name);
  24914. }
  24915. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  24916. var target = this.getTarget();
  24917. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  24918. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  24919. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  24920. };
  24921. AnaglyphFreeCamera.prototype._update = function () {
  24922. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  24923. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  24924. this._updateCamera(this._leftCamera);
  24925. this._updateCamera(this._rightCamera);
  24926. _super.prototype._update.call(this);
  24927. };
  24928. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  24929. camera.minZ = this.minZ;
  24930. camera.maxZ = this.maxZ;
  24931. camera.fov = this.fov;
  24932. camera.viewport = this.viewport;
  24933. camera.setTarget(this.getTarget());
  24934. };
  24935. return AnaglyphFreeCamera;
  24936. })(BABYLON.FreeCamera);
  24937. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  24938. })(BABYLON || (BABYLON = {}));
  24939. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  24940. var __extends = this.__extends || function (d, b) {
  24941. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24942. function __() { this.constructor = d; }
  24943. __.prototype = b.prototype;
  24944. d.prototype = new __();
  24945. };
  24946. var BABYLON;
  24947. (function (BABYLON) {
  24948. var AnaglyphPostProcess = (function (_super) {
  24949. __extends(AnaglyphPostProcess, _super);
  24950. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  24951. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  24952. }
  24953. return AnaglyphPostProcess;
  24954. })(BABYLON.PostProcess);
  24955. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  24956. })(BABYLON || (BABYLON = {}));
  24957. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  24958. var BABYLON;
  24959. (function (BABYLON) {
  24960. var Tags = (function () {
  24961. function Tags() {
  24962. }
  24963. Tags.EnableFor = function (obj) {
  24964. obj._tags = obj._tags || {};
  24965. obj.hasTags = function () {
  24966. return Tags.HasTags(obj);
  24967. };
  24968. obj.addTags = function (tagsString) {
  24969. return Tags.AddTagsTo(obj, tagsString);
  24970. };
  24971. obj.removeTags = function (tagsString) {
  24972. return Tags.RemoveTagsFrom(obj, tagsString);
  24973. };
  24974. obj.matchesTagsQuery = function (tagsQuery) {
  24975. return Tags.MatchesQuery(obj, tagsQuery);
  24976. };
  24977. };
  24978. Tags.DisableFor = function (obj) {
  24979. delete obj._tags;
  24980. delete obj.hasTags;
  24981. delete obj.addTags;
  24982. delete obj.removeTags;
  24983. delete obj.matchesTagsQuery;
  24984. };
  24985. Tags.HasTags = function (obj) {
  24986. if (!obj._tags) {
  24987. return false;
  24988. }
  24989. return !BABYLON.Tools.IsEmpty(obj._tags);
  24990. };
  24991. Tags.GetTags = function (obj) {
  24992. if (!obj._tags) {
  24993. return null;
  24994. }
  24995. return obj._tags;
  24996. };
  24997. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24998. // a tag cannot start with '||', '&&', and '!'
  24999. // it cannot contain whitespaces
  25000. Tags.AddTagsTo = function (obj, tagsString) {
  25001. if (!tagsString) {
  25002. return;
  25003. }
  25004. var tags = tagsString.split(" ");
  25005. for (var t in tags) {
  25006. Tags._AddTagTo(obj, tags[t]);
  25007. }
  25008. };
  25009. Tags._AddTagTo = function (obj, tag) {
  25010. tag = tag.trim();
  25011. if (tag === "" || tag === "true" || tag === "false") {
  25012. return;
  25013. }
  25014. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25015. return;
  25016. }
  25017. Tags.EnableFor(obj);
  25018. obj._tags[tag] = true;
  25019. };
  25020. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25021. if (!Tags.HasTags(obj)) {
  25022. return;
  25023. }
  25024. var tags = tagsString.split(" ");
  25025. for (var t in tags) {
  25026. Tags._RemoveTagFrom(obj, tags[t]);
  25027. }
  25028. };
  25029. Tags._RemoveTagFrom = function (obj, tag) {
  25030. delete obj._tags[tag];
  25031. };
  25032. Tags.MatchesQuery = function (obj, tagsQuery) {
  25033. if (tagsQuery === undefined) {
  25034. return true;
  25035. }
  25036. if (tagsQuery === "") {
  25037. return Tags.HasTags(obj);
  25038. }
  25039. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25040. };
  25041. return Tags;
  25042. })();
  25043. BABYLON.Tags = Tags;
  25044. })(BABYLON || (BABYLON = {}));
  25045. //# sourceMappingURL=babylon.tags.js.map
  25046. var BABYLON;
  25047. (function (BABYLON) {
  25048. var Internals;
  25049. (function (Internals) {
  25050. var AndOrNotEvaluator = (function () {
  25051. function AndOrNotEvaluator() {
  25052. }
  25053. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25054. if (!query.match(/\([^\(\)]*\)/g)) {
  25055. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25056. }
  25057. else {
  25058. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25059. // remove parenthesis
  25060. r = r.slice(1, r.length - 1);
  25061. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25062. });
  25063. }
  25064. if (query === "true") {
  25065. return true;
  25066. }
  25067. if (query === "false") {
  25068. return false;
  25069. }
  25070. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25071. };
  25072. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25073. evaluateCallback = evaluateCallback || (function (r) {
  25074. return r === "true" ? true : false;
  25075. });
  25076. var result;
  25077. var or = parenthesisContent.split("||");
  25078. for (var i in or) {
  25079. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25080. var and = ori.split("&&");
  25081. if (and.length > 1) {
  25082. for (var j = 0; j < and.length; ++j) {
  25083. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25084. if (andj !== "true" && andj !== "false") {
  25085. if (andj[0] === "!") {
  25086. result = !evaluateCallback(andj.substring(1));
  25087. }
  25088. else {
  25089. result = evaluateCallback(andj);
  25090. }
  25091. }
  25092. else {
  25093. result = andj === "true" ? true : false;
  25094. }
  25095. if (!result) {
  25096. ori = "false";
  25097. break;
  25098. }
  25099. }
  25100. }
  25101. if (result || ori === "true") {
  25102. result = true;
  25103. break;
  25104. }
  25105. // result equals false (or undefined)
  25106. if (ori !== "true" && ori !== "false") {
  25107. if (ori[0] === "!") {
  25108. result = !evaluateCallback(ori.substring(1));
  25109. }
  25110. else {
  25111. result = evaluateCallback(ori);
  25112. }
  25113. }
  25114. else {
  25115. result = ori === "true" ? true : false;
  25116. }
  25117. }
  25118. // the whole parenthesis scope is replaced by 'true' or 'false'
  25119. return result ? "true" : "false";
  25120. };
  25121. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25122. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25123. // remove whitespaces
  25124. r = r.replace(/[\s]/g, function () { return ""; });
  25125. return r.length % 2 ? "!" : "";
  25126. });
  25127. booleanString = booleanString.trim();
  25128. if (booleanString === "!true") {
  25129. booleanString = "false";
  25130. }
  25131. else if (booleanString === "!false") {
  25132. booleanString = "true";
  25133. }
  25134. return booleanString;
  25135. };
  25136. return AndOrNotEvaluator;
  25137. })();
  25138. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25139. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25140. })(BABYLON || (BABYLON = {}));
  25141. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  25142. var BABYLON;
  25143. (function (BABYLON) {
  25144. var PostProcessRenderPass = (function () {
  25145. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25146. this._enabled = true;
  25147. this._refCount = 0;
  25148. this._name = name;
  25149. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25150. this.setRenderList(renderList);
  25151. this._renderTexture.onBeforeRender = beforeRender;
  25152. this._renderTexture.onAfterRender = afterRender;
  25153. this._scene = scene;
  25154. this._renderList = renderList;
  25155. }
  25156. // private
  25157. PostProcessRenderPass.prototype._incRefCount = function () {
  25158. if (this._refCount === 0) {
  25159. this._scene.customRenderTargets.push(this._renderTexture);
  25160. }
  25161. return ++this._refCount;
  25162. };
  25163. PostProcessRenderPass.prototype._decRefCount = function () {
  25164. this._refCount--;
  25165. if (this._refCount <= 0) {
  25166. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25167. }
  25168. return this._refCount;
  25169. };
  25170. PostProcessRenderPass.prototype._update = function () {
  25171. this.setRenderList(this._renderList);
  25172. };
  25173. // public
  25174. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25175. this._renderTexture.renderList = renderList;
  25176. };
  25177. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25178. return this._renderTexture;
  25179. };
  25180. return PostProcessRenderPass;
  25181. })();
  25182. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25183. })(BABYLON || (BABYLON = {}));
  25184. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  25185. var BABYLON;
  25186. (function (BABYLON) {
  25187. var PostProcessRenderEffect = (function () {
  25188. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25189. this._engine = engine;
  25190. this._name = name;
  25191. this._singleInstance = singleInstance || true;
  25192. this._getPostProcess = getPostProcess;
  25193. this._cameras = [];
  25194. this._indicesForCamera = [];
  25195. this._postProcesses = {};
  25196. this._renderPasses = {};
  25197. this._renderEffectAsPasses = {};
  25198. }
  25199. PostProcessRenderEffect.prototype._update = function () {
  25200. for (var renderPassName in this._renderPasses) {
  25201. this._renderPasses[renderPassName]._update();
  25202. }
  25203. };
  25204. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25205. this._renderPasses[renderPass._name] = renderPass;
  25206. this._linkParameters();
  25207. };
  25208. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25209. delete this._renderPasses[renderPass._name];
  25210. this._linkParameters();
  25211. };
  25212. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25213. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25214. this._linkParameters();
  25215. };
  25216. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25217. for (var renderPassName in this._renderPasses) {
  25218. if (renderPassName === passName) {
  25219. return this._renderPasses[passName];
  25220. }
  25221. }
  25222. };
  25223. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25224. this._renderPasses = {};
  25225. this._linkParameters();
  25226. };
  25227. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25228. var cameraKey;
  25229. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25230. for (var i = 0; i < _cam.length; i++) {
  25231. var camera = _cam[i];
  25232. var cameraName = camera.name;
  25233. if (this._singleInstance) {
  25234. cameraKey = 0;
  25235. }
  25236. else {
  25237. cameraKey = cameraName;
  25238. }
  25239. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25240. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25241. if (!this._indicesForCamera[cameraName]) {
  25242. this._indicesForCamera[cameraName] = [];
  25243. }
  25244. this._indicesForCamera[cameraName].push(index);
  25245. if (this._cameras.indexOf(camera) === -1) {
  25246. this._cameras[cameraName] = camera;
  25247. }
  25248. for (var passName in this._renderPasses) {
  25249. this._renderPasses[passName]._incRefCount();
  25250. }
  25251. }
  25252. this._linkParameters();
  25253. };
  25254. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25255. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25256. for (var i = 0; i < _cam.length; i++) {
  25257. var camera = _cam[i];
  25258. var cameraName = camera.name;
  25259. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25260. var index = this._cameras.indexOf(cameraName);
  25261. this._indicesForCamera.splice(index, 1);
  25262. this._cameras.splice(index, 1);
  25263. for (var passName in this._renderPasses) {
  25264. this._renderPasses[passName]._decRefCount();
  25265. }
  25266. }
  25267. };
  25268. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25269. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25270. for (var i = 0; i < _cam.length; i++) {
  25271. var camera = _cam[i];
  25272. var cameraName = camera.name;
  25273. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25274. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25275. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25276. }
  25277. }
  25278. for (var passName in this._renderPasses) {
  25279. this._renderPasses[passName]._incRefCount();
  25280. }
  25281. }
  25282. };
  25283. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25284. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25285. for (var i = 0; i < _cam.length; i++) {
  25286. var camera = _cam[i];
  25287. var cameraName = camera.Name;
  25288. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25289. for (var passName in this._renderPasses) {
  25290. this._renderPasses[passName]._decRefCount();
  25291. }
  25292. }
  25293. };
  25294. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25295. if (this._singleInstance) {
  25296. return this._postProcesses[0];
  25297. }
  25298. else {
  25299. return this._postProcesses[camera.name];
  25300. }
  25301. };
  25302. PostProcessRenderEffect.prototype._linkParameters = function () {
  25303. var _this = this;
  25304. for (var index in this._postProcesses) {
  25305. if (this.applyParameters) {
  25306. this.applyParameters(this._postProcesses[index]);
  25307. }
  25308. this._postProcesses[index].onBeforeRender = function (effect) {
  25309. _this._linkTextures(effect);
  25310. };
  25311. }
  25312. };
  25313. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25314. for (var renderPassName in this._renderPasses) {
  25315. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25316. }
  25317. for (var renderEffectName in this._renderEffectAsPasses) {
  25318. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25319. }
  25320. };
  25321. return PostProcessRenderEffect;
  25322. })();
  25323. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25324. })(BABYLON || (BABYLON = {}));
  25325. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  25326. var BABYLON;
  25327. (function (BABYLON) {
  25328. var PostProcessRenderPipeline = (function () {
  25329. function PostProcessRenderPipeline(engine, name) {
  25330. this._engine = engine;
  25331. this._name = name;
  25332. this._renderEffects = {};
  25333. this._renderEffectsForIsolatedPass = {};
  25334. this._cameras = [];
  25335. }
  25336. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25337. this._renderEffects[renderEffect._name] = renderEffect;
  25338. };
  25339. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25340. var renderEffects = this._renderEffects[renderEffectName];
  25341. if (!renderEffects) {
  25342. return;
  25343. }
  25344. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25345. };
  25346. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25347. var renderEffects = this._renderEffects[renderEffectName];
  25348. if (!renderEffects) {
  25349. return;
  25350. }
  25351. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25352. };
  25353. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25354. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25355. var indicesToDelete = [];
  25356. for (var i = 0; i < _cam.length; i++) {
  25357. var camera = _cam[i];
  25358. var cameraName = camera.name;
  25359. if (this._cameras.indexOf(camera) === -1) {
  25360. this._cameras[cameraName] = camera;
  25361. }
  25362. else if (unique) {
  25363. indicesToDelete.push(i);
  25364. }
  25365. }
  25366. for (var i = 0; i < indicesToDelete.length; i++) {
  25367. cameras.splice(indicesToDelete[i], 1);
  25368. }
  25369. for (var renderEffectName in this._renderEffects) {
  25370. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25371. }
  25372. };
  25373. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25374. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25375. for (var renderEffectName in this._renderEffects) {
  25376. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25377. }
  25378. for (var i = 0; i < _cam.length; i++) {
  25379. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25380. }
  25381. };
  25382. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25383. var _this = this;
  25384. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25385. var pass = null;
  25386. for (var renderEffectName in this._renderEffects) {
  25387. pass = this._renderEffects[renderEffectName].getPass(passName);
  25388. if (pass != null) {
  25389. break;
  25390. }
  25391. }
  25392. if (pass === null) {
  25393. return;
  25394. }
  25395. for (var renderEffectName in this._renderEffects) {
  25396. this._renderEffects[renderEffectName]._disable(_cam);
  25397. }
  25398. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25399. for (var i = 0; i < _cam.length; i++) {
  25400. var camera = _cam[i];
  25401. var cameraName = camera.name;
  25402. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25403. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25404. });
  25405. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25406. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25407. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25408. }
  25409. };
  25410. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25411. var _this = this;
  25412. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25413. for (var i = 0; i < _cam.length; i++) {
  25414. var camera = _cam[i];
  25415. var cameraName = camera.name;
  25416. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25417. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25418. });
  25419. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25420. }
  25421. for (var renderEffectName in this._renderEffects) {
  25422. this._renderEffects[renderEffectName]._enable(_cam);
  25423. }
  25424. };
  25425. PostProcessRenderPipeline.prototype._update = function () {
  25426. for (var renderEffectName in this._renderEffects) {
  25427. this._renderEffects[renderEffectName]._update();
  25428. }
  25429. for (var i = 0; i < this._cameras.length; i++) {
  25430. var cameraName = this._cameras[i].name;
  25431. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25432. this._renderEffectsForIsolatedPass[cameraName]._update();
  25433. }
  25434. }
  25435. };
  25436. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25437. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25438. return PostProcessRenderPipeline;
  25439. })();
  25440. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25441. })(BABYLON || (BABYLON = {}));
  25442. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  25443. var BABYLON;
  25444. (function (BABYLON) {
  25445. var PostProcessRenderPipelineManager = (function () {
  25446. function PostProcessRenderPipelineManager() {
  25447. this._renderPipelines = {};
  25448. }
  25449. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25450. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25451. };
  25452. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25453. var renderPipeline = this._renderPipelines[renderPipelineName];
  25454. if (!renderPipeline) {
  25455. return;
  25456. }
  25457. renderPipeline._attachCameras(cameras, unique);
  25458. };
  25459. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25460. var renderPipeline = this._renderPipelines[renderPipelineName];
  25461. if (!renderPipeline) {
  25462. return;
  25463. }
  25464. renderPipeline._detachCameras(cameras);
  25465. };
  25466. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25467. var renderPipeline = this._renderPipelines[renderPipelineName];
  25468. if (!renderPipeline) {
  25469. return;
  25470. }
  25471. renderPipeline._enableEffect(renderEffectName, cameras);
  25472. };
  25473. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25474. var renderPipeline = this._renderPipelines[renderPipelineName];
  25475. if (!renderPipeline) {
  25476. return;
  25477. }
  25478. renderPipeline._disableEffect(renderEffectName, cameras);
  25479. };
  25480. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25481. var renderPipeline = this._renderPipelines[renderPipelineName];
  25482. if (!renderPipeline) {
  25483. return;
  25484. }
  25485. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25486. };
  25487. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25488. var renderPipeline = this._renderPipelines[renderPipelineName];
  25489. if (!renderPipeline) {
  25490. return;
  25491. }
  25492. renderPipeline._disableDisplayOnlyPass(cameras);
  25493. };
  25494. PostProcessRenderPipelineManager.prototype.update = function () {
  25495. for (var renderPipelineName in this._renderPipelines) {
  25496. this._renderPipelines[renderPipelineName]._update();
  25497. }
  25498. };
  25499. return PostProcessRenderPipelineManager;
  25500. })();
  25501. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25502. })(BABYLON || (BABYLON = {}));
  25503. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  25504. var __extends = this.__extends || function (d, b) {
  25505. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25506. function __() { this.constructor = d; }
  25507. __.prototype = b.prototype;
  25508. d.prototype = new __();
  25509. };
  25510. var BABYLON;
  25511. (function (BABYLON) {
  25512. var DisplayPassPostProcess = (function (_super) {
  25513. __extends(DisplayPassPostProcess, _super);
  25514. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25515. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  25516. }
  25517. return DisplayPassPostProcess;
  25518. })(BABYLON.PostProcess);
  25519. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  25520. })(BABYLON || (BABYLON = {}));
  25521. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  25522. var BABYLON;
  25523. (function (BABYLON) {
  25524. var BoundingBoxRenderer = (function () {
  25525. function BoundingBoxRenderer(scene) {
  25526. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25527. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25528. this.showBackLines = true;
  25529. this.renderList = new BABYLON.SmartArray(32);
  25530. this._scene = scene;
  25531. }
  25532. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25533. if (this._colorShader) {
  25534. return;
  25535. }
  25536. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25537. attributes: ["position"],
  25538. uniforms: ["worldViewProjection", "color"]
  25539. });
  25540. var engine = this._scene.getEngine();
  25541. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25542. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25543. this._ib = engine.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]);
  25544. };
  25545. BoundingBoxRenderer.prototype.reset = function () {
  25546. this.renderList.reset();
  25547. };
  25548. BoundingBoxRenderer.prototype.render = function () {
  25549. if (this.renderList.length === 0) {
  25550. return;
  25551. }
  25552. this._prepareRessources();
  25553. if (!this._colorShader.isReady()) {
  25554. return;
  25555. }
  25556. var engine = this._scene.getEngine();
  25557. engine.setDepthWrite(false);
  25558. this._colorShader._preBind();
  25559. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25560. var boundingBox = this.renderList.data[boundingBoxIndex];
  25561. var min = boundingBox.minimum;
  25562. var max = boundingBox.maximum;
  25563. var diff = max.subtract(min);
  25564. var median = min.add(diff.scale(0.5));
  25565. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  25566. // VBOs
  25567. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25568. if (this.showBackLines) {
  25569. // Back
  25570. engine.setDepthFunctionToGreaterOrEqual();
  25571. this._scene.resetCachedMaterial();
  25572. this._colorShader.setColor4("color", this.backColor.toColor4());
  25573. this._colorShader.bind(worldMatrix);
  25574. // Draw order
  25575. engine.draw(false, 0, 24);
  25576. }
  25577. // Front
  25578. engine.setDepthFunctionToLess();
  25579. this._scene.resetCachedMaterial();
  25580. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25581. this._colorShader.bind(worldMatrix);
  25582. // Draw order
  25583. engine.draw(false, 0, 24);
  25584. }
  25585. this._colorShader.unbind();
  25586. engine.setDepthFunctionToLessOrEqual();
  25587. engine.setDepthWrite(true);
  25588. };
  25589. BoundingBoxRenderer.prototype.dispose = function () {
  25590. if (!this._colorShader) {
  25591. return;
  25592. }
  25593. this._colorShader.dispose();
  25594. this._vb.dispose();
  25595. this._scene.getEngine()._releaseBuffer(this._ib);
  25596. };
  25597. return BoundingBoxRenderer;
  25598. })();
  25599. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25600. })(BABYLON || (BABYLON = {}));
  25601. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  25602. var __extends = this.__extends || function (d, b) {
  25603. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25604. function __() { this.constructor = d; }
  25605. __.prototype = b.prototype;
  25606. d.prototype = new __();
  25607. };
  25608. var BABYLON;
  25609. (function (BABYLON) {
  25610. var Condition = (function () {
  25611. function Condition(actionManager) {
  25612. this._actionManager = actionManager;
  25613. }
  25614. Condition.prototype.isValid = function () {
  25615. return true;
  25616. };
  25617. Condition.prototype._getProperty = function (propertyPath) {
  25618. return this._actionManager._getProperty(propertyPath);
  25619. };
  25620. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25621. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25622. };
  25623. return Condition;
  25624. })();
  25625. BABYLON.Condition = Condition;
  25626. var ValueCondition = (function (_super) {
  25627. __extends(ValueCondition, _super);
  25628. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25629. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25630. _super.call(this, actionManager);
  25631. this.propertyPath = propertyPath;
  25632. this.value = value;
  25633. this.operator = operator;
  25634. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25635. this._property = this._getProperty(this.propertyPath);
  25636. }
  25637. Object.defineProperty(ValueCondition, "IsEqual", {
  25638. get: function () {
  25639. return ValueCondition._IsEqual;
  25640. },
  25641. enumerable: true,
  25642. configurable: true
  25643. });
  25644. Object.defineProperty(ValueCondition, "IsDifferent", {
  25645. get: function () {
  25646. return ValueCondition._IsDifferent;
  25647. },
  25648. enumerable: true,
  25649. configurable: true
  25650. });
  25651. Object.defineProperty(ValueCondition, "IsGreater", {
  25652. get: function () {
  25653. return ValueCondition._IsGreater;
  25654. },
  25655. enumerable: true,
  25656. configurable: true
  25657. });
  25658. Object.defineProperty(ValueCondition, "IsLesser", {
  25659. get: function () {
  25660. return ValueCondition._IsLesser;
  25661. },
  25662. enumerable: true,
  25663. configurable: true
  25664. });
  25665. // Methods
  25666. ValueCondition.prototype.isValid = function () {
  25667. switch (this.operator) {
  25668. case ValueCondition.IsGreater:
  25669. return this._target[this._property] > this.value;
  25670. case ValueCondition.IsLesser:
  25671. return this._target[this._property] < this.value;
  25672. case ValueCondition.IsEqual:
  25673. case ValueCondition.IsDifferent:
  25674. var check;
  25675. if (this.value.equals) {
  25676. check = this.value.equals(this._target[this._property]);
  25677. }
  25678. else {
  25679. check = this.value === this._target[this._property];
  25680. }
  25681. return this.operator === ValueCondition.IsEqual ? check : !check;
  25682. }
  25683. return false;
  25684. };
  25685. // Statics
  25686. ValueCondition._IsEqual = 0;
  25687. ValueCondition._IsDifferent = 1;
  25688. ValueCondition._IsGreater = 2;
  25689. ValueCondition._IsLesser = 3;
  25690. return ValueCondition;
  25691. })(Condition);
  25692. BABYLON.ValueCondition = ValueCondition;
  25693. var PredicateCondition = (function (_super) {
  25694. __extends(PredicateCondition, _super);
  25695. function PredicateCondition(actionManager, predicate) {
  25696. _super.call(this, actionManager);
  25697. this.predicate = predicate;
  25698. }
  25699. PredicateCondition.prototype.isValid = function () {
  25700. return this.predicate();
  25701. };
  25702. return PredicateCondition;
  25703. })(Condition);
  25704. BABYLON.PredicateCondition = PredicateCondition;
  25705. var StateCondition = (function (_super) {
  25706. __extends(StateCondition, _super);
  25707. function StateCondition(actionManager, target, value) {
  25708. _super.call(this, actionManager);
  25709. this.value = value;
  25710. this._target = target;
  25711. }
  25712. // Methods
  25713. StateCondition.prototype.isValid = function () {
  25714. return this._target.state === this.value;
  25715. };
  25716. return StateCondition;
  25717. })(Condition);
  25718. BABYLON.StateCondition = StateCondition;
  25719. })(BABYLON || (BABYLON = {}));
  25720. //# sourceMappingURL=babylon.condition.js.map
  25721. var BABYLON;
  25722. (function (BABYLON) {
  25723. var Action = (function () {
  25724. function Action(triggerOptions, condition) {
  25725. this.triggerOptions = triggerOptions;
  25726. if (triggerOptions.parameter) {
  25727. this.trigger = triggerOptions.trigger;
  25728. this._triggerParameter = triggerOptions.parameter;
  25729. }
  25730. else {
  25731. this.trigger = triggerOptions;
  25732. }
  25733. this._nextActiveAction = this;
  25734. this._condition = condition;
  25735. }
  25736. // Methods
  25737. Action.prototype._prepare = function () {
  25738. };
  25739. Action.prototype.getTriggerParameter = function () {
  25740. return this._triggerParameter;
  25741. };
  25742. Action.prototype._executeCurrent = function (evt) {
  25743. if (this._nextActiveAction._condition) {
  25744. var condition = this._nextActiveAction._condition;
  25745. var currentRenderId = this._actionManager.getScene().getRenderId();
  25746. // We cache the current evaluation for the current frame
  25747. if (condition._evaluationId === currentRenderId) {
  25748. if (!condition._currentResult) {
  25749. return;
  25750. }
  25751. }
  25752. else {
  25753. condition._evaluationId = currentRenderId;
  25754. if (!condition.isValid()) {
  25755. condition._currentResult = false;
  25756. return;
  25757. }
  25758. condition._currentResult = true;
  25759. }
  25760. }
  25761. this._nextActiveAction.execute(evt);
  25762. if (this._nextActiveAction._child) {
  25763. if (!this._nextActiveAction._child._actionManager) {
  25764. this._nextActiveAction._child._actionManager = this._actionManager;
  25765. }
  25766. this._nextActiveAction = this._nextActiveAction._child;
  25767. }
  25768. else {
  25769. this._nextActiveAction = this;
  25770. }
  25771. };
  25772. Action.prototype.execute = function (evt) {
  25773. };
  25774. Action.prototype.then = function (action) {
  25775. this._child = action;
  25776. action._actionManager = this._actionManager;
  25777. action._prepare();
  25778. return action;
  25779. };
  25780. Action.prototype._getProperty = function (propertyPath) {
  25781. return this._actionManager._getProperty(propertyPath);
  25782. };
  25783. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25784. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25785. };
  25786. return Action;
  25787. })();
  25788. BABYLON.Action = Action;
  25789. })(BABYLON || (BABYLON = {}));
  25790. //# sourceMappingURL=babylon.action.js.map
  25791. var BABYLON;
  25792. (function (BABYLON) {
  25793. /**
  25794. * ActionEvent is the event beint sent when an action is triggered.
  25795. */
  25796. var ActionEvent = (function () {
  25797. /**
  25798. * @constructor
  25799. * @param source The mesh that triggered the action.
  25800. * @param pointerX the X mouse cursor position at the time of the event
  25801. * @param pointerY the Y mouse cursor position at the time of the event
  25802. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25803. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25804. */
  25805. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  25806. this.source = source;
  25807. this.pointerX = pointerX;
  25808. this.pointerY = pointerY;
  25809. this.meshUnderPointer = meshUnderPointer;
  25810. this.sourceEvent = sourceEvent;
  25811. }
  25812. /**
  25813. * Helper function to auto-create an ActionEvent from a source mesh.
  25814. * @param source the source mesh that triggered the event
  25815. * @param evt {Event} The original (browser) event
  25816. */
  25817. ActionEvent.CreateNew = function (source, evt) {
  25818. var scene = source.getScene();
  25819. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25820. };
  25821. /**
  25822. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25823. * @param scene the scene where the event occurred
  25824. * @param evt {Event} The original (browser) event
  25825. */
  25826. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25827. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25828. };
  25829. return ActionEvent;
  25830. })();
  25831. BABYLON.ActionEvent = ActionEvent;
  25832. /**
  25833. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25834. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25835. */
  25836. var ActionManager = (function () {
  25837. function ActionManager(scene) {
  25838. // Members
  25839. this.actions = new Array();
  25840. this._scene = scene;
  25841. scene._actionManagers.push(this);
  25842. }
  25843. Object.defineProperty(ActionManager, "NothingTrigger", {
  25844. get: function () {
  25845. return ActionManager._NothingTrigger;
  25846. },
  25847. enumerable: true,
  25848. configurable: true
  25849. });
  25850. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25851. get: function () {
  25852. return ActionManager._OnPickTrigger;
  25853. },
  25854. enumerable: true,
  25855. configurable: true
  25856. });
  25857. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25858. get: function () {
  25859. return ActionManager._OnLeftPickTrigger;
  25860. },
  25861. enumerable: true,
  25862. configurable: true
  25863. });
  25864. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25865. get: function () {
  25866. return ActionManager._OnRightPickTrigger;
  25867. },
  25868. enumerable: true,
  25869. configurable: true
  25870. });
  25871. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25872. get: function () {
  25873. return ActionManager._OnCenterPickTrigger;
  25874. },
  25875. enumerable: true,
  25876. configurable: true
  25877. });
  25878. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25879. get: function () {
  25880. return ActionManager._OnPointerOverTrigger;
  25881. },
  25882. enumerable: true,
  25883. configurable: true
  25884. });
  25885. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25886. get: function () {
  25887. return ActionManager._OnPointerOutTrigger;
  25888. },
  25889. enumerable: true,
  25890. configurable: true
  25891. });
  25892. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25893. get: function () {
  25894. return ActionManager._OnEveryFrameTrigger;
  25895. },
  25896. enumerable: true,
  25897. configurable: true
  25898. });
  25899. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25900. get: function () {
  25901. return ActionManager._OnIntersectionEnterTrigger;
  25902. },
  25903. enumerable: true,
  25904. configurable: true
  25905. });
  25906. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25907. get: function () {
  25908. return ActionManager._OnIntersectionExitTrigger;
  25909. },
  25910. enumerable: true,
  25911. configurable: true
  25912. });
  25913. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25914. get: function () {
  25915. return ActionManager._OnKeyDownTrigger;
  25916. },
  25917. enumerable: true,
  25918. configurable: true
  25919. });
  25920. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25921. get: function () {
  25922. return ActionManager._OnKeyUpTrigger;
  25923. },
  25924. enumerable: true,
  25925. configurable: true
  25926. });
  25927. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25928. get: function () {
  25929. return ActionManager._OnPickUpTrigger;
  25930. },
  25931. enumerable: true,
  25932. configurable: true
  25933. });
  25934. // Methods
  25935. ActionManager.prototype.dispose = function () {
  25936. var index = this._scene._actionManagers.indexOf(this);
  25937. if (index > -1) {
  25938. this._scene._actionManagers.splice(index, 1);
  25939. }
  25940. };
  25941. ActionManager.prototype.getScene = function () {
  25942. return this._scene;
  25943. };
  25944. /**
  25945. * Does this action manager handles actions of any of the given triggers
  25946. * @param {number[]} triggers - the triggers to be tested
  25947. * @return {boolean} whether one (or more) of the triggers is handeled
  25948. */
  25949. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25950. for (var index = 0; index < this.actions.length; index++) {
  25951. var action = this.actions[index];
  25952. if (triggers.indexOf(action.trigger) > -1) {
  25953. return true;
  25954. }
  25955. }
  25956. return false;
  25957. };
  25958. /**
  25959. * Does this action manager handles actions of a given trigger
  25960. * @param {number} trigger - the trigger to be tested
  25961. * @return {boolean} whether the trigger is handeled
  25962. */
  25963. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25964. for (var index = 0; index < this.actions.length; index++) {
  25965. var action = this.actions[index];
  25966. if (action.trigger === trigger) {
  25967. return true;
  25968. }
  25969. }
  25970. return false;
  25971. };
  25972. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25973. /**
  25974. * Does this action manager has pointer triggers
  25975. * @return {boolean} whether or not it has pointer triggers
  25976. */
  25977. get: function () {
  25978. for (var index = 0; index < this.actions.length; index++) {
  25979. var action = this.actions[index];
  25980. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25981. return true;
  25982. }
  25983. if (action.trigger == ActionManager._OnPickUpTrigger) {
  25984. return true;
  25985. }
  25986. }
  25987. return false;
  25988. },
  25989. enumerable: true,
  25990. configurable: true
  25991. });
  25992. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25993. /**
  25994. * Does this action manager has pick triggers
  25995. * @return {boolean} whether or not it has pick triggers
  25996. */
  25997. get: function () {
  25998. for (var index = 0; index < this.actions.length; index++) {
  25999. var action = this.actions[index];
  26000. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26001. return true;
  26002. }
  26003. }
  26004. return false;
  26005. },
  26006. enumerable: true,
  26007. configurable: true
  26008. });
  26009. /**
  26010. * Registers an action to this action manager
  26011. * @param {BABYLON.Action} action - the action to be registered
  26012. * @return {BABYLON.Action} the action amended (prepared) after registration
  26013. */
  26014. ActionManager.prototype.registerAction = function (action) {
  26015. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26016. if (this.getScene().actionManager !== this) {
  26017. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26018. return null;
  26019. }
  26020. }
  26021. this.actions.push(action);
  26022. action._actionManager = this;
  26023. action._prepare();
  26024. return action;
  26025. };
  26026. /**
  26027. * Process a specific trigger
  26028. * @param {number} trigger - the trigger to process
  26029. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26030. */
  26031. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26032. for (var index = 0; index < this.actions.length; index++) {
  26033. var action = this.actions[index];
  26034. if (action.trigger === trigger) {
  26035. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  26036. var parameter = action.getTriggerParameter();
  26037. if (parameter) {
  26038. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26039. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26040. if (actualkey !== parameter.toLowerCase()) {
  26041. continue;
  26042. }
  26043. }
  26044. }
  26045. action._executeCurrent(evt);
  26046. }
  26047. }
  26048. };
  26049. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26050. var properties = propertyPath.split(".");
  26051. for (var index = 0; index < properties.length - 1; index++) {
  26052. target = target[properties[index]];
  26053. }
  26054. return target;
  26055. };
  26056. ActionManager.prototype._getProperty = function (propertyPath) {
  26057. var properties = propertyPath.split(".");
  26058. return properties[properties.length - 1];
  26059. };
  26060. // Statics
  26061. ActionManager._NothingTrigger = 0;
  26062. ActionManager._OnPickTrigger = 1;
  26063. ActionManager._OnLeftPickTrigger = 2;
  26064. ActionManager._OnRightPickTrigger = 3;
  26065. ActionManager._OnCenterPickTrigger = 4;
  26066. ActionManager._OnPointerOverTrigger = 5;
  26067. ActionManager._OnPointerOutTrigger = 6;
  26068. ActionManager._OnEveryFrameTrigger = 7;
  26069. ActionManager._OnIntersectionEnterTrigger = 8;
  26070. ActionManager._OnIntersectionExitTrigger = 9;
  26071. ActionManager._OnKeyDownTrigger = 10;
  26072. ActionManager._OnKeyUpTrigger = 11;
  26073. ActionManager._OnPickUpTrigger = 12;
  26074. return ActionManager;
  26075. })();
  26076. BABYLON.ActionManager = ActionManager;
  26077. })(BABYLON || (BABYLON = {}));
  26078. //# sourceMappingURL=babylon.actionManager.js.map
  26079. var __extends = this.__extends || function (d, b) {
  26080. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26081. function __() { this.constructor = d; }
  26082. __.prototype = b.prototype;
  26083. d.prototype = new __();
  26084. };
  26085. var BABYLON;
  26086. (function (BABYLON) {
  26087. var InterpolateValueAction = (function (_super) {
  26088. __extends(InterpolateValueAction, _super);
  26089. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26090. if (duration === void 0) { duration = 1000; }
  26091. _super.call(this, triggerOptions, condition);
  26092. this.propertyPath = propertyPath;
  26093. this.value = value;
  26094. this.duration = duration;
  26095. this.stopOtherAnimations = stopOtherAnimations;
  26096. this._target = target;
  26097. }
  26098. InterpolateValueAction.prototype._prepare = function () {
  26099. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26100. this._property = this._getProperty(this.propertyPath);
  26101. };
  26102. InterpolateValueAction.prototype.execute = function () {
  26103. var scene = this._actionManager.getScene();
  26104. var keys = [
  26105. {
  26106. frame: 0,
  26107. value: this._target[this._property]
  26108. },
  26109. {
  26110. frame: 100,
  26111. value: this.value
  26112. }
  26113. ];
  26114. var dataType;
  26115. if (typeof this.value === "number") {
  26116. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26117. }
  26118. else if (this.value instanceof BABYLON.Color3) {
  26119. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26120. }
  26121. else if (this.value instanceof BABYLON.Vector3) {
  26122. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26123. }
  26124. else if (this.value instanceof BABYLON.Matrix) {
  26125. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26126. }
  26127. else if (this.value instanceof BABYLON.Quaternion) {
  26128. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26129. }
  26130. else {
  26131. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26132. return;
  26133. }
  26134. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26135. animation.setKeys(keys);
  26136. if (this.stopOtherAnimations) {
  26137. scene.stopAnimation(this._target);
  26138. }
  26139. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  26140. };
  26141. return InterpolateValueAction;
  26142. })(BABYLON.Action);
  26143. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26144. })(BABYLON || (BABYLON = {}));
  26145. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  26146. var __extends = this.__extends || function (d, b) {
  26147. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26148. function __() { this.constructor = d; }
  26149. __.prototype = b.prototype;
  26150. d.prototype = new __();
  26151. };
  26152. var BABYLON;
  26153. (function (BABYLON) {
  26154. var SwitchBooleanAction = (function (_super) {
  26155. __extends(SwitchBooleanAction, _super);
  26156. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26157. _super.call(this, triggerOptions, condition);
  26158. this.propertyPath = propertyPath;
  26159. this._target = target;
  26160. }
  26161. SwitchBooleanAction.prototype._prepare = function () {
  26162. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26163. this._property = this._getProperty(this.propertyPath);
  26164. };
  26165. SwitchBooleanAction.prototype.execute = function () {
  26166. this._target[this._property] = !this._target[this._property];
  26167. };
  26168. return SwitchBooleanAction;
  26169. })(BABYLON.Action);
  26170. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26171. var SetStateAction = (function (_super) {
  26172. __extends(SetStateAction, _super);
  26173. function SetStateAction(triggerOptions, target, value, condition) {
  26174. _super.call(this, triggerOptions, condition);
  26175. this.value = value;
  26176. this._target = target;
  26177. }
  26178. SetStateAction.prototype.execute = function () {
  26179. this._target.state = this.value;
  26180. };
  26181. return SetStateAction;
  26182. })(BABYLON.Action);
  26183. BABYLON.SetStateAction = SetStateAction;
  26184. var SetValueAction = (function (_super) {
  26185. __extends(SetValueAction, _super);
  26186. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26187. _super.call(this, triggerOptions, condition);
  26188. this.propertyPath = propertyPath;
  26189. this.value = value;
  26190. this._target = target;
  26191. }
  26192. SetValueAction.prototype._prepare = function () {
  26193. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26194. this._property = this._getProperty(this.propertyPath);
  26195. };
  26196. SetValueAction.prototype.execute = function () {
  26197. this._target[this._property] = this.value;
  26198. };
  26199. return SetValueAction;
  26200. })(BABYLON.Action);
  26201. BABYLON.SetValueAction = SetValueAction;
  26202. var IncrementValueAction = (function (_super) {
  26203. __extends(IncrementValueAction, _super);
  26204. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26205. _super.call(this, triggerOptions, condition);
  26206. this.propertyPath = propertyPath;
  26207. this.value = value;
  26208. this._target = target;
  26209. }
  26210. IncrementValueAction.prototype._prepare = function () {
  26211. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26212. this._property = this._getProperty(this.propertyPath);
  26213. if (typeof this._target[this._property] !== "number") {
  26214. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26215. }
  26216. };
  26217. IncrementValueAction.prototype.execute = function () {
  26218. this._target[this._property] += this.value;
  26219. };
  26220. return IncrementValueAction;
  26221. })(BABYLON.Action);
  26222. BABYLON.IncrementValueAction = IncrementValueAction;
  26223. var PlayAnimationAction = (function (_super) {
  26224. __extends(PlayAnimationAction, _super);
  26225. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26226. _super.call(this, triggerOptions, condition);
  26227. this.from = from;
  26228. this.to = to;
  26229. this.loop = loop;
  26230. this._target = target;
  26231. }
  26232. PlayAnimationAction.prototype._prepare = function () {
  26233. };
  26234. PlayAnimationAction.prototype.execute = function () {
  26235. var scene = this._actionManager.getScene();
  26236. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26237. };
  26238. return PlayAnimationAction;
  26239. })(BABYLON.Action);
  26240. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26241. var StopAnimationAction = (function (_super) {
  26242. __extends(StopAnimationAction, _super);
  26243. function StopAnimationAction(triggerOptions, target, condition) {
  26244. _super.call(this, triggerOptions, condition);
  26245. this._target = target;
  26246. }
  26247. StopAnimationAction.prototype._prepare = function () {
  26248. };
  26249. StopAnimationAction.prototype.execute = function () {
  26250. var scene = this._actionManager.getScene();
  26251. scene.stopAnimation(this._target);
  26252. };
  26253. return StopAnimationAction;
  26254. })(BABYLON.Action);
  26255. BABYLON.StopAnimationAction = StopAnimationAction;
  26256. var DoNothingAction = (function (_super) {
  26257. __extends(DoNothingAction, _super);
  26258. function DoNothingAction(triggerOptions, condition) {
  26259. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26260. _super.call(this, triggerOptions, condition);
  26261. }
  26262. DoNothingAction.prototype.execute = function () {
  26263. };
  26264. return DoNothingAction;
  26265. })(BABYLON.Action);
  26266. BABYLON.DoNothingAction = DoNothingAction;
  26267. var CombineAction = (function (_super) {
  26268. __extends(CombineAction, _super);
  26269. function CombineAction(triggerOptions, children, condition) {
  26270. _super.call(this, triggerOptions, condition);
  26271. this.children = children;
  26272. }
  26273. CombineAction.prototype._prepare = function () {
  26274. for (var index = 0; index < this.children.length; index++) {
  26275. this.children[index]._actionManager = this._actionManager;
  26276. this.children[index]._prepare();
  26277. }
  26278. };
  26279. CombineAction.prototype.execute = function (evt) {
  26280. for (var index = 0; index < this.children.length; index++) {
  26281. this.children[index].execute(evt);
  26282. }
  26283. };
  26284. return CombineAction;
  26285. })(BABYLON.Action);
  26286. BABYLON.CombineAction = CombineAction;
  26287. var ExecuteCodeAction = (function (_super) {
  26288. __extends(ExecuteCodeAction, _super);
  26289. function ExecuteCodeAction(triggerOptions, func, condition) {
  26290. _super.call(this, triggerOptions, condition);
  26291. this.func = func;
  26292. }
  26293. ExecuteCodeAction.prototype.execute = function (evt) {
  26294. this.func(evt);
  26295. };
  26296. return ExecuteCodeAction;
  26297. })(BABYLON.Action);
  26298. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26299. var SetParentAction = (function (_super) {
  26300. __extends(SetParentAction, _super);
  26301. function SetParentAction(triggerOptions, target, parent, condition) {
  26302. _super.call(this, triggerOptions, condition);
  26303. this._target = target;
  26304. this._parent = parent;
  26305. }
  26306. SetParentAction.prototype._prepare = function () {
  26307. };
  26308. SetParentAction.prototype.execute = function () {
  26309. if (this._target.parent === this._parent) {
  26310. return;
  26311. }
  26312. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26313. invertParentWorldMatrix.invert();
  26314. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26315. this._target.parent = this._parent;
  26316. };
  26317. return SetParentAction;
  26318. })(BABYLON.Action);
  26319. BABYLON.SetParentAction = SetParentAction;
  26320. var PlaySoundAction = (function (_super) {
  26321. __extends(PlaySoundAction, _super);
  26322. function PlaySoundAction(triggerOptions, sound, condition) {
  26323. _super.call(this, triggerOptions, condition);
  26324. this._sound = sound;
  26325. }
  26326. PlaySoundAction.prototype._prepare = function () {
  26327. };
  26328. PlaySoundAction.prototype.execute = function () {
  26329. if (this._sound !== undefined)
  26330. this._sound.play();
  26331. };
  26332. return PlaySoundAction;
  26333. })(BABYLON.Action);
  26334. BABYLON.PlaySoundAction = PlaySoundAction;
  26335. var StopSoundAction = (function (_super) {
  26336. __extends(StopSoundAction, _super);
  26337. function StopSoundAction(triggerOptions, sound, condition) {
  26338. _super.call(this, triggerOptions, condition);
  26339. this._sound = sound;
  26340. }
  26341. StopSoundAction.prototype._prepare = function () {
  26342. };
  26343. StopSoundAction.prototype.execute = function () {
  26344. if (this._sound !== undefined)
  26345. this._sound.stop();
  26346. };
  26347. return StopSoundAction;
  26348. })(BABYLON.Action);
  26349. BABYLON.StopSoundAction = StopSoundAction;
  26350. })(BABYLON || (BABYLON = {}));
  26351. //# sourceMappingURL=babylon.directActions.js.map
  26352. var __extends = this.__extends || function (d, b) {
  26353. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26354. function __() { this.constructor = d; }
  26355. __.prototype = b.prototype;
  26356. d.prototype = new __();
  26357. };
  26358. var BABYLON;
  26359. (function (BABYLON) {
  26360. var Geometry = (function () {
  26361. function Geometry(id, scene, vertexData, updatable, mesh) {
  26362. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26363. this._totalVertices = 0;
  26364. this._indices = [];
  26365. this._isDisposed = false;
  26366. this.id = id;
  26367. this._engine = scene.getEngine();
  26368. this._meshes = [];
  26369. this._scene = scene;
  26370. // vertexData
  26371. if (vertexData) {
  26372. this.setAllVerticesData(vertexData, updatable);
  26373. }
  26374. else {
  26375. this._totalVertices = 0;
  26376. this._indices = [];
  26377. }
  26378. // applyToMesh
  26379. if (mesh) {
  26380. this.applyToMesh(mesh);
  26381. mesh.computeWorldMatrix(true);
  26382. }
  26383. }
  26384. Geometry.prototype.getScene = function () {
  26385. return this._scene;
  26386. };
  26387. Geometry.prototype.getEngine = function () {
  26388. return this._engine;
  26389. };
  26390. Geometry.prototype.isReady = function () {
  26391. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26392. };
  26393. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26394. vertexData.applyToGeometry(this, updatable);
  26395. this.notifyUpdate();
  26396. };
  26397. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26398. this._vertexBuffers = this._vertexBuffers || {};
  26399. if (this._vertexBuffers[kind]) {
  26400. this._vertexBuffers[kind].dispose();
  26401. }
  26402. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26403. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26404. stride = this._vertexBuffers[kind].getStrideSize();
  26405. this._totalVertices = data.length / stride;
  26406. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26407. var meshes = this._meshes;
  26408. var numOfMeshes = meshes.length;
  26409. for (var index = 0; index < numOfMeshes; index++) {
  26410. var mesh = meshes[index];
  26411. mesh._resetPointsArrayCache();
  26412. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26413. mesh._createGlobalSubMesh();
  26414. mesh.computeWorldMatrix(true);
  26415. }
  26416. }
  26417. this.notifyUpdate(kind);
  26418. };
  26419. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26420. var vertexBuffer = this.getVertexBuffer(kind);
  26421. if (!vertexBuffer) {
  26422. return;
  26423. }
  26424. vertexBuffer.updateDirectly(data, offset);
  26425. this.notifyUpdate(kind);
  26426. };
  26427. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26428. var vertexBuffer = this.getVertexBuffer(kind);
  26429. if (!vertexBuffer) {
  26430. return;
  26431. }
  26432. vertexBuffer.update(data);
  26433. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26434. var extend;
  26435. var stride = vertexBuffer.getStrideSize();
  26436. this._totalVertices = data.length / stride;
  26437. if (updateExtends) {
  26438. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26439. }
  26440. var meshes = this._meshes;
  26441. var numOfMeshes = meshes.length;
  26442. for (var index = 0; index < numOfMeshes; index++) {
  26443. var mesh = meshes[index];
  26444. mesh._resetPointsArrayCache();
  26445. if (updateExtends) {
  26446. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26447. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26448. var subMesh = mesh.subMeshes[subIndex];
  26449. subMesh.refreshBoundingInfo();
  26450. }
  26451. }
  26452. }
  26453. }
  26454. this.notifyUpdate(kind);
  26455. };
  26456. Geometry.prototype.getTotalVertices = function () {
  26457. if (!this.isReady()) {
  26458. return 0;
  26459. }
  26460. return this._totalVertices;
  26461. };
  26462. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26463. var vertexBuffer = this.getVertexBuffer(kind);
  26464. if (!vertexBuffer) {
  26465. return null;
  26466. }
  26467. var orig = vertexBuffer.getData();
  26468. if (!copyWhenShared || this._meshes.length === 1) {
  26469. return orig;
  26470. }
  26471. else {
  26472. var len = orig.length;
  26473. var copy = [];
  26474. for (var i = 0; i < len; i++) {
  26475. copy.push(orig[i]);
  26476. }
  26477. return copy;
  26478. }
  26479. };
  26480. Geometry.prototype.getVertexBuffer = function (kind) {
  26481. if (!this.isReady()) {
  26482. return null;
  26483. }
  26484. return this._vertexBuffers[kind];
  26485. };
  26486. Geometry.prototype.getVertexBuffers = function () {
  26487. if (!this.isReady()) {
  26488. return null;
  26489. }
  26490. return this._vertexBuffers;
  26491. };
  26492. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26493. if (!this._vertexBuffers) {
  26494. if (this._delayInfo) {
  26495. return this._delayInfo.indexOf(kind) !== -1;
  26496. }
  26497. return false;
  26498. }
  26499. return this._vertexBuffers[kind] !== undefined;
  26500. };
  26501. Geometry.prototype.getVerticesDataKinds = function () {
  26502. var result = [];
  26503. if (!this._vertexBuffers && this._delayInfo) {
  26504. for (var kind in this._delayInfo) {
  26505. result.push(kind);
  26506. }
  26507. }
  26508. else {
  26509. for (kind in this._vertexBuffers) {
  26510. result.push(kind);
  26511. }
  26512. }
  26513. return result;
  26514. };
  26515. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26516. if (this._indexBuffer) {
  26517. this._engine._releaseBuffer(this._indexBuffer);
  26518. }
  26519. this._indices = indices;
  26520. if (this._meshes.length !== 0 && this._indices) {
  26521. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26522. }
  26523. if (totalVertices !== undefined) {
  26524. this._totalVertices = totalVertices;
  26525. }
  26526. var meshes = this._meshes;
  26527. var numOfMeshes = meshes.length;
  26528. for (var index = 0; index < numOfMeshes; index++) {
  26529. meshes[index]._createGlobalSubMesh();
  26530. }
  26531. this.notifyUpdate();
  26532. };
  26533. Geometry.prototype.getTotalIndices = function () {
  26534. if (!this.isReady()) {
  26535. return 0;
  26536. }
  26537. return this._indices.length;
  26538. };
  26539. Geometry.prototype.getIndices = function (copyWhenShared) {
  26540. if (!this.isReady()) {
  26541. return null;
  26542. }
  26543. var orig = this._indices;
  26544. if (!copyWhenShared || this._meshes.length === 1) {
  26545. return orig;
  26546. }
  26547. else {
  26548. var len = orig.length;
  26549. var copy = [];
  26550. for (var i = 0; i < len; i++) {
  26551. copy.push(orig[i]);
  26552. }
  26553. return copy;
  26554. }
  26555. };
  26556. Geometry.prototype.getIndexBuffer = function () {
  26557. if (!this.isReady()) {
  26558. return null;
  26559. }
  26560. return this._indexBuffer;
  26561. };
  26562. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26563. var meshes = this._meshes;
  26564. var index = meshes.indexOf(mesh);
  26565. if (index === -1) {
  26566. return;
  26567. }
  26568. for (var kind in this._vertexBuffers) {
  26569. this._vertexBuffers[kind].dispose();
  26570. }
  26571. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26572. this._indexBuffer = null;
  26573. }
  26574. meshes.splice(index, 1);
  26575. mesh._geometry = null;
  26576. if (meshes.length === 0 && shouldDispose) {
  26577. this.dispose();
  26578. }
  26579. };
  26580. Geometry.prototype.applyToMesh = function (mesh) {
  26581. if (mesh._geometry === this) {
  26582. return;
  26583. }
  26584. var previousGeometry = mesh._geometry;
  26585. if (previousGeometry) {
  26586. previousGeometry.releaseForMesh(mesh);
  26587. }
  26588. var meshes = this._meshes;
  26589. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26590. mesh._geometry = this;
  26591. this._scene.pushGeometry(this);
  26592. meshes.push(mesh);
  26593. if (this.isReady()) {
  26594. this._applyToMesh(mesh);
  26595. }
  26596. else {
  26597. mesh._boundingInfo = this._boundingInfo;
  26598. }
  26599. };
  26600. Geometry.prototype._applyToMesh = function (mesh) {
  26601. var numOfMeshes = this._meshes.length;
  26602. for (var kind in this._vertexBuffers) {
  26603. if (numOfMeshes === 1) {
  26604. this._vertexBuffers[kind].create();
  26605. }
  26606. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26607. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26608. mesh._resetPointsArrayCache();
  26609. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26610. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26611. mesh._createGlobalSubMesh();
  26612. //bounding info was just created again, world matrix should be applied again.
  26613. mesh._updateBoundingInfo();
  26614. }
  26615. }
  26616. // indexBuffer
  26617. if (numOfMeshes === 1 && this._indices) {
  26618. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26619. }
  26620. if (this._indexBuffer) {
  26621. this._indexBuffer.references = numOfMeshes;
  26622. }
  26623. };
  26624. Geometry.prototype.notifyUpdate = function (kind) {
  26625. if (this.onGeometryUpdated) {
  26626. this.onGeometryUpdated(this, kind);
  26627. }
  26628. };
  26629. Geometry.prototype.load = function (scene, onLoaded) {
  26630. var _this = this;
  26631. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26632. return;
  26633. }
  26634. if (this.isReady()) {
  26635. if (onLoaded) {
  26636. onLoaded();
  26637. }
  26638. return;
  26639. }
  26640. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26641. scene._addPendingData(this);
  26642. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26643. _this._delayLoadingFunction(JSON.parse(data), _this);
  26644. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26645. _this._delayInfo = [];
  26646. scene._removePendingData(_this);
  26647. var meshes = _this._meshes;
  26648. var numOfMeshes = meshes.length;
  26649. for (var index = 0; index < numOfMeshes; index++) {
  26650. _this._applyToMesh(meshes[index]);
  26651. }
  26652. if (onLoaded) {
  26653. onLoaded();
  26654. }
  26655. }, function () {
  26656. }, scene.database);
  26657. };
  26658. Geometry.prototype.isDisposed = function () {
  26659. return this._isDisposed;
  26660. };
  26661. Geometry.prototype.dispose = function () {
  26662. var meshes = this._meshes;
  26663. var numOfMeshes = meshes.length;
  26664. var index;
  26665. for (index = 0; index < numOfMeshes; index++) {
  26666. this.releaseForMesh(meshes[index]);
  26667. }
  26668. this._meshes = [];
  26669. for (var kind in this._vertexBuffers) {
  26670. this._vertexBuffers[kind].dispose();
  26671. }
  26672. this._vertexBuffers = [];
  26673. this._totalVertices = 0;
  26674. if (this._indexBuffer) {
  26675. this._engine._releaseBuffer(this._indexBuffer);
  26676. }
  26677. this._indexBuffer = null;
  26678. this._indices = [];
  26679. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26680. this.delayLoadingFile = null;
  26681. this._delayLoadingFunction = null;
  26682. this._delayInfo = [];
  26683. this._boundingInfo = null; // todo: .dispose()
  26684. this._scene.removeGeometry(this);
  26685. this._isDisposed = true;
  26686. };
  26687. Geometry.prototype.copy = function (id) {
  26688. var vertexData = new BABYLON.VertexData();
  26689. vertexData.indices = [];
  26690. var indices = this.getIndices();
  26691. for (var index = 0; index < indices.length; index++) {
  26692. vertexData.indices.push(indices[index]);
  26693. }
  26694. var updatable = false;
  26695. var stopChecking = false;
  26696. for (var kind in this._vertexBuffers) {
  26697. // using slice() to make a copy of the array and not just reference it
  26698. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  26699. if (!stopChecking) {
  26700. updatable = this.getVertexBuffer(kind).isUpdatable();
  26701. stopChecking = !updatable;
  26702. }
  26703. }
  26704. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26705. geometry.delayLoadState = this.delayLoadState;
  26706. geometry.delayLoadingFile = this.delayLoadingFile;
  26707. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26708. for (kind in this._delayInfo) {
  26709. geometry._delayInfo = geometry._delayInfo || [];
  26710. geometry._delayInfo.push(kind);
  26711. }
  26712. // Bounding info
  26713. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  26714. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26715. return geometry;
  26716. };
  26717. // Statics
  26718. Geometry.ExtractFromMesh = function (mesh, id) {
  26719. var geometry = mesh._geometry;
  26720. if (!geometry) {
  26721. return null;
  26722. }
  26723. return geometry.copy(id);
  26724. };
  26725. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26726. // be aware Math.random() could cause collisions
  26727. Geometry.RandomId = function () {
  26728. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26729. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26730. return v.toString(16);
  26731. });
  26732. };
  26733. return Geometry;
  26734. })();
  26735. BABYLON.Geometry = Geometry;
  26736. /////// Primitives //////////////////////////////////////////////
  26737. var Geometry;
  26738. (function (Geometry) {
  26739. var Primitives;
  26740. (function (Primitives) {
  26741. /// Abstract class
  26742. var _Primitive = (function (_super) {
  26743. __extends(_Primitive, _super);
  26744. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26745. this._beingRegenerated = true;
  26746. this._canBeRegenerated = canBeRegenerated;
  26747. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26748. this._beingRegenerated = false;
  26749. }
  26750. _Primitive.prototype.canBeRegenerated = function () {
  26751. return this._canBeRegenerated;
  26752. };
  26753. _Primitive.prototype.regenerate = function () {
  26754. if (!this._canBeRegenerated) {
  26755. return;
  26756. }
  26757. this._beingRegenerated = true;
  26758. this.setAllVerticesData(this._regenerateVertexData(), false);
  26759. this._beingRegenerated = false;
  26760. };
  26761. _Primitive.prototype.asNewGeometry = function (id) {
  26762. return _super.prototype.copy.call(this, id);
  26763. };
  26764. // overrides
  26765. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26766. if (!this._beingRegenerated) {
  26767. return;
  26768. }
  26769. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26770. };
  26771. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26772. if (!this._beingRegenerated) {
  26773. return;
  26774. }
  26775. _super.prototype.setVerticesData.call(this, kind, data, false);
  26776. };
  26777. // to override
  26778. // protected
  26779. _Primitive.prototype._regenerateVertexData = function () {
  26780. throw new Error("Abstract method");
  26781. };
  26782. _Primitive.prototype.copy = function (id) {
  26783. throw new Error("Must be overriden in sub-classes.");
  26784. };
  26785. return _Primitive;
  26786. })(Geometry);
  26787. Primitives._Primitive = _Primitive;
  26788. var Ribbon = (function (_super) {
  26789. __extends(Ribbon, _super);
  26790. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26791. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26792. this.pathArray = pathArray;
  26793. this.closeArray = closeArray;
  26794. this.closePath = closePath;
  26795. this.offset = offset;
  26796. this.side = side;
  26797. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26798. }
  26799. Ribbon.prototype._regenerateVertexData = function () {
  26800. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  26801. };
  26802. Ribbon.prototype.copy = function (id) {
  26803. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26804. };
  26805. return Ribbon;
  26806. })(_Primitive);
  26807. Primitives.Ribbon = Ribbon;
  26808. var Box = (function (_super) {
  26809. __extends(Box, _super);
  26810. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26811. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26812. this.size = size;
  26813. this.side = side;
  26814. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26815. }
  26816. Box.prototype._regenerateVertexData = function () {
  26817. return BABYLON.VertexData.CreateBox(this.size, this.side);
  26818. };
  26819. Box.prototype.copy = function (id) {
  26820. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26821. };
  26822. return Box;
  26823. })(_Primitive);
  26824. Primitives.Box = Box;
  26825. var Sphere = (function (_super) {
  26826. __extends(Sphere, _super);
  26827. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26828. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26829. this.segments = segments;
  26830. this.diameter = diameter;
  26831. this.side = side;
  26832. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26833. }
  26834. Sphere.prototype._regenerateVertexData = function () {
  26835. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  26836. };
  26837. Sphere.prototype.copy = function (id) {
  26838. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26839. };
  26840. return Sphere;
  26841. })(_Primitive);
  26842. Primitives.Sphere = Sphere;
  26843. var Cylinder = (function (_super) {
  26844. __extends(Cylinder, _super);
  26845. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26846. if (subdivisions === void 0) { subdivisions = 1; }
  26847. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26848. this.height = height;
  26849. this.diameterTop = diameterTop;
  26850. this.diameterBottom = diameterBottom;
  26851. this.tessellation = tessellation;
  26852. this.subdivisions = subdivisions;
  26853. this.side = side;
  26854. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26855. }
  26856. Cylinder.prototype._regenerateVertexData = function () {
  26857. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  26858. };
  26859. Cylinder.prototype.copy = function (id) {
  26860. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26861. };
  26862. return Cylinder;
  26863. })(_Primitive);
  26864. Primitives.Cylinder = Cylinder;
  26865. var Torus = (function (_super) {
  26866. __extends(Torus, _super);
  26867. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26868. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26869. this.diameter = diameter;
  26870. this.thickness = thickness;
  26871. this.tessellation = tessellation;
  26872. this.side = side;
  26873. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26874. }
  26875. Torus.prototype._regenerateVertexData = function () {
  26876. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  26877. };
  26878. Torus.prototype.copy = function (id) {
  26879. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26880. };
  26881. return Torus;
  26882. })(_Primitive);
  26883. Primitives.Torus = Torus;
  26884. var Ground = (function (_super) {
  26885. __extends(Ground, _super);
  26886. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26887. this.width = width;
  26888. this.height = height;
  26889. this.subdivisions = subdivisions;
  26890. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26891. }
  26892. Ground.prototype._regenerateVertexData = function () {
  26893. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  26894. };
  26895. Ground.prototype.copy = function (id) {
  26896. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26897. };
  26898. return Ground;
  26899. })(_Primitive);
  26900. Primitives.Ground = Ground;
  26901. var TiledGround = (function (_super) {
  26902. __extends(TiledGround, _super);
  26903. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26904. this.xmin = xmin;
  26905. this.zmin = zmin;
  26906. this.xmax = xmax;
  26907. this.zmax = zmax;
  26908. this.subdivisions = subdivisions;
  26909. this.precision = precision;
  26910. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26911. }
  26912. TiledGround.prototype._regenerateVertexData = function () {
  26913. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  26914. };
  26915. TiledGround.prototype.copy = function (id) {
  26916. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26917. };
  26918. return TiledGround;
  26919. })(_Primitive);
  26920. Primitives.TiledGround = TiledGround;
  26921. var Plane = (function (_super) {
  26922. __extends(Plane, _super);
  26923. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26924. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26925. this.size = size;
  26926. this.side = side;
  26927. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26928. }
  26929. Plane.prototype._regenerateVertexData = function () {
  26930. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  26931. };
  26932. Plane.prototype.copy = function (id) {
  26933. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26934. };
  26935. return Plane;
  26936. })(_Primitive);
  26937. Primitives.Plane = Plane;
  26938. var TorusKnot = (function (_super) {
  26939. __extends(TorusKnot, _super);
  26940. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26941. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26942. this.radius = radius;
  26943. this.tube = tube;
  26944. this.radialSegments = radialSegments;
  26945. this.tubularSegments = tubularSegments;
  26946. this.p = p;
  26947. this.q = q;
  26948. this.side = side;
  26949. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26950. }
  26951. TorusKnot.prototype._regenerateVertexData = function () {
  26952. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  26953. };
  26954. TorusKnot.prototype.copy = function (id) {
  26955. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26956. };
  26957. return TorusKnot;
  26958. })(_Primitive);
  26959. Primitives.TorusKnot = TorusKnot;
  26960. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26961. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26962. })(BABYLON || (BABYLON = {}));
  26963. //# sourceMappingURL=babylon.geometry.js.map
  26964. var __extends = this.__extends || function (d, b) {
  26965. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26966. function __() { this.constructor = d; }
  26967. __.prototype = b.prototype;
  26968. d.prototype = new __();
  26969. };
  26970. var BABYLON;
  26971. (function (BABYLON) {
  26972. var GroundMesh = (function (_super) {
  26973. __extends(GroundMesh, _super);
  26974. function GroundMesh(name, scene) {
  26975. _super.call(this, name, scene);
  26976. this.generateOctree = false;
  26977. this._worldInverse = new BABYLON.Matrix();
  26978. }
  26979. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26980. get: function () {
  26981. return this._subdivisions;
  26982. },
  26983. enumerable: true,
  26984. configurable: true
  26985. });
  26986. GroundMesh.prototype.optimize = function (chunksCount) {
  26987. this.subdivide(this._subdivisions);
  26988. this.createOrUpdateSubmeshesOctree(32);
  26989. };
  26990. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26991. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26992. this.getWorldMatrix().invertToRef(this._worldInverse);
  26993. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26994. var pickInfo = this.intersects(ray);
  26995. if (pickInfo.hit) {
  26996. return pickInfo.pickedPoint.y;
  26997. }
  26998. return 0;
  26999. };
  27000. return GroundMesh;
  27001. })(BABYLON.Mesh);
  27002. BABYLON.GroundMesh = GroundMesh;
  27003. })(BABYLON || (BABYLON = {}));
  27004. //# sourceMappingURL=babylon.groundMesh.js.map
  27005. var __extends = this.__extends || function (d, b) {
  27006. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27007. function __() { this.constructor = d; }
  27008. __.prototype = b.prototype;
  27009. d.prototype = new __();
  27010. };
  27011. var BABYLON;
  27012. (function (BABYLON) {
  27013. var Gamepads = (function () {
  27014. function Gamepads(ongamedpadconnected) {
  27015. var _this = this;
  27016. this.babylonGamepads = [];
  27017. this.oneGamepadConnected = false;
  27018. this.isMonitoring = false;
  27019. this.gamepadEventSupported = 'GamepadEvent' in window;
  27020. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  27021. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  27022. this._callbackGamepadConnected = ongamedpadconnected;
  27023. if (this.gamepadSupportAvailable) {
  27024. // Checking if the gamepad connected event is supported (like in Firefox)
  27025. if (this.gamepadEventSupported) {
  27026. window.addEventListener('gamepadconnected', function (evt) {
  27027. _this._onGamepadConnected(evt);
  27028. }, false);
  27029. window.addEventListener('gamepaddisconnected', function (evt) {
  27030. _this._onGamepadDisconnected(evt);
  27031. }, false);
  27032. }
  27033. else {
  27034. this._startMonitoringGamepads();
  27035. }
  27036. if (!this.oneGamepadConnected) {
  27037. this._insertGamepadDOMInstructions();
  27038. }
  27039. }
  27040. else {
  27041. this._insertGamepadDOMNotSupported();
  27042. }
  27043. }
  27044. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  27045. Gamepads.gamepadDOMInfo = document.createElement("div");
  27046. var buttonAImage = document.createElement("img");
  27047. buttonAImage.src = this.buttonADataURL;
  27048. var spanMessage = document.createElement("span");
  27049. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  27050. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  27051. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27052. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27053. Gamepads.gamepadDOMInfo.style.width = "100%";
  27054. Gamepads.gamepadDOMInfo.style.height = "48px";
  27055. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27056. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27057. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27058. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27059. buttonAImage.style.position = "relative";
  27060. buttonAImage.style.bottom = "8px";
  27061. spanMessage.style.position = "relative";
  27062. spanMessage.style.fontSize = "32px";
  27063. spanMessage.style.bottom = "32px";
  27064. spanMessage.style.color = "green";
  27065. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27066. };
  27067. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  27068. Gamepads.gamepadDOMInfo = document.createElement("div");
  27069. var spanMessage = document.createElement("span");
  27070. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  27071. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27072. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27073. Gamepads.gamepadDOMInfo.style.width = "100%";
  27074. Gamepads.gamepadDOMInfo.style.height = "40px";
  27075. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27076. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27077. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27078. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27079. spanMessage.style.position = "relative";
  27080. spanMessage.style.fontSize = "32px";
  27081. spanMessage.style.color = "red";
  27082. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27083. };
  27084. Gamepads.prototype.dispose = function () {
  27085. if (Gamepads.gamepadDOMInfo) {
  27086. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27087. }
  27088. };
  27089. Gamepads.prototype._onGamepadConnected = function (evt) {
  27090. var newGamepad = this._addNewGamepad(evt.gamepad);
  27091. if (this._callbackGamepadConnected)
  27092. this._callbackGamepadConnected(newGamepad);
  27093. this._startMonitoringGamepads();
  27094. };
  27095. Gamepads.prototype._addNewGamepad = function (gamepad) {
  27096. if (!this.oneGamepadConnected) {
  27097. this.oneGamepadConnected = true;
  27098. if (Gamepads.gamepadDOMInfo) {
  27099. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27100. Gamepads.gamepadDOMInfo = null;
  27101. }
  27102. }
  27103. var newGamepad;
  27104. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  27105. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  27106. }
  27107. else {
  27108. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  27109. }
  27110. this.babylonGamepads.push(newGamepad);
  27111. return newGamepad;
  27112. };
  27113. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  27114. for (var i in this.babylonGamepads) {
  27115. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  27116. this.babylonGamepads.splice(i, 1);
  27117. break;
  27118. }
  27119. }
  27120. // If no gamepads are left, stop the polling loop.
  27121. if (this.babylonGamepads.length == 0) {
  27122. this._stopMonitoringGamepads();
  27123. }
  27124. };
  27125. Gamepads.prototype._startMonitoringGamepads = function () {
  27126. if (!this.isMonitoring) {
  27127. this.isMonitoring = true;
  27128. this._checkGamepadsStatus();
  27129. }
  27130. };
  27131. Gamepads.prototype._stopMonitoringGamepads = function () {
  27132. this.isMonitoring = false;
  27133. };
  27134. Gamepads.prototype._checkGamepadsStatus = function () {
  27135. var _this = this;
  27136. // updating gamepad objects
  27137. this._updateGamepadObjects();
  27138. for (var i in this.babylonGamepads) {
  27139. this.babylonGamepads[i].update();
  27140. }
  27141. if (this.isMonitoring) {
  27142. if (window.requestAnimationFrame) {
  27143. window.requestAnimationFrame(function () {
  27144. _this._checkGamepadsStatus();
  27145. });
  27146. }
  27147. else if (window.mozRequestAnimationFrame) {
  27148. window.mozRequestAnimationFrame(function () {
  27149. _this._checkGamepadsStatus();
  27150. });
  27151. }
  27152. else if (window.webkitRequestAnimationFrame) {
  27153. window.webkitRequestAnimationFrame(function () {
  27154. _this._checkGamepadsStatus();
  27155. });
  27156. }
  27157. }
  27158. };
  27159. // This function is called only on Chrome, which does not yet support
  27160. // connection/disconnection events, but requires you to monitor
  27161. // an array for changes.
  27162. Gamepads.prototype._updateGamepadObjects = function () {
  27163. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  27164. for (var i = 0; i < gamepads.length; i++) {
  27165. if (gamepads[i]) {
  27166. if (!(gamepads[i].index in this.babylonGamepads)) {
  27167. var newGamepad = this._addNewGamepad(gamepads[i]);
  27168. if (this._callbackGamepadConnected) {
  27169. this._callbackGamepadConnected(newGamepad);
  27170. }
  27171. }
  27172. else {
  27173. this.babylonGamepads[i].browserGamepad = gamepads[i];
  27174. }
  27175. }
  27176. }
  27177. };
  27178. return Gamepads;
  27179. })();
  27180. BABYLON.Gamepads = Gamepads;
  27181. var StickValues = (function () {
  27182. function StickValues(x, y) {
  27183. this.x = x;
  27184. this.y = y;
  27185. }
  27186. return StickValues;
  27187. })();
  27188. BABYLON.StickValues = StickValues;
  27189. var Gamepad = (function () {
  27190. function Gamepad(id, index, browserGamepad) {
  27191. this.id = id;
  27192. this.index = index;
  27193. this.browserGamepad = browserGamepad;
  27194. if (this.browserGamepad.axes.length >= 2) {
  27195. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27196. }
  27197. if (this.browserGamepad.axes.length >= 4) {
  27198. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27199. }
  27200. }
  27201. Gamepad.prototype.onleftstickchanged = function (callback) {
  27202. this._onleftstickchanged = callback;
  27203. };
  27204. Gamepad.prototype.onrightstickchanged = function (callback) {
  27205. this._onrightstickchanged = callback;
  27206. };
  27207. Object.defineProperty(Gamepad.prototype, "leftStick", {
  27208. get: function () {
  27209. return this._leftStick;
  27210. },
  27211. set: function (newValues) {
  27212. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  27213. this._onleftstickchanged(newValues);
  27214. }
  27215. this._leftStick = newValues;
  27216. },
  27217. enumerable: true,
  27218. configurable: true
  27219. });
  27220. Object.defineProperty(Gamepad.prototype, "rightStick", {
  27221. get: function () {
  27222. return this._rightStick;
  27223. },
  27224. set: function (newValues) {
  27225. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  27226. this._onrightstickchanged(newValues);
  27227. }
  27228. this._rightStick = newValues;
  27229. },
  27230. enumerable: true,
  27231. configurable: true
  27232. });
  27233. Gamepad.prototype.update = function () {
  27234. if (this._leftStick) {
  27235. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27236. }
  27237. if (this._rightStick) {
  27238. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27239. }
  27240. };
  27241. return Gamepad;
  27242. })();
  27243. BABYLON.Gamepad = Gamepad;
  27244. var GenericPad = (function (_super) {
  27245. __extends(GenericPad, _super);
  27246. function GenericPad(id, index, gamepad) {
  27247. _super.call(this, id, index, gamepad);
  27248. this.id = id;
  27249. this.index = index;
  27250. this.gamepad = gamepad;
  27251. this._buttons = new Array(gamepad.buttons.length);
  27252. }
  27253. GenericPad.prototype.onbuttondown = function (callback) {
  27254. this._onbuttondown = callback;
  27255. };
  27256. GenericPad.prototype.onbuttonup = function (callback) {
  27257. this._onbuttonup = callback;
  27258. };
  27259. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  27260. if (newValue !== currentValue) {
  27261. if (this._onbuttondown && newValue === 1) {
  27262. this._onbuttondown(buttonIndex);
  27263. }
  27264. if (this._onbuttonup && newValue === 0) {
  27265. this._onbuttonup(buttonIndex);
  27266. }
  27267. }
  27268. return newValue;
  27269. };
  27270. GenericPad.prototype.update = function () {
  27271. _super.prototype.update.call(this);
  27272. for (var index = 0; index < this._buttons.length; index++) {
  27273. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  27274. }
  27275. };
  27276. return GenericPad;
  27277. })(Gamepad);
  27278. BABYLON.GenericPad = GenericPad;
  27279. (function (Xbox360Button) {
  27280. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  27281. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  27282. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  27283. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  27284. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  27285. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  27286. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  27287. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  27288. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  27289. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  27290. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  27291. var Xbox360Button = BABYLON.Xbox360Button;
  27292. (function (Xbox360Dpad) {
  27293. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  27294. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  27295. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  27296. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  27297. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  27298. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  27299. var Xbox360Pad = (function (_super) {
  27300. __extends(Xbox360Pad, _super);
  27301. function Xbox360Pad() {
  27302. _super.apply(this, arguments);
  27303. this._leftTrigger = 0;
  27304. this._rightTrigger = 0;
  27305. this._buttonA = 0;
  27306. this._buttonB = 0;
  27307. this._buttonX = 0;
  27308. this._buttonY = 0;
  27309. this._buttonBack = 0;
  27310. this._buttonStart = 0;
  27311. this._buttonLB = 0;
  27312. this._buttonRB = 0;
  27313. this._buttonLeftStick = 0;
  27314. this._buttonRightStick = 0;
  27315. this._dPadUp = 0;
  27316. this._dPadDown = 0;
  27317. this._dPadLeft = 0;
  27318. this._dPadRight = 0;
  27319. }
  27320. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  27321. this._onlefttriggerchanged = callback;
  27322. };
  27323. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  27324. this._onrighttriggerchanged = callback;
  27325. };
  27326. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  27327. get: function () {
  27328. return this._leftTrigger;
  27329. },
  27330. set: function (newValue) {
  27331. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  27332. this._onlefttriggerchanged(newValue);
  27333. }
  27334. this._leftTrigger = newValue;
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  27340. get: function () {
  27341. return this._rightTrigger;
  27342. },
  27343. set: function (newValue) {
  27344. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  27345. this._onrighttriggerchanged(newValue);
  27346. }
  27347. this._rightTrigger = newValue;
  27348. },
  27349. enumerable: true,
  27350. configurable: true
  27351. });
  27352. Xbox360Pad.prototype.onbuttondown = function (callback) {
  27353. this._onbuttondown = callback;
  27354. };
  27355. Xbox360Pad.prototype.onbuttonup = function (callback) {
  27356. this._onbuttonup = callback;
  27357. };
  27358. Xbox360Pad.prototype.ondpaddown = function (callback) {
  27359. this._ondpaddown = callback;
  27360. };
  27361. Xbox360Pad.prototype.ondpadup = function (callback) {
  27362. this._ondpadup = callback;
  27363. };
  27364. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  27365. if (newValue !== currentValue) {
  27366. if (this._onbuttondown && newValue === 1) {
  27367. this._onbuttondown(buttonType);
  27368. }
  27369. if (this._onbuttonup && newValue === 0) {
  27370. this._onbuttonup(buttonType);
  27371. }
  27372. }
  27373. return newValue;
  27374. };
  27375. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  27376. if (newValue !== currentValue) {
  27377. if (this._ondpaddown && newValue === 1) {
  27378. this._ondpaddown(buttonType);
  27379. }
  27380. if (this._ondpadup && newValue === 0) {
  27381. this._ondpadup(buttonType);
  27382. }
  27383. }
  27384. return newValue;
  27385. };
  27386. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  27387. get: function () {
  27388. return this._buttonA;
  27389. },
  27390. set: function (value) {
  27391. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  27392. },
  27393. enumerable: true,
  27394. configurable: true
  27395. });
  27396. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  27397. get: function () {
  27398. return this._buttonB;
  27399. },
  27400. set: function (value) {
  27401. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  27402. },
  27403. enumerable: true,
  27404. configurable: true
  27405. });
  27406. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  27407. get: function () {
  27408. return this._buttonX;
  27409. },
  27410. set: function (value) {
  27411. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  27412. },
  27413. enumerable: true,
  27414. configurable: true
  27415. });
  27416. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  27417. get: function () {
  27418. return this._buttonY;
  27419. },
  27420. set: function (value) {
  27421. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  27422. },
  27423. enumerable: true,
  27424. configurable: true
  27425. });
  27426. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  27427. get: function () {
  27428. return this._buttonStart;
  27429. },
  27430. set: function (value) {
  27431. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  27432. },
  27433. enumerable: true,
  27434. configurable: true
  27435. });
  27436. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  27437. get: function () {
  27438. return this._buttonBack;
  27439. },
  27440. set: function (value) {
  27441. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  27442. },
  27443. enumerable: true,
  27444. configurable: true
  27445. });
  27446. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  27447. get: function () {
  27448. return this._buttonLB;
  27449. },
  27450. set: function (value) {
  27451. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  27452. },
  27453. enumerable: true,
  27454. configurable: true
  27455. });
  27456. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  27457. get: function () {
  27458. return this._buttonRB;
  27459. },
  27460. set: function (value) {
  27461. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  27462. },
  27463. enumerable: true,
  27464. configurable: true
  27465. });
  27466. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  27467. get: function () {
  27468. return this._buttonLeftStick;
  27469. },
  27470. set: function (value) {
  27471. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  27472. },
  27473. enumerable: true,
  27474. configurable: true
  27475. });
  27476. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  27477. get: function () {
  27478. return this._buttonRightStick;
  27479. },
  27480. set: function (value) {
  27481. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  27482. },
  27483. enumerable: true,
  27484. configurable: true
  27485. });
  27486. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  27487. get: function () {
  27488. return this._dPadUp;
  27489. },
  27490. set: function (value) {
  27491. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  27492. },
  27493. enumerable: true,
  27494. configurable: true
  27495. });
  27496. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  27497. get: function () {
  27498. return this._dPadDown;
  27499. },
  27500. set: function (value) {
  27501. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  27502. },
  27503. enumerable: true,
  27504. configurable: true
  27505. });
  27506. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  27507. get: function () {
  27508. return this._dPadLeft;
  27509. },
  27510. set: function (value) {
  27511. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  27512. },
  27513. enumerable: true,
  27514. configurable: true
  27515. });
  27516. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  27517. get: function () {
  27518. return this._dPadRight;
  27519. },
  27520. set: function (value) {
  27521. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  27522. },
  27523. enumerable: true,
  27524. configurable: true
  27525. });
  27526. Xbox360Pad.prototype.update = function () {
  27527. _super.prototype.update.call(this);
  27528. this.buttonA = this.browserGamepad.buttons[0].value;
  27529. this.buttonB = this.browserGamepad.buttons[1].value;
  27530. this.buttonX = this.browserGamepad.buttons[2].value;
  27531. this.buttonY = this.browserGamepad.buttons[3].value;
  27532. this.buttonLB = this.browserGamepad.buttons[4].value;
  27533. this.buttonRB = this.browserGamepad.buttons[5].value;
  27534. this.leftTrigger = this.browserGamepad.buttons[6].value;
  27535. this.rightTrigger = this.browserGamepad.buttons[7].value;
  27536. this.buttonBack = this.browserGamepad.buttons[8].value;
  27537. this.buttonStart = this.browserGamepad.buttons[9].value;
  27538. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  27539. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  27540. this.dPadUp = this.browserGamepad.buttons[12].value;
  27541. this.dPadDown = this.browserGamepad.buttons[13].value;
  27542. this.dPadLeft = this.browserGamepad.buttons[14].value;
  27543. this.dPadRight = this.browserGamepad.buttons[15].value;
  27544. };
  27545. return Xbox360Pad;
  27546. })(Gamepad);
  27547. BABYLON.Xbox360Pad = Xbox360Pad;
  27548. })(BABYLON || (BABYLON = {}));
  27549. //# sourceMappingURL=babylon.gamepads.js.map
  27550. var __extends = this.__extends || function (d, b) {
  27551. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27552. function __() { this.constructor = d; }
  27553. __.prototype = b.prototype;
  27554. d.prototype = new __();
  27555. };
  27556. var BABYLON;
  27557. (function (BABYLON) {
  27558. // We're mainly based on the logic defined into the FreeCamera code
  27559. var GamepadCamera = (function (_super) {
  27560. __extends(GamepadCamera, _super);
  27561. function GamepadCamera(name, position, scene) {
  27562. var _this = this;
  27563. _super.call(this, name, position, scene);
  27564. this.angularSensibility = 200;
  27565. this.moveSensibility = 75;
  27566. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  27567. _this._onNewGameConnected(gamepad);
  27568. });
  27569. }
  27570. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  27571. // Only the first gamepad can control the camera
  27572. if (gamepad.index === 0) {
  27573. this._gamepad = gamepad;
  27574. }
  27575. };
  27576. GamepadCamera.prototype._checkInputs = function () {
  27577. if (!this._gamepad) {
  27578. return;
  27579. }
  27580. var LSValues = this._gamepad.leftStick;
  27581. var normalizedLX = LSValues.x / this.moveSensibility;
  27582. var normalizedLY = LSValues.y / this.moveSensibility;
  27583. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  27584. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  27585. var RSValues = this._gamepad.rightStick;
  27586. var normalizedRX = RSValues.x / this.angularSensibility;
  27587. var normalizedRY = RSValues.y / this.angularSensibility;
  27588. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  27589. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  27590. ;
  27591. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  27592. var speed = this._computeLocalCameraSpeed() * 50.0;
  27593. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  27594. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  27595. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  27596. };
  27597. GamepadCamera.prototype.dispose = function () {
  27598. this._gamepads.dispose();
  27599. _super.prototype.dispose.call(this);
  27600. };
  27601. return GamepadCamera;
  27602. })(BABYLON.FreeCamera);
  27603. BABYLON.GamepadCamera = GamepadCamera;
  27604. })(BABYLON || (BABYLON = {}));
  27605. //# sourceMappingURL=babylon.gamepadCamera.js.map
  27606. var __extends = this.__extends || function (d, b) {
  27607. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27608. function __() { this.constructor = d; }
  27609. __.prototype = b.prototype;
  27610. d.prototype = new __();
  27611. };
  27612. var BABYLON;
  27613. (function (BABYLON) {
  27614. var LinesMesh = (function (_super) {
  27615. __extends(LinesMesh, _super);
  27616. function LinesMesh(name, scene, updatable) {
  27617. if (updatable === void 0) { updatable = false; }
  27618. _super.call(this, name, scene);
  27619. this.color = new BABYLON.Color3(1, 1, 1);
  27620. this.alpha = 1;
  27621. this._indices = new Array();
  27622. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27623. attributes: ["position"],
  27624. uniforms: ["worldViewProjection", "color"],
  27625. needAlphaBlending: true
  27626. });
  27627. }
  27628. Object.defineProperty(LinesMesh.prototype, "material", {
  27629. get: function () {
  27630. return this._colorShader;
  27631. },
  27632. enumerable: true,
  27633. configurable: true
  27634. });
  27635. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27636. get: function () {
  27637. return false;
  27638. },
  27639. enumerable: true,
  27640. configurable: true
  27641. });
  27642. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27643. get: function () {
  27644. return false;
  27645. },
  27646. enumerable: true,
  27647. configurable: true
  27648. });
  27649. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27650. var engine = this.getScene().getEngine();
  27651. var indexToBind = this._geometry.getIndexBuffer();
  27652. // VBOs
  27653. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27654. // Color
  27655. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27656. };
  27657. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27658. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27659. return;
  27660. }
  27661. var engine = this.getScene().getEngine();
  27662. // Draw order
  27663. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27664. };
  27665. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27666. return null;
  27667. };
  27668. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27669. this._colorShader.dispose();
  27670. _super.prototype.dispose.call(this, doNotRecurse);
  27671. };
  27672. return LinesMesh;
  27673. })(BABYLON.Mesh);
  27674. BABYLON.LinesMesh = LinesMesh;
  27675. })(BABYLON || (BABYLON = {}));
  27676. //# sourceMappingURL=babylon.linesMesh.js.map
  27677. var BABYLON;
  27678. (function (BABYLON) {
  27679. var OutlineRenderer = (function () {
  27680. function OutlineRenderer(scene) {
  27681. this._scene = scene;
  27682. }
  27683. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27684. var _this = this;
  27685. if (useOverlay === void 0) { useOverlay = false; }
  27686. var scene = this._scene;
  27687. var engine = this._scene.getEngine();
  27688. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27689. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27690. return;
  27691. }
  27692. var mesh = subMesh.getRenderingMesh();
  27693. var material = subMesh.getMaterial();
  27694. engine.enableEffect(this._effect);
  27695. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27696. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27697. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27698. // Bones
  27699. if (mesh.useBones) {
  27700. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27701. }
  27702. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27703. // Alpha test
  27704. if (material && material.needAlphaTesting()) {
  27705. var alphaTexture = material.getAlphaTestTexture();
  27706. this._effect.setTexture("diffuseSampler", alphaTexture);
  27707. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27708. }
  27709. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  27710. _this._effect.setMatrix("world", world);
  27711. });
  27712. };
  27713. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27714. var defines = [];
  27715. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27716. var mesh = subMesh.getMesh();
  27717. var material = subMesh.getMaterial();
  27718. // Alpha test
  27719. if (material && material.needAlphaTesting()) {
  27720. defines.push("#define ALPHATEST");
  27721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27722. attribs.push(BABYLON.VertexBuffer.UVKind);
  27723. defines.push("#define UV1");
  27724. }
  27725. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27726. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27727. defines.push("#define UV2");
  27728. }
  27729. }
  27730. // Bones
  27731. if (mesh.useBones) {
  27732. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27733. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27734. defines.push("#define BONES");
  27735. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27736. }
  27737. // Instances
  27738. if (useInstances) {
  27739. defines.push("#define INSTANCES");
  27740. attribs.push("world0");
  27741. attribs.push("world1");
  27742. attribs.push("world2");
  27743. attribs.push("world3");
  27744. }
  27745. // Get correct effect
  27746. var join = defines.join("\n");
  27747. if (this._cachedDefines !== join) {
  27748. this._cachedDefines = join;
  27749. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  27750. }
  27751. return this._effect.isReady();
  27752. };
  27753. return OutlineRenderer;
  27754. })();
  27755. BABYLON.OutlineRenderer = OutlineRenderer;
  27756. })(BABYLON || (BABYLON = {}));
  27757. //# sourceMappingURL=babylon.outlineRenderer.js.map
  27758. var BABYLON;
  27759. (function (BABYLON) {
  27760. var MeshAssetTask = (function () {
  27761. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  27762. this.name = name;
  27763. this.meshesNames = meshesNames;
  27764. this.rootUrl = rootUrl;
  27765. this.sceneFilename = sceneFilename;
  27766. this.isCompleted = false;
  27767. }
  27768. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27769. var _this = this;
  27770. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  27771. _this.loadedMeshes = meshes;
  27772. _this.loadedParticleSystems = particleSystems;
  27773. _this.loadedSkeletons = skeletons;
  27774. _this.isCompleted = true;
  27775. if (_this.onSuccess) {
  27776. _this.onSuccess(_this);
  27777. }
  27778. onSuccess();
  27779. }, null, function () {
  27780. if (_this.onError) {
  27781. _this.onError(_this);
  27782. }
  27783. onError();
  27784. });
  27785. };
  27786. return MeshAssetTask;
  27787. })();
  27788. BABYLON.MeshAssetTask = MeshAssetTask;
  27789. var TextFileAssetTask = (function () {
  27790. function TextFileAssetTask(name, url) {
  27791. this.name = name;
  27792. this.url = url;
  27793. this.isCompleted = false;
  27794. }
  27795. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27796. var _this = this;
  27797. BABYLON.Tools.LoadFile(this.url, function (data) {
  27798. _this.text = data;
  27799. _this.isCompleted = true;
  27800. if (_this.onSuccess) {
  27801. _this.onSuccess(_this);
  27802. }
  27803. onSuccess();
  27804. }, null, scene.database, false, function () {
  27805. if (_this.onError) {
  27806. _this.onError(_this);
  27807. }
  27808. onError();
  27809. });
  27810. };
  27811. return TextFileAssetTask;
  27812. })();
  27813. BABYLON.TextFileAssetTask = TextFileAssetTask;
  27814. var BinaryFileAssetTask = (function () {
  27815. function BinaryFileAssetTask(name, url) {
  27816. this.name = name;
  27817. this.url = url;
  27818. this.isCompleted = false;
  27819. }
  27820. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27821. var _this = this;
  27822. BABYLON.Tools.LoadFile(this.url, function (data) {
  27823. _this.data = data;
  27824. _this.isCompleted = true;
  27825. if (_this.onSuccess) {
  27826. _this.onSuccess(_this);
  27827. }
  27828. onSuccess();
  27829. }, null, scene.database, true, function () {
  27830. if (_this.onError) {
  27831. _this.onError(_this);
  27832. }
  27833. onError();
  27834. });
  27835. };
  27836. return BinaryFileAssetTask;
  27837. })();
  27838. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  27839. var ImageAssetTask = (function () {
  27840. function ImageAssetTask(name, url) {
  27841. this.name = name;
  27842. this.url = url;
  27843. this.isCompleted = false;
  27844. }
  27845. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27846. var _this = this;
  27847. var img = new Image();
  27848. img.onload = function () {
  27849. _this.image = img;
  27850. _this.isCompleted = true;
  27851. if (_this.onSuccess) {
  27852. _this.onSuccess(_this);
  27853. }
  27854. onSuccess();
  27855. };
  27856. img.onerror = function () {
  27857. if (_this.onError) {
  27858. _this.onError(_this);
  27859. }
  27860. onError();
  27861. };
  27862. img.src = this.url;
  27863. };
  27864. return ImageAssetTask;
  27865. })();
  27866. BABYLON.ImageAssetTask = ImageAssetTask;
  27867. var TextureAssetTask = (function () {
  27868. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  27869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27870. this.name = name;
  27871. this.url = url;
  27872. this.noMipmap = noMipmap;
  27873. this.invertY = invertY;
  27874. this.samplingMode = samplingMode;
  27875. this.isCompleted = false;
  27876. }
  27877. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27878. var _this = this;
  27879. var onload = function () {
  27880. _this.isCompleted = true;
  27881. if (_this.onSuccess) {
  27882. _this.onSuccess(_this);
  27883. }
  27884. onSuccess();
  27885. };
  27886. var onerror = function () {
  27887. if (_this.onError) {
  27888. _this.onError(_this);
  27889. }
  27890. onError();
  27891. };
  27892. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  27893. };
  27894. return TextureAssetTask;
  27895. })();
  27896. BABYLON.TextureAssetTask = TextureAssetTask;
  27897. var AssetsManager = (function () {
  27898. function AssetsManager(scene) {
  27899. this._tasks = new Array();
  27900. this._waitingTasksCount = 0;
  27901. this.useDefaultLoadingScreen = true;
  27902. this._scene = scene;
  27903. }
  27904. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  27905. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  27906. this._tasks.push(task);
  27907. return task;
  27908. };
  27909. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  27910. var task = new TextFileAssetTask(taskName, url);
  27911. this._tasks.push(task);
  27912. return task;
  27913. };
  27914. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  27915. var task = new BinaryFileAssetTask(taskName, url);
  27916. this._tasks.push(task);
  27917. return task;
  27918. };
  27919. AssetsManager.prototype.addImageTask = function (taskName, url) {
  27920. var task = new ImageAssetTask(taskName, url);
  27921. this._tasks.push(task);
  27922. return task;
  27923. };
  27924. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  27925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27926. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  27927. this._tasks.push(task);
  27928. return task;
  27929. };
  27930. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  27931. this._waitingTasksCount--;
  27932. if (this._waitingTasksCount === 0) {
  27933. if (this.onFinish) {
  27934. this.onFinish(this._tasks);
  27935. }
  27936. this._scene.getEngine().hideLoadingUI();
  27937. }
  27938. };
  27939. AssetsManager.prototype._runTask = function (task) {
  27940. var _this = this;
  27941. task.run(this._scene, function () {
  27942. if (_this.onTaskSuccess) {
  27943. _this.onTaskSuccess(task);
  27944. }
  27945. _this._decreaseWaitingTasksCount();
  27946. }, function () {
  27947. if (_this.onTaskError) {
  27948. _this.onTaskError(task);
  27949. }
  27950. _this._decreaseWaitingTasksCount();
  27951. });
  27952. };
  27953. AssetsManager.prototype.reset = function () {
  27954. this._tasks = new Array();
  27955. return this;
  27956. };
  27957. AssetsManager.prototype.load = function () {
  27958. this._waitingTasksCount = this._tasks.length;
  27959. if (this._waitingTasksCount === 0) {
  27960. if (this.onFinish) {
  27961. this.onFinish(this._tasks);
  27962. }
  27963. return this;
  27964. }
  27965. if (this.useDefaultLoadingScreen) {
  27966. this._scene.getEngine().displayLoadingUI();
  27967. }
  27968. for (var index = 0; index < this._tasks.length; index++) {
  27969. var task = this._tasks[index];
  27970. this._runTask(task);
  27971. }
  27972. return this;
  27973. };
  27974. return AssetsManager;
  27975. })();
  27976. BABYLON.AssetsManager = AssetsManager;
  27977. })(BABYLON || (BABYLON = {}));
  27978. //# sourceMappingURL=babylon.assetsManager.js.map
  27979. var __extends = this.__extends || function (d, b) {
  27980. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27981. function __() { this.constructor = d; }
  27982. __.prototype = b.prototype;
  27983. d.prototype = new __();
  27984. };
  27985. var BABYLON;
  27986. (function (BABYLON) {
  27987. var VRDeviceOrientationCamera = (function (_super) {
  27988. __extends(VRDeviceOrientationCamera, _super);
  27989. function VRDeviceOrientationCamera(name, position, scene) {
  27990. _super.call(this, name, position, scene);
  27991. this._alpha = 0;
  27992. this._beta = 0;
  27993. this._gamma = 0;
  27994. }
  27995. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  27996. this._alpha = +evt.alpha | 0;
  27997. this._beta = +evt.beta | 0;
  27998. this._gamma = +evt.gamma | 0;
  27999. if (this._gamma < 0) {
  28000. this._gamma = 90 + this._gamma;
  28001. }
  28002. else {
  28003. // Incline it in the correct angle.
  28004. this._gamma = 270 - this._gamma;
  28005. }
  28006. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28007. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28008. this.rotation.z = this._beta / 180.0 * Math.PI;
  28009. };
  28010. return VRDeviceOrientationCamera;
  28011. })(BABYLON.OculusCamera);
  28012. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  28013. })(BABYLON || (BABYLON = {}));
  28014. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28015. var __extends = this.__extends || function (d, b) {
  28016. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28017. function __() { this.constructor = d; }
  28018. __.prototype = b.prototype;
  28019. d.prototype = new __();
  28020. };
  28021. var BABYLON;
  28022. (function (BABYLON) {
  28023. var WebVRCamera = (function (_super) {
  28024. __extends(WebVRCamera, _super);
  28025. function WebVRCamera(name, position, scene) {
  28026. _super.call(this, name, position, scene);
  28027. this._hmdDevice = null;
  28028. this._sensorDevice = null;
  28029. this._cacheState = null;
  28030. this._cacheQuaternion = new BABYLON.Quaternion();
  28031. this._cacheRotation = BABYLON.Vector3.Zero();
  28032. this._vrEnabled = false;
  28033. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28034. }
  28035. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  28036. var size = devices.length;
  28037. var i = 0;
  28038. // Reset devices.
  28039. this._sensorDevice = null;
  28040. this._hmdDevice = null;
  28041. while (i < size && this._hmdDevice === null) {
  28042. if (devices[i] instanceof HMDVRDevice) {
  28043. this._hmdDevice = devices[i];
  28044. }
  28045. i++;
  28046. }
  28047. i = 0;
  28048. while (i < size && this._sensorDevice === null) {
  28049. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28050. this._sensorDevice = devices[i];
  28051. }
  28052. i++;
  28053. }
  28054. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28055. };
  28056. WebVRCamera.prototype._update = function () {
  28057. if (this._vrEnabled) {
  28058. this._cacheState = this._sensorDevice.getState();
  28059. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28060. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28061. this.rotation.x = -this._cacheRotation.z;
  28062. this.rotation.y = -this._cacheRotation.y;
  28063. this.rotation.z = this._cacheRotation.x;
  28064. }
  28065. _super.prototype._update.call(this);
  28066. };
  28067. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  28068. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28069. if (navigator.getVRDevices) {
  28070. navigator.getVRDevices().then(this._getWebVRDevices);
  28071. }
  28072. else if (navigator.mozGetVRDevices) {
  28073. navigator.mozGetVRDevices(this._getWebVRDevices);
  28074. }
  28075. };
  28076. WebVRCamera.prototype.detachControl = function (element) {
  28077. _super.prototype.detachControl.call(this, element);
  28078. this._vrEnabled = false;
  28079. };
  28080. return WebVRCamera;
  28081. })(BABYLON.OculusCamera);
  28082. BABYLON.WebVRCamera = WebVRCamera;
  28083. })(BABYLON || (BABYLON = {}));
  28084. //# sourceMappingURL=babylon.webVRCamera.js.map
  28085. var __extends = this.__extends || function (d, b) {
  28086. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28087. function __() { this.constructor = d; }
  28088. __.prototype = b.prototype;
  28089. d.prototype = new __();
  28090. };
  28091. var BABYLON;
  28092. (function (BABYLON) {
  28093. // Standard optimizations
  28094. var SceneOptimization = (function () {
  28095. function SceneOptimization(priority) {
  28096. if (priority === void 0) { priority = 0; }
  28097. this.priority = priority;
  28098. this.apply = function (scene) {
  28099. return true; // Return true if everything that can be done was applied
  28100. };
  28101. }
  28102. return SceneOptimization;
  28103. })();
  28104. BABYLON.SceneOptimization = SceneOptimization;
  28105. var TextureOptimization = (function (_super) {
  28106. __extends(TextureOptimization, _super);
  28107. function TextureOptimization(priority, maximumSize) {
  28108. var _this = this;
  28109. if (priority === void 0) { priority = 0; }
  28110. if (maximumSize === void 0) { maximumSize = 1024; }
  28111. _super.call(this, priority);
  28112. this.priority = priority;
  28113. this.maximumSize = maximumSize;
  28114. this.apply = function (scene) {
  28115. var allDone = true;
  28116. for (var index = 0; index < scene.textures.length; index++) {
  28117. var texture = scene.textures[index];
  28118. if (!texture.canRescale) {
  28119. continue;
  28120. }
  28121. var currentSize = texture.getSize();
  28122. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28123. if (maxDimension > _this.maximumSize) {
  28124. texture.scale(0.5);
  28125. allDone = false;
  28126. }
  28127. }
  28128. return allDone;
  28129. };
  28130. }
  28131. return TextureOptimization;
  28132. })(SceneOptimization);
  28133. BABYLON.TextureOptimization = TextureOptimization;
  28134. var HardwareScalingOptimization = (function (_super) {
  28135. __extends(HardwareScalingOptimization, _super);
  28136. function HardwareScalingOptimization(priority, maximumScale) {
  28137. var _this = this;
  28138. if (priority === void 0) { priority = 0; }
  28139. if (maximumScale === void 0) { maximumScale = 2; }
  28140. _super.call(this, priority);
  28141. this.priority = priority;
  28142. this.maximumScale = maximumScale;
  28143. this._currentScale = 1;
  28144. this.apply = function (scene) {
  28145. _this._currentScale++;
  28146. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28147. return _this._currentScale >= _this.maximumScale;
  28148. };
  28149. }
  28150. return HardwareScalingOptimization;
  28151. })(SceneOptimization);
  28152. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28153. var ShadowsOptimization = (function (_super) {
  28154. __extends(ShadowsOptimization, _super);
  28155. function ShadowsOptimization() {
  28156. _super.apply(this, arguments);
  28157. this.apply = function (scene) {
  28158. scene.shadowsEnabled = false;
  28159. return true;
  28160. };
  28161. }
  28162. return ShadowsOptimization;
  28163. })(SceneOptimization);
  28164. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28165. var PostProcessesOptimization = (function (_super) {
  28166. __extends(PostProcessesOptimization, _super);
  28167. function PostProcessesOptimization() {
  28168. _super.apply(this, arguments);
  28169. this.apply = function (scene) {
  28170. scene.postProcessesEnabled = false;
  28171. return true;
  28172. };
  28173. }
  28174. return PostProcessesOptimization;
  28175. })(SceneOptimization);
  28176. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28177. var LensFlaresOptimization = (function (_super) {
  28178. __extends(LensFlaresOptimization, _super);
  28179. function LensFlaresOptimization() {
  28180. _super.apply(this, arguments);
  28181. this.apply = function (scene) {
  28182. scene.lensFlaresEnabled = false;
  28183. return true;
  28184. };
  28185. }
  28186. return LensFlaresOptimization;
  28187. })(SceneOptimization);
  28188. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28189. var ParticlesOptimization = (function (_super) {
  28190. __extends(ParticlesOptimization, _super);
  28191. function ParticlesOptimization() {
  28192. _super.apply(this, arguments);
  28193. this.apply = function (scene) {
  28194. scene.particlesEnabled = false;
  28195. return true;
  28196. };
  28197. }
  28198. return ParticlesOptimization;
  28199. })(SceneOptimization);
  28200. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28201. var RenderTargetsOptimization = (function (_super) {
  28202. __extends(RenderTargetsOptimization, _super);
  28203. function RenderTargetsOptimization() {
  28204. _super.apply(this, arguments);
  28205. this.apply = function (scene) {
  28206. scene.renderTargetsEnabled = false;
  28207. return true;
  28208. };
  28209. }
  28210. return RenderTargetsOptimization;
  28211. })(SceneOptimization);
  28212. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28213. var MergeMeshesOptimization = (function (_super) {
  28214. __extends(MergeMeshesOptimization, _super);
  28215. function MergeMeshesOptimization() {
  28216. var _this = this;
  28217. _super.apply(this, arguments);
  28218. this._canBeMerged = function (abstractMesh) {
  28219. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28220. return false;
  28221. }
  28222. var mesh = abstractMesh;
  28223. if (!mesh.isVisible || !mesh.isEnabled()) {
  28224. return false;
  28225. }
  28226. if (mesh.instances.length > 0) {
  28227. return false;
  28228. }
  28229. if (mesh.skeleton || mesh.hasLODLevels) {
  28230. return false;
  28231. }
  28232. return true;
  28233. };
  28234. this.apply = function (scene) {
  28235. var globalPool = scene.meshes.slice(0);
  28236. var globalLength = globalPool.length;
  28237. for (var index = 0; index < globalLength; index++) {
  28238. var currentPool = new Array();
  28239. var current = globalPool[index];
  28240. // Checks
  28241. if (!_this._canBeMerged(current)) {
  28242. continue;
  28243. }
  28244. currentPool.push(current);
  28245. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28246. var otherMesh = globalPool[subIndex];
  28247. if (!_this._canBeMerged(otherMesh)) {
  28248. continue;
  28249. }
  28250. if (otherMesh.material !== current.material) {
  28251. continue;
  28252. }
  28253. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28254. continue;
  28255. }
  28256. currentPool.push(otherMesh);
  28257. globalLength--;
  28258. globalPool.splice(subIndex, 1);
  28259. subIndex--;
  28260. }
  28261. if (currentPool.length < 2) {
  28262. continue;
  28263. }
  28264. // Merge meshes
  28265. BABYLON.Mesh.MergeMeshes(currentPool);
  28266. }
  28267. return true;
  28268. };
  28269. }
  28270. return MergeMeshesOptimization;
  28271. })(SceneOptimization);
  28272. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28273. // Options
  28274. var SceneOptimizerOptions = (function () {
  28275. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28276. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28277. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28278. this.targetFrameRate = targetFrameRate;
  28279. this.trackerDuration = trackerDuration;
  28280. this.optimizations = new Array();
  28281. }
  28282. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28283. var result = new SceneOptimizerOptions(targetFrameRate);
  28284. var priority = 0;
  28285. result.optimizations.push(new MergeMeshesOptimization(priority));
  28286. result.optimizations.push(new ShadowsOptimization(priority));
  28287. result.optimizations.push(new LensFlaresOptimization(priority));
  28288. // Next priority
  28289. priority++;
  28290. result.optimizations.push(new PostProcessesOptimization(priority));
  28291. result.optimizations.push(new ParticlesOptimization(priority));
  28292. // Next priority
  28293. priority++;
  28294. result.optimizations.push(new TextureOptimization(priority, 1024));
  28295. return result;
  28296. };
  28297. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28298. var result = new SceneOptimizerOptions(targetFrameRate);
  28299. var priority = 0;
  28300. result.optimizations.push(new MergeMeshesOptimization(priority));
  28301. result.optimizations.push(new ShadowsOptimization(priority));
  28302. result.optimizations.push(new LensFlaresOptimization(priority));
  28303. // Next priority
  28304. priority++;
  28305. result.optimizations.push(new PostProcessesOptimization(priority));
  28306. result.optimizations.push(new ParticlesOptimization(priority));
  28307. // Next priority
  28308. priority++;
  28309. result.optimizations.push(new TextureOptimization(priority, 512));
  28310. // Next priority
  28311. priority++;
  28312. result.optimizations.push(new RenderTargetsOptimization(priority));
  28313. // Next priority
  28314. priority++;
  28315. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28316. return result;
  28317. };
  28318. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28319. var result = new SceneOptimizerOptions(targetFrameRate);
  28320. var priority = 0;
  28321. result.optimizations.push(new MergeMeshesOptimization(priority));
  28322. result.optimizations.push(new ShadowsOptimization(priority));
  28323. result.optimizations.push(new LensFlaresOptimization(priority));
  28324. // Next priority
  28325. priority++;
  28326. result.optimizations.push(new PostProcessesOptimization(priority));
  28327. result.optimizations.push(new ParticlesOptimization(priority));
  28328. // Next priority
  28329. priority++;
  28330. result.optimizations.push(new TextureOptimization(priority, 256));
  28331. // Next priority
  28332. priority++;
  28333. result.optimizations.push(new RenderTargetsOptimization(priority));
  28334. // Next priority
  28335. priority++;
  28336. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28337. return result;
  28338. };
  28339. return SceneOptimizerOptions;
  28340. })();
  28341. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28342. // Scene optimizer tool
  28343. var SceneOptimizer = (function () {
  28344. function SceneOptimizer() {
  28345. }
  28346. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28347. // TODO: add an epsilon
  28348. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28349. if (onSuccess) {
  28350. onSuccess();
  28351. }
  28352. return;
  28353. }
  28354. // Apply current level of optimizations
  28355. var allDone = true;
  28356. var noOptimizationApplied = true;
  28357. for (var index = 0; index < options.optimizations.length; index++) {
  28358. var optimization = options.optimizations[index];
  28359. if (optimization.priority === currentPriorityLevel) {
  28360. noOptimizationApplied = false;
  28361. allDone = allDone && optimization.apply(scene);
  28362. }
  28363. }
  28364. // If no optimization was applied, this is a failure :(
  28365. if (noOptimizationApplied) {
  28366. if (onFailure) {
  28367. onFailure();
  28368. }
  28369. return;
  28370. }
  28371. // If all optimizations were done, move to next level
  28372. if (allDone) {
  28373. currentPriorityLevel++;
  28374. }
  28375. // Let's the system running for a specific amount of time before checking FPS
  28376. scene.executeWhenReady(function () {
  28377. setTimeout(function () {
  28378. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28379. }, options.trackerDuration);
  28380. });
  28381. };
  28382. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28383. if (!options) {
  28384. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28385. }
  28386. // Let's the system running for a specific amount of time before checking FPS
  28387. scene.executeWhenReady(function () {
  28388. setTimeout(function () {
  28389. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28390. }, options.trackerDuration);
  28391. });
  28392. };
  28393. return SceneOptimizer;
  28394. })();
  28395. BABYLON.SceneOptimizer = SceneOptimizer;
  28396. })(BABYLON || (BABYLON = {}));
  28397. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28398. var BABYLON;
  28399. (function (BABYLON) {
  28400. var Internals;
  28401. (function (Internals) {
  28402. var MeshLODLevel = (function () {
  28403. function MeshLODLevel(distance, mesh) {
  28404. this.distance = distance;
  28405. this.mesh = mesh;
  28406. }
  28407. return MeshLODLevel;
  28408. })();
  28409. Internals.MeshLODLevel = MeshLODLevel;
  28410. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28411. })(BABYLON || (BABYLON = {}));
  28412. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28413. var BABYLON;
  28414. (function (BABYLON) {
  28415. var AudioEngine = (function () {
  28416. function AudioEngine() {
  28417. this._audioContext = null;
  28418. this._audioContextInitialized = false;
  28419. this.canUseWebAudio = false;
  28420. this.WarnedWebAudioUnsupported = false;
  28421. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28422. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28423. this.canUseWebAudio = true;
  28424. }
  28425. }
  28426. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28427. get: function () {
  28428. if (!this._audioContextInitialized) {
  28429. this._initializeAudioContext();
  28430. }
  28431. return this._audioContext;
  28432. },
  28433. enumerable: true,
  28434. configurable: true
  28435. });
  28436. AudioEngine.prototype._initializeAudioContext = function () {
  28437. try {
  28438. if (this.canUseWebAudio) {
  28439. this._audioContext = new AudioContext();
  28440. // create a global volume gain node
  28441. this.masterGain = this._audioContext.createGain();
  28442. this.masterGain.gain.value = 1;
  28443. this.masterGain.connect(this._audioContext.destination);
  28444. this._audioContextInitialized = true;
  28445. }
  28446. }
  28447. catch (e) {
  28448. this.canUseWebAudio = false;
  28449. BABYLON.Tools.Error("Web Audio: " + e.message);
  28450. }
  28451. };
  28452. AudioEngine.prototype.dispose = function () {
  28453. if (this.canUseWebAudio && this._audioContextInitialized) {
  28454. if (this._connectedAnalyser) {
  28455. this._connectedAnalyser.stopDebugCanvas();
  28456. this._connectedAnalyser.dispose();
  28457. this.masterGain.disconnect();
  28458. this.masterGain.connect(this._audioContext.destination);
  28459. this._connectedAnalyser = null;
  28460. }
  28461. this.masterGain.gain.value = 1;
  28462. }
  28463. this.WarnedWebAudioUnsupported = false;
  28464. };
  28465. AudioEngine.prototype.getGlobalVolume = function () {
  28466. if (this.canUseWebAudio && this._audioContextInitialized) {
  28467. return this.masterGain.gain.value;
  28468. }
  28469. else {
  28470. return -1;
  28471. }
  28472. };
  28473. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28474. if (this.canUseWebAudio && this._audioContextInitialized) {
  28475. this.masterGain.gain.value = newVolume;
  28476. }
  28477. };
  28478. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28479. if (this._connectedAnalyser) {
  28480. this._connectedAnalyser.stopDebugCanvas();
  28481. }
  28482. if (this.canUseWebAudio && this._audioContextInitialized) {
  28483. this._connectedAnalyser = analyser;
  28484. this.masterGain.disconnect();
  28485. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28486. }
  28487. };
  28488. return AudioEngine;
  28489. })();
  28490. BABYLON.AudioEngine = AudioEngine;
  28491. })(BABYLON || (BABYLON = {}));
  28492. //# sourceMappingURL=babylon.audioEngine.js.map
  28493. var BABYLON;
  28494. (function (BABYLON) {
  28495. var Sound = (function () {
  28496. /**
  28497. * Create a sound and attach it to a scene
  28498. * @param name Name of your sound
  28499. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28500. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28501. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28502. */
  28503. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28504. var _this = this;
  28505. this.autoplay = false;
  28506. this.loop = false;
  28507. this.useCustomAttenuation = false;
  28508. this.spatialSound = false;
  28509. this.refDistance = 1;
  28510. this.rolloffFactor = 1;
  28511. this.maxDistance = 100;
  28512. this.distanceModel = "linear";
  28513. this._panningModel = "equalpower";
  28514. this._playbackRate = 1;
  28515. this._startTime = 0;
  28516. this._startOffset = 0;
  28517. this._position = BABYLON.Vector3.Zero();
  28518. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28519. this._volume = 1;
  28520. this._isLoaded = false;
  28521. this._isReadyToPlay = false;
  28522. this.isPlaying = false;
  28523. this.isPaused = false;
  28524. this._isDirectional = false;
  28525. // Used if you'd like to create a directional sound.
  28526. // If not set, the sound will be omnidirectional
  28527. this._coneInnerAngle = 360;
  28528. this._coneOuterAngle = 360;
  28529. this._coneOuterGain = 0;
  28530. this.name = name;
  28531. this._scene = scene;
  28532. this._readyToPlayCallback = readyToPlayCallback;
  28533. // Default custom attenuation function is a linear attenuation
  28534. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28535. if (currentDistance < maxDistance) {
  28536. return currentVolume * (1 - currentDistance / maxDistance);
  28537. }
  28538. else {
  28539. return 0;
  28540. }
  28541. };
  28542. if (options) {
  28543. this.autoplay = options.autoplay || false;
  28544. this.loop = options.loop || false;
  28545. // if volume === 0, we need another way to check this option
  28546. if (options.volume !== undefined) {
  28547. this._volume = options.volume;
  28548. }
  28549. this.spatialSound = options.spatialSound || false;
  28550. this.maxDistance = options.maxDistance || 100;
  28551. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28552. this.rolloffFactor = options.rolloffFactor || 1;
  28553. this.refDistance = options.refDistance || 1;
  28554. this.distanceModel = options.distanceModel || "linear";
  28555. this._playbackRate = options.playbackRate || 1;
  28556. }
  28557. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28558. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28559. this._soundGain.gain.value = this._volume;
  28560. this._inputAudioNode = this._soundGain;
  28561. this._ouputAudioNode = this._soundGain;
  28562. if (this.spatialSound) {
  28563. this._createSpatialParameters();
  28564. }
  28565. this._scene.mainSoundTrack.AddSound(this);
  28566. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28567. if (urlOrArrayBuffer) {
  28568. // If it's an URL
  28569. if (typeof (urlOrArrayBuffer) === "string") {
  28570. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  28571. _this._soundLoaded(data);
  28572. }, null, null, true);
  28573. }
  28574. else {
  28575. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28576. this._soundLoaded(urlOrArrayBuffer);
  28577. }
  28578. else {
  28579. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28580. }
  28581. }
  28582. }
  28583. }
  28584. else {
  28585. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28586. this._scene.mainSoundTrack.AddSound(this);
  28587. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28588. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28589. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28590. }
  28591. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28592. if (this._readyToPlayCallback) {
  28593. window.setTimeout(function () {
  28594. _this._readyToPlayCallback();
  28595. }, 1000);
  28596. }
  28597. }
  28598. }
  28599. Sound.prototype.dispose = function () {
  28600. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28601. if (this.isPlaying) {
  28602. this.stop();
  28603. }
  28604. this._isReadyToPlay = false;
  28605. if (this.soundTrackId === -1) {
  28606. this._scene.mainSoundTrack.RemoveSound(this);
  28607. }
  28608. else {
  28609. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28610. }
  28611. if (this._soundGain) {
  28612. this._soundGain.disconnect();
  28613. this._soundGain = null;
  28614. }
  28615. if (this._soundPanner) {
  28616. this._soundPanner.disconnect();
  28617. this._soundPanner = null;
  28618. }
  28619. if (this._soundSource) {
  28620. this._soundSource.disconnect();
  28621. this._soundSource = null;
  28622. }
  28623. this._audioBuffer = null;
  28624. if (this._connectedMesh) {
  28625. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28626. this._connectedMesh = null;
  28627. }
  28628. }
  28629. };
  28630. Sound.prototype._soundLoaded = function (audioData) {
  28631. var _this = this;
  28632. this._isLoaded = true;
  28633. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28634. _this._audioBuffer = buffer;
  28635. _this._isReadyToPlay = true;
  28636. if (_this.autoplay) {
  28637. _this.play();
  28638. }
  28639. if (_this._readyToPlayCallback) {
  28640. _this._readyToPlayCallback();
  28641. }
  28642. }, function (error) {
  28643. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  28644. });
  28645. };
  28646. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28647. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28648. this._audioBuffer = audioBuffer;
  28649. this._isReadyToPlay = true;
  28650. }
  28651. };
  28652. Sound.prototype.updateOptions = function (options) {
  28653. if (options) {
  28654. this.loop = options.loop || this.loop;
  28655. this.maxDistance = options.maxDistance || this.maxDistance;
  28656. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28657. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28658. this.refDistance = options.refDistance || this.refDistance;
  28659. this.distanceModel = options.distanceModel || this.distanceModel;
  28660. this._playbackRate = options.playbackRate || this._playbackRate;
  28661. }
  28662. };
  28663. Sound.prototype._createSpatialParameters = function () {
  28664. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28665. if (this._scene.headphone) {
  28666. this._panningModel = "HRTF";
  28667. }
  28668. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28669. if (this.useCustomAttenuation) {
  28670. // Tricks to disable in a way embedded Web Audio attenuation
  28671. this._soundPanner.distanceModel = "linear";
  28672. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28673. this._soundPanner.refDistance = 1;
  28674. this._soundPanner.rolloffFactor = 1;
  28675. this._soundPanner.panningModel = this._panningModel;
  28676. }
  28677. else {
  28678. this._soundPanner.distanceModel = this.distanceModel;
  28679. this._soundPanner.maxDistance = this.maxDistance;
  28680. this._soundPanner.refDistance = this.refDistance;
  28681. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28682. this._soundPanner.panningModel = this._panningModel;
  28683. }
  28684. this._soundPanner.connect(this._ouputAudioNode);
  28685. this._inputAudioNode = this._soundPanner;
  28686. }
  28687. };
  28688. Sound.prototype.switchPanningModelToHRTF = function () {
  28689. this._panningModel = "HRTF";
  28690. this._switchPanningModel();
  28691. };
  28692. Sound.prototype.switchPanningModelToEqualPower = function () {
  28693. this._panningModel = "equalpower";
  28694. this._switchPanningModel();
  28695. };
  28696. Sound.prototype._switchPanningModel = function () {
  28697. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28698. this._soundPanner.panningModel = this._panningModel;
  28699. }
  28700. };
  28701. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28702. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28703. this._ouputAudioNode.disconnect();
  28704. this._ouputAudioNode.connect(soundTrackAudioNode);
  28705. }
  28706. };
  28707. /**
  28708. * Transform this sound into a directional source
  28709. * @param coneInnerAngle Size of the inner cone in degree
  28710. * @param coneOuterAngle Size of the outer cone in degree
  28711. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  28712. */
  28713. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  28714. if (coneOuterAngle < coneInnerAngle) {
  28715. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  28716. return;
  28717. }
  28718. this._coneInnerAngle = coneInnerAngle;
  28719. this._coneOuterAngle = coneOuterAngle;
  28720. this._coneOuterGain = coneOuterGain;
  28721. this._isDirectional = true;
  28722. if (this.isPlaying && this.loop) {
  28723. this.stop();
  28724. this.play();
  28725. }
  28726. };
  28727. Sound.prototype.setPosition = function (newPosition) {
  28728. this._position = newPosition;
  28729. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28730. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28731. }
  28732. };
  28733. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  28734. this._localDirection = newLocalDirection;
  28735. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  28736. this._updateDirection();
  28737. }
  28738. };
  28739. Sound.prototype._updateDirection = function () {
  28740. var mat = this._connectedMesh.getWorldMatrix();
  28741. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  28742. direction.normalize();
  28743. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  28744. };
  28745. Sound.prototype.updateDistanceFromListener = function () {
  28746. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  28747. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  28748. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  28749. }
  28750. };
  28751. Sound.prototype.setAttenuationFunction = function (callback) {
  28752. this._customAttenuationFunction = callback;
  28753. };
  28754. /**
  28755. * Play the sound
  28756. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  28757. */
  28758. Sound.prototype.play = function (time) {
  28759. var _this = this;
  28760. if (this._isReadyToPlay && this._scene.audioEnabled) {
  28761. try {
  28762. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28763. if (!this._soundSource) {
  28764. if (this.spatialSound) {
  28765. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28766. if (this._isDirectional) {
  28767. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  28768. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  28769. this._soundPanner.coneOuterGain = this._coneOuterGain;
  28770. if (this._connectedMesh) {
  28771. this._updateDirection();
  28772. }
  28773. else {
  28774. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  28775. }
  28776. }
  28777. }
  28778. }
  28779. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  28780. this._soundSource.buffer = this._audioBuffer;
  28781. this._soundSource.connect(this._inputAudioNode);
  28782. this._soundSource.loop = this.loop;
  28783. this._soundSource.playbackRate.value = this._playbackRate;
  28784. this._startTime = startTime;
  28785. this._soundSource.onended = function () {
  28786. _this._onended();
  28787. };
  28788. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  28789. this.isPlaying = true;
  28790. this.isPaused = false;
  28791. }
  28792. catch (ex) {
  28793. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  28794. }
  28795. }
  28796. };
  28797. Sound.prototype._onended = function () {
  28798. this.isPlaying = false;
  28799. if (this.onended) {
  28800. this.onended();
  28801. }
  28802. };
  28803. /**
  28804. * Stop the sound
  28805. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  28806. */
  28807. Sound.prototype.stop = function (time) {
  28808. if (this.isPlaying) {
  28809. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28810. this._soundSource.stop(stopTime);
  28811. this.isPlaying = false;
  28812. }
  28813. };
  28814. Sound.prototype.pause = function () {
  28815. if (this.isPlaying) {
  28816. this.stop(0);
  28817. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  28818. this.isPaused = true;
  28819. }
  28820. };
  28821. Sound.prototype.setVolume = function (newVolume, time) {
  28822. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  28823. if (time) {
  28824. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  28825. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  28826. }
  28827. else {
  28828. this._soundGain.gain.value = newVolume;
  28829. }
  28830. }
  28831. this._volume = newVolume;
  28832. };
  28833. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  28834. this._playbackRate = newPlaybackRate;
  28835. if (this.isPlaying) {
  28836. this._soundSource.playbackRate.value = this._playbackRate;
  28837. }
  28838. };
  28839. Sound.prototype.getVolume = function () {
  28840. return this._volume;
  28841. };
  28842. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  28843. var _this = this;
  28844. this._connectedMesh = meshToConnectTo;
  28845. if (!this.spatialSound) {
  28846. this._createSpatialParameters();
  28847. this.spatialSound = true;
  28848. if (this.isPlaying && this.loop) {
  28849. this.stop();
  28850. this.play();
  28851. }
  28852. }
  28853. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  28854. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  28855. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  28856. };
  28857. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  28858. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  28859. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  28860. this._updateDirection();
  28861. }
  28862. };
  28863. return Sound;
  28864. })();
  28865. BABYLON.Sound = Sound;
  28866. })(BABYLON || (BABYLON = {}));
  28867. //# sourceMappingURL=babylon.sound.js.map
  28868. var BABYLON;
  28869. (function (BABYLON) {
  28870. var SoundTrack = (function () {
  28871. function SoundTrack(scene, options) {
  28872. this.id = -1;
  28873. this._isMainTrack = false;
  28874. this._scene = scene;
  28875. this._audioEngine = BABYLON.Engine.audioEngine;
  28876. this.soundCollection = new Array();
  28877. if (this._audioEngine.canUseWebAudio) {
  28878. this._trackGain = this._audioEngine.audioContext.createGain();
  28879. this._trackGain.connect(this._audioEngine.masterGain);
  28880. if (options) {
  28881. if (options.volume) {
  28882. this._trackGain.gain.value = options.volume;
  28883. }
  28884. if (options.mainTrack) {
  28885. this._isMainTrack = options.mainTrack;
  28886. }
  28887. }
  28888. }
  28889. if (!this._isMainTrack) {
  28890. this._scene.soundTracks.push(this);
  28891. this.id = this._scene.soundTracks.length - 1;
  28892. }
  28893. }
  28894. SoundTrack.prototype.dispose = function () {
  28895. if (this._audioEngine.canUseWebAudio) {
  28896. if (this._connectedAnalyser) {
  28897. this._connectedAnalyser.stopDebugCanvas();
  28898. }
  28899. while (this.soundCollection.length) {
  28900. this.soundCollection[0].dispose();
  28901. }
  28902. this._trackGain.disconnect();
  28903. this._trackGain = null;
  28904. }
  28905. };
  28906. SoundTrack.prototype.AddSound = function (sound) {
  28907. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28908. sound.connectToSoundTrackAudioNode(this._trackGain);
  28909. }
  28910. if (sound.soundTrackId) {
  28911. if (sound.soundTrackId === -1) {
  28912. this._scene.mainSoundTrack.RemoveSound(sound);
  28913. }
  28914. else {
  28915. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  28916. }
  28917. }
  28918. this.soundCollection.push(sound);
  28919. sound.soundTrackId = this.id;
  28920. };
  28921. SoundTrack.prototype.RemoveSound = function (sound) {
  28922. var index = this.soundCollection.indexOf(sound);
  28923. if (index !== -1) {
  28924. this.soundCollection.splice(index, 1);
  28925. }
  28926. };
  28927. SoundTrack.prototype.setVolume = function (newVolume) {
  28928. if (this._audioEngine.canUseWebAudio) {
  28929. this._trackGain.gain.value = newVolume;
  28930. }
  28931. };
  28932. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  28933. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28934. for (var i = 0; i < this.soundCollection.length; i++) {
  28935. this.soundCollection[i].switchPanningModelToHRTF();
  28936. }
  28937. }
  28938. };
  28939. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  28940. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28941. for (var i = 0; i < this.soundCollection.length; i++) {
  28942. this.soundCollection[i].switchPanningModelToEqualPower();
  28943. }
  28944. }
  28945. };
  28946. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  28947. if (this._connectedAnalyser) {
  28948. this._connectedAnalyser.stopDebugCanvas();
  28949. }
  28950. this._connectedAnalyser = analyser;
  28951. if (this._audioEngine.canUseWebAudio) {
  28952. this._trackGain.disconnect();
  28953. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  28954. }
  28955. };
  28956. return SoundTrack;
  28957. })();
  28958. BABYLON.SoundTrack = SoundTrack;
  28959. })(BABYLON || (BABYLON = {}));
  28960. //# sourceMappingURL=babylon.soundtrack.js.map
  28961. var BABYLON;
  28962. (function (BABYLON) {
  28963. var DebugLayer = (function () {
  28964. function DebugLayer(scene) {
  28965. var _this = this;
  28966. this._transformationMatrix = BABYLON.Matrix.Identity();
  28967. this._enabled = false;
  28968. this._labelsEnabled = false;
  28969. this._displayStatistics = true;
  28970. this._displayTree = false;
  28971. this._displayLogs = false;
  28972. this._identityMatrix = BABYLON.Matrix.Identity();
  28973. this.axisRatio = 0.02;
  28974. this.accentColor = "orange";
  28975. this._scene = scene;
  28976. this._syncPositions = function () {
  28977. var engine = _this._scene.getEngine();
  28978. var canvasRect = engine.getRenderingCanvasClientRect();
  28979. if (_this._showUI) {
  28980. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28981. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28982. _this._statsDiv.style.width = "400px";
  28983. _this._statsDiv.style.height = "auto";
  28984. _this._statsSubsetDiv.style.maxHeight = "240px";
  28985. _this._optionsDiv.style.left = "0px";
  28986. _this._optionsDiv.style.top = "10px";
  28987. _this._optionsDiv.style.width = "200px";
  28988. _this._optionsDiv.style.height = "auto";
  28989. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28990. _this._logDiv.style.left = "0px";
  28991. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28992. _this._logDiv.style.width = "600px";
  28993. _this._logDiv.style.height = "160px";
  28994. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28995. _this._treeDiv.style.top = "10px";
  28996. _this._treeDiv.style.width = "300px";
  28997. _this._treeDiv.style.height = "auto";
  28998. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28999. }
  29000. _this._globalDiv.style.left = canvasRect.left + "px";
  29001. _this._globalDiv.style.top = canvasRect.top + "px";
  29002. _this._drawingCanvas.style.left = "0px";
  29003. _this._drawingCanvas.style.top = "0px";
  29004. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29005. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29006. var devicePixelRatio = window.devicePixelRatio || 1;
  29007. var context = _this._drawingContext;
  29008. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  29009. _this._ratio = devicePixelRatio / backingStoreRatio;
  29010. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29011. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29012. };
  29013. this._onCanvasClick = function (evt) {
  29014. _this._clickPosition = {
  29015. x: evt.clientX * _this._ratio,
  29016. y: evt.clientY * _this._ratio
  29017. };
  29018. };
  29019. this._syncUI = function () {
  29020. if (_this._showUI) {
  29021. if (_this._displayStatistics) {
  29022. _this._displayStats();
  29023. _this._statsDiv.style.display = "";
  29024. }
  29025. else {
  29026. _this._statsDiv.style.display = "none";
  29027. }
  29028. if (_this._displayLogs) {
  29029. _this._logDiv.style.display = "";
  29030. }
  29031. else {
  29032. _this._logDiv.style.display = "none";
  29033. }
  29034. if (_this._displayTree) {
  29035. _this._treeDiv.style.display = "";
  29036. if (_this._needToRefreshMeshesTree) {
  29037. _this._needToRefreshMeshesTree = false;
  29038. _this._refreshMeshesTreeContent();
  29039. }
  29040. }
  29041. else {
  29042. _this._treeDiv.style.display = "none";
  29043. }
  29044. }
  29045. };
  29046. this._syncData = function () {
  29047. if (_this._labelsEnabled || !_this._showUI) {
  29048. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29049. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29050. var engine = _this._scene.getEngine();
  29051. var viewport = _this._camera.viewport;
  29052. var globalViewport = viewport.toGlobal(engine);
  29053. // Meshes
  29054. var meshes = _this._camera.getActiveMeshes();
  29055. for (var index = 0; index < meshes.length; index++) {
  29056. var mesh = meshes.data[index];
  29057. var position = mesh.getBoundingInfo().boundingSphere.center;
  29058. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29059. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29060. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29061. }
  29062. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29063. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  29064. mesh.renderOverlay = !mesh.renderOverlay;
  29065. }, function () {
  29066. return mesh.renderOverlay ? 'red' : 'black';
  29067. });
  29068. }
  29069. }
  29070. // Cameras
  29071. var cameras = _this._scene.cameras;
  29072. for (index = 0; index < cameras.length; index++) {
  29073. var camera = cameras[index];
  29074. if (camera === _this._camera) {
  29075. continue;
  29076. }
  29077. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29078. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29079. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29080. _this._camera.detachControl(engine.getRenderingCanvas());
  29081. _this._camera = camera;
  29082. _this._camera.attachControl(engine.getRenderingCanvas());
  29083. }, function () {
  29084. return "purple";
  29085. });
  29086. }
  29087. }
  29088. // Lights
  29089. var lights = _this._scene.lights;
  29090. for (index = 0; index < lights.length; index++) {
  29091. var light = lights[index];
  29092. if (light.position) {
  29093. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29094. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29095. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29096. light.setEnabled(!light.isEnabled());
  29097. }, function () {
  29098. return light.isEnabled() ? "orange" : "gray";
  29099. });
  29100. }
  29101. }
  29102. }
  29103. }
  29104. _this._clickPosition = undefined;
  29105. };
  29106. }
  29107. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29108. while (this._treeSubsetDiv.hasChildNodes()) {
  29109. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29110. }
  29111. // Add meshes
  29112. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29113. sortedArray.sort(function (a, b) {
  29114. if (a.name === b.name) {
  29115. return 0;
  29116. }
  29117. return (a.name > b.name) ? 1 : -1;
  29118. });
  29119. for (var index = 0; index < sortedArray.length; index++) {
  29120. var mesh = sortedArray[index];
  29121. if (!mesh.isEnabled()) {
  29122. continue;
  29123. }
  29124. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29125. m.isVisible = element.checked;
  29126. }, mesh);
  29127. }
  29128. };
  29129. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29130. this._drawingContext.beginPath();
  29131. this._drawingContext.moveTo(zero.x, zero.y);
  29132. this._drawingContext.lineTo(unit.x, unit.y);
  29133. this._drawingContext.strokeStyle = color;
  29134. this._drawingContext.lineWidth = 4;
  29135. this._drawingContext.stroke();
  29136. this._drawingContext.font = "normal 14px Segoe UI";
  29137. this._drawingContext.fillStyle = color;
  29138. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29139. };
  29140. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29141. var position = mesh.getBoundingInfo().boundingSphere.center;
  29142. var worldMatrix = mesh.getWorldMatrix();
  29143. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29144. var unit = (unprojectedVector.subtract(position)).length();
  29145. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29146. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29147. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29148. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29149. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29150. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29151. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29152. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29153. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29154. };
  29155. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29156. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29157. this._drawingContext.font = "normal 12px Segoe UI";
  29158. var textMetrics = this._drawingContext.measureText(text);
  29159. var centerX = projectedPosition.x - textMetrics.width / 2;
  29160. var centerY = projectedPosition.y;
  29161. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29162. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29163. onClick();
  29164. }
  29165. this._drawingContext.beginPath();
  29166. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29167. this._drawingContext.fillStyle = getFillStyle();
  29168. this._drawingContext.globalAlpha = 0.5;
  29169. this._drawingContext.fill();
  29170. this._drawingContext.globalAlpha = 1.0;
  29171. this._drawingContext.strokeStyle = '#FFFFFF';
  29172. this._drawingContext.lineWidth = 1;
  29173. this._drawingContext.stroke();
  29174. this._drawingContext.fillStyle = "#FFFFFF";
  29175. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29176. this._drawingContext.beginPath();
  29177. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29178. this._drawingContext.fill();
  29179. }
  29180. };
  29181. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29182. if (!this._clickPosition) {
  29183. return false;
  29184. }
  29185. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29186. return false;
  29187. }
  29188. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29189. return false;
  29190. }
  29191. return true;
  29192. };
  29193. DebugLayer.prototype.isVisible = function () {
  29194. return this._enabled;
  29195. };
  29196. DebugLayer.prototype.hide = function () {
  29197. if (!this._enabled) {
  29198. return;
  29199. }
  29200. this._enabled = false;
  29201. var engine = this._scene.getEngine();
  29202. this._scene.unregisterBeforeRender(this._syncData);
  29203. this._scene.unregisterAfterRender(this._syncUI);
  29204. document.body.removeChild(this._globalDiv);
  29205. window.removeEventListener("resize", this._syncPositions);
  29206. this._scene.forceShowBoundingBoxes = false;
  29207. this._scene.forceWireframe = false;
  29208. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29209. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29210. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29211. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29212. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29213. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29214. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29215. this._scene.shadowsEnabled = true;
  29216. this._scene.particlesEnabled = true;
  29217. this._scene.postProcessesEnabled = true;
  29218. this._scene.collisionsEnabled = true;
  29219. this._scene.lightsEnabled = true;
  29220. this._scene.texturesEnabled = true;
  29221. this._scene.lensFlaresEnabled = true;
  29222. this._scene.proceduralTexturesEnabled = true;
  29223. this._scene.renderTargetsEnabled = true;
  29224. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29225. };
  29226. DebugLayer.prototype.show = function (showUI, camera) {
  29227. if (showUI === void 0) { showUI = true; }
  29228. if (camera === void 0) { camera = null; }
  29229. if (this._enabled) {
  29230. return;
  29231. }
  29232. this._enabled = true;
  29233. if (camera) {
  29234. this._camera = camera;
  29235. }
  29236. else {
  29237. this._camera = this._scene.activeCamera;
  29238. }
  29239. this._showUI = showUI;
  29240. var engine = this._scene.getEngine();
  29241. this._globalDiv = document.createElement("div");
  29242. document.body.appendChild(this._globalDiv);
  29243. this._generateDOMelements();
  29244. window.addEventListener("resize", this._syncPositions);
  29245. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29246. this._syncPositions();
  29247. this._scene.registerBeforeRender(this._syncData);
  29248. this._scene.registerAfterRender(this._syncUI);
  29249. };
  29250. DebugLayer.prototype._clearLabels = function () {
  29251. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29252. for (var index = 0; index < this._scene.meshes.length; index++) {
  29253. var mesh = this._scene.meshes[index];
  29254. mesh.renderOverlay = false;
  29255. }
  29256. };
  29257. DebugLayer.prototype._generateheader = function (root, text) {
  29258. var header = document.createElement("div");
  29259. header.innerHTML = text + "&nbsp;";
  29260. header.style.textAlign = "right";
  29261. header.style.width = "100%";
  29262. header.style.color = "white";
  29263. header.style.backgroundColor = "Black";
  29264. header.style.padding = "5px 5px 4px 0px";
  29265. header.style.marginLeft = "-5px";
  29266. header.style.fontWeight = "bold";
  29267. root.appendChild(header);
  29268. };
  29269. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29270. var label = document.createElement("label");
  29271. label.innerHTML = title;
  29272. label.style.color = color;
  29273. root.appendChild(label);
  29274. root.appendChild(document.createElement("br"));
  29275. };
  29276. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29277. if (tag === void 0) { tag = null; }
  29278. var label = document.createElement("label");
  29279. var boundingBoxesCheckbox = document.createElement("input");
  29280. boundingBoxesCheckbox.type = "checkbox";
  29281. boundingBoxesCheckbox.checked = initialState;
  29282. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29283. task(evt.target, tag);
  29284. });
  29285. label.appendChild(boundingBoxesCheckbox);
  29286. var container = document.createElement("span");
  29287. var leftPart = document.createElement("span");
  29288. var rightPart = document.createElement("span");
  29289. rightPart.style.cssFloat = "right";
  29290. leftPart.innerHTML = leftTitle;
  29291. rightPart.innerHTML = rightTitle;
  29292. rightPart.style.fontSize = "12px";
  29293. rightPart.style.maxWidth = "200px";
  29294. container.appendChild(leftPart);
  29295. container.appendChild(rightPart);
  29296. label.appendChild(container);
  29297. root.appendChild(label);
  29298. root.appendChild(document.createElement("br"));
  29299. };
  29300. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29301. if (tag === void 0) { tag = null; }
  29302. var label = document.createElement("label");
  29303. var checkBox = document.createElement("input");
  29304. checkBox.type = "checkbox";
  29305. checkBox.checked = initialState;
  29306. checkBox.addEventListener("change", function (evt) {
  29307. task(evt.target, tag);
  29308. });
  29309. label.appendChild(checkBox);
  29310. label.appendChild(document.createTextNode(title));
  29311. root.appendChild(label);
  29312. root.appendChild(document.createElement("br"));
  29313. };
  29314. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29315. if (tag === void 0) { tag = null; }
  29316. var button = document.createElement("button");
  29317. button.innerHTML = title;
  29318. button.style.height = "24px";
  29319. button.style.color = "#444444";
  29320. button.style.border = "1px solid white";
  29321. button.className = "debugLayerButton";
  29322. button.addEventListener("click", function (evt) {
  29323. task(evt.target, tag);
  29324. });
  29325. root.appendChild(button);
  29326. root.appendChild(document.createElement("br"));
  29327. };
  29328. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29329. if (tag === void 0) { tag = null; }
  29330. var label = document.createElement("label");
  29331. var boundingBoxesRadio = document.createElement("input");
  29332. boundingBoxesRadio.type = "radio";
  29333. boundingBoxesRadio.name = name;
  29334. boundingBoxesRadio.checked = initialState;
  29335. boundingBoxesRadio.addEventListener("change", function (evt) {
  29336. task(evt.target, tag);
  29337. });
  29338. label.appendChild(boundingBoxesRadio);
  29339. label.appendChild(document.createTextNode(title));
  29340. root.appendChild(label);
  29341. root.appendChild(document.createElement("br"));
  29342. };
  29343. DebugLayer.prototype._generateDOMelements = function () {
  29344. var _this = this;
  29345. this._globalDiv.id = "DebugLayer";
  29346. this._globalDiv.style.position = "absolute";
  29347. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29348. this._globalDiv.style.fontSize = "14px";
  29349. this._globalDiv.style.color = "white";
  29350. // Drawing canvas
  29351. this._drawingCanvas = document.createElement("canvas");
  29352. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29353. this._drawingCanvas.style.position = "absolute";
  29354. this._drawingCanvas.style.pointerEvents = "none";
  29355. this._drawingContext = this._drawingCanvas.getContext("2d");
  29356. this._globalDiv.appendChild(this._drawingCanvas);
  29357. if (this._showUI) {
  29358. var background = "rgba(128, 128, 128, 0.4)";
  29359. var border = "rgb(180, 180, 180) solid 1px";
  29360. // Stats
  29361. this._statsDiv = document.createElement("div");
  29362. this._statsDiv.id = "DebugLayerStats";
  29363. this._statsDiv.style.border = border;
  29364. this._statsDiv.style.position = "absolute";
  29365. this._statsDiv.style.background = background;
  29366. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29367. this._generateheader(this._statsDiv, "STATISTICS");
  29368. this._statsSubsetDiv = document.createElement("div");
  29369. this._statsSubsetDiv.style.paddingTop = "5px";
  29370. this._statsSubsetDiv.style.paddingBottom = "5px";
  29371. this._statsSubsetDiv.style.overflowY = "auto";
  29372. this._statsDiv.appendChild(this._statsSubsetDiv);
  29373. // Tree
  29374. this._treeDiv = document.createElement("div");
  29375. this._treeDiv.id = "DebugLayerTree";
  29376. this._treeDiv.style.border = border;
  29377. this._treeDiv.style.position = "absolute";
  29378. this._treeDiv.style.background = background;
  29379. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29380. this._treeDiv.style.display = "none";
  29381. this._generateheader(this._treeDiv, "MESHES TREE");
  29382. this._treeSubsetDiv = document.createElement("div");
  29383. this._treeSubsetDiv.style.paddingTop = "5px";
  29384. this._treeSubsetDiv.style.paddingRight = "5px";
  29385. this._treeSubsetDiv.style.overflowY = "auto";
  29386. this._treeSubsetDiv.style.maxHeight = "300px";
  29387. this._treeDiv.appendChild(this._treeSubsetDiv);
  29388. this._needToRefreshMeshesTree = true;
  29389. // Logs
  29390. this._logDiv = document.createElement("div");
  29391. this._logDiv.style.border = border;
  29392. this._logDiv.id = "DebugLayerLogs";
  29393. this._logDiv.style.position = "absolute";
  29394. this._logDiv.style.background = background;
  29395. this._logDiv.style.padding = "0px 0px 0px 5px";
  29396. this._logDiv.style.display = "none";
  29397. this._generateheader(this._logDiv, "LOGS");
  29398. this._logSubsetDiv = document.createElement("div");
  29399. this._logSubsetDiv.style.height = "127px";
  29400. this._logSubsetDiv.style.paddingTop = "5px";
  29401. this._logSubsetDiv.style.overflowY = "auto";
  29402. this._logSubsetDiv.style.fontSize = "12px";
  29403. this._logSubsetDiv.style.fontFamily = "consolas";
  29404. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29405. this._logDiv.appendChild(this._logSubsetDiv);
  29406. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29407. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29408. };
  29409. // Options
  29410. this._optionsDiv = document.createElement("div");
  29411. this._optionsDiv.id = "DebugLayerOptions";
  29412. this._optionsDiv.style.border = border;
  29413. this._optionsDiv.style.position = "absolute";
  29414. this._optionsDiv.style.background = background;
  29415. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29416. this._optionsDiv.style.overflowY = "auto";
  29417. this._generateheader(this._optionsDiv, "OPTIONS");
  29418. this._optionsSubsetDiv = document.createElement("div");
  29419. this._optionsSubsetDiv.style.paddingTop = "5px";
  29420. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29421. this._optionsSubsetDiv.style.overflowY = "auto";
  29422. this._optionsSubsetDiv.style.maxHeight = "200px";
  29423. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29424. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29425. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  29426. _this._displayStatistics = element.checked;
  29427. });
  29428. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  29429. _this._displayLogs = element.checked;
  29430. });
  29431. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29432. _this._displayTree = element.checked;
  29433. _this._needToRefreshMeshesTree = true;
  29434. });
  29435. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29436. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29437. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  29438. _this._scene.forceShowBoundingBoxes = element.checked;
  29439. });
  29440. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29441. _this._labelsEnabled = element.checked;
  29442. if (!_this._labelsEnabled) {
  29443. _this._clearLabels();
  29444. }
  29445. });
  29446. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29447. if (element.checked) {
  29448. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29449. }
  29450. else {
  29451. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29452. }
  29453. });
  29454. ;
  29455. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29456. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29457. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29458. if (element.checked) {
  29459. _this._scene.forceWireframe = false;
  29460. _this._scene.forcePointsCloud = false;
  29461. }
  29462. });
  29463. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29464. if (element.checked) {
  29465. _this._scene.forceWireframe = true;
  29466. _this._scene.forcePointsCloud = false;
  29467. }
  29468. });
  29469. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29470. if (element.checked) {
  29471. _this._scene.forceWireframe = false;
  29472. _this._scene.forcePointsCloud = true;
  29473. }
  29474. });
  29475. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29476. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29477. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  29478. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  29479. });
  29480. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  29481. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  29482. });
  29483. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  29484. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  29485. });
  29486. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  29487. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  29488. });
  29489. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  29490. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  29491. });
  29492. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  29493. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  29494. });
  29495. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  29496. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  29497. });
  29498. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  29499. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  29500. });
  29501. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29502. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29503. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  29504. _this._scene.animationsEnabled = element.checked;
  29505. });
  29506. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  29507. _this._scene.collisionsEnabled = element.checked;
  29508. });
  29509. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  29510. _this._scene.fogEnabled = element.checked;
  29511. });
  29512. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  29513. _this._scene.lensFlaresEnabled = element.checked;
  29514. });
  29515. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  29516. _this._scene.lightsEnabled = element.checked;
  29517. });
  29518. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  29519. _this._scene.particlesEnabled = element.checked;
  29520. });
  29521. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  29522. _this._scene.postProcessesEnabled = element.checked;
  29523. });
  29524. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  29525. _this._scene.proceduralTexturesEnabled = element.checked;
  29526. });
  29527. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  29528. _this._scene.renderTargetsEnabled = element.checked;
  29529. });
  29530. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  29531. _this._scene.shadowsEnabled = element.checked;
  29532. });
  29533. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  29534. _this._scene.skeletonsEnabled = element.checked;
  29535. });
  29536. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  29537. _this._scene.spritesEnabled = element.checked;
  29538. });
  29539. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  29540. _this._scene.texturesEnabled = element.checked;
  29541. });
  29542. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29543. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29544. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29545. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29546. if (element.checked) {
  29547. _this._scene.headphone = true;
  29548. }
  29549. });
  29550. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29551. if (element.checked) {
  29552. _this._scene.headphone = false;
  29553. }
  29554. });
  29555. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29556. _this._scene.audioEnabled = !element.checked;
  29557. });
  29558. }
  29559. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29560. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29561. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  29562. _this._scene.dumpNextRenderTargets = true;
  29563. });
  29564. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29565. this._globalDiv.appendChild(this._statsDiv);
  29566. this._globalDiv.appendChild(this._logDiv);
  29567. this._globalDiv.appendChild(this._optionsDiv);
  29568. this._globalDiv.appendChild(this._treeDiv);
  29569. }
  29570. };
  29571. DebugLayer.prototype._displayStats = function () {
  29572. var scene = this._scene;
  29573. var engine = scene.getEngine();
  29574. var glInfo = engine.getGlInfo();
  29575. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active indices: " + scene.getActiveIndices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  29576. if (this.customStatsFunction) {
  29577. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29578. }
  29579. };
  29580. return DebugLayer;
  29581. })();
  29582. BABYLON.DebugLayer = DebugLayer;
  29583. })(BABYLON || (BABYLON = {}));
  29584. //# sourceMappingURL=babylon.debugLayer.js.map
  29585. var __extends = this.__extends || function (d, b) {
  29586. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29587. function __() { this.constructor = d; }
  29588. __.prototype = b.prototype;
  29589. d.prototype = new __();
  29590. };
  29591. var BABYLON;
  29592. (function (BABYLON) {
  29593. var RawTexture = (function (_super) {
  29594. __extends(RawTexture, _super);
  29595. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29596. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29597. if (invertY === void 0) { invertY = false; }
  29598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29599. _super.call(this, null, scene, !generateMipMaps, invertY);
  29600. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29601. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29602. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29603. }
  29604. // Statics
  29605. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29606. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29607. if (invertY === void 0) { invertY = false; }
  29608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29609. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29610. };
  29611. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29612. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29613. if (invertY === void 0) { invertY = false; }
  29614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29615. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29616. };
  29617. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29618. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29619. if (invertY === void 0) { invertY = false; }
  29620. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29621. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29622. };
  29623. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29624. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29625. if (invertY === void 0) { invertY = false; }
  29626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29627. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29628. };
  29629. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29630. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29631. if (invertY === void 0) { invertY = false; }
  29632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29633. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29634. };
  29635. return RawTexture;
  29636. })(BABYLON.Texture);
  29637. BABYLON.RawTexture = RawTexture;
  29638. })(BABYLON || (BABYLON = {}));
  29639. //# sourceMappingURL=babylon.rawTexture.js.map
  29640. var __extends = this.__extends || function (d, b) {
  29641. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29642. function __() { this.constructor = d; }
  29643. __.prototype = b.prototype;
  29644. d.prototype = new __();
  29645. };
  29646. var BABYLON;
  29647. (function (BABYLON) {
  29648. var IndexedVector2 = (function (_super) {
  29649. __extends(IndexedVector2, _super);
  29650. function IndexedVector2(original, index) {
  29651. _super.call(this, original.x, original.y);
  29652. this.index = index;
  29653. }
  29654. return IndexedVector2;
  29655. })(BABYLON.Vector2);
  29656. var PolygonPoints = (function () {
  29657. function PolygonPoints() {
  29658. this.elements = new Array();
  29659. }
  29660. PolygonPoints.prototype.add = function (originalPoints) {
  29661. var _this = this;
  29662. var result = new Array();
  29663. originalPoints.forEach(function (point) {
  29664. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  29665. var newPoint = new IndexedVector2(point, _this.elements.length);
  29666. result.push(newPoint);
  29667. _this.elements.push(newPoint);
  29668. }
  29669. });
  29670. return result;
  29671. };
  29672. PolygonPoints.prototype.computeBounds = function () {
  29673. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29674. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29675. this.elements.forEach(function (point) {
  29676. // x
  29677. if (point.x < lmin.x) {
  29678. lmin.x = point.x;
  29679. }
  29680. else if (point.x > lmax.x) {
  29681. lmax.x = point.x;
  29682. }
  29683. // y
  29684. if (point.y < lmin.y) {
  29685. lmin.y = point.y;
  29686. }
  29687. else if (point.y > lmax.y) {
  29688. lmax.y = point.y;
  29689. }
  29690. });
  29691. return {
  29692. min: lmin,
  29693. max: lmax,
  29694. width: lmax.x - lmin.x,
  29695. height: lmax.y - lmin.y
  29696. };
  29697. };
  29698. return PolygonPoints;
  29699. })();
  29700. var Polygon = (function () {
  29701. function Polygon() {
  29702. }
  29703. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29704. return [
  29705. new BABYLON.Vector2(xmin, ymin),
  29706. new BABYLON.Vector2(xmax, ymin),
  29707. new BABYLON.Vector2(xmax, ymax),
  29708. new BABYLON.Vector2(xmin, ymax)
  29709. ];
  29710. };
  29711. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29712. if (cx === void 0) { cx = 0; }
  29713. if (cy === void 0) { cy = 0; }
  29714. if (numberOfSides === void 0) { numberOfSides = 32; }
  29715. var result = new Array();
  29716. var angle = 0;
  29717. var increment = (Math.PI * 2) / numberOfSides;
  29718. for (var i = 0; i < numberOfSides; i++) {
  29719. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29720. angle -= increment;
  29721. }
  29722. return result;
  29723. };
  29724. Polygon.Parse = function (input) {
  29725. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29726. var i, result = [];
  29727. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29728. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  29729. }
  29730. return result;
  29731. };
  29732. Polygon.StartingAt = function (x, y) {
  29733. return BABYLON.Path2.StartingAt(x, y);
  29734. };
  29735. return Polygon;
  29736. })();
  29737. BABYLON.Polygon = Polygon;
  29738. var PolygonMeshBuilder = (function () {
  29739. function PolygonMeshBuilder(name, contours, scene) {
  29740. this._points = new PolygonPoints();
  29741. if (!("poly2tri" in window)) {
  29742. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  29743. }
  29744. this._name = name;
  29745. this._scene = scene;
  29746. var points;
  29747. if (contours instanceof BABYLON.Path2) {
  29748. points = contours.getPoints();
  29749. }
  29750. else {
  29751. points = contours;
  29752. }
  29753. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  29754. }
  29755. PolygonMeshBuilder.prototype.addHole = function (hole) {
  29756. this._swctx.addHole(this._points.add(hole));
  29757. return this;
  29758. };
  29759. PolygonMeshBuilder.prototype.build = function (updatable) {
  29760. if (updatable === void 0) { updatable = false; }
  29761. var result = new BABYLON.Mesh(this._name, this._scene);
  29762. var normals = [];
  29763. var positions = [];
  29764. var uvs = [];
  29765. var bounds = this._points.computeBounds();
  29766. this._points.elements.forEach(function (p) {
  29767. normals.push(0, 1.0, 0);
  29768. positions.push(p.x, 0, p.y);
  29769. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  29770. });
  29771. var indices = [];
  29772. this._swctx.triangulate();
  29773. this._swctx.getTriangles().forEach(function (triangle) {
  29774. triangle.getPoints().forEach(function (point) {
  29775. indices.push(point.index);
  29776. });
  29777. });
  29778. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  29779. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  29780. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  29781. result.setIndices(indices);
  29782. return result;
  29783. };
  29784. return PolygonMeshBuilder;
  29785. })();
  29786. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  29787. })(BABYLON || (BABYLON = {}));
  29788. //# sourceMappingURL=babylon.polygonMesh.js.map
  29789. var BABYLON;
  29790. (function (BABYLON) {
  29791. var SimplificationSettings = (function () {
  29792. function SimplificationSettings(quality, distance, optimizeMesh) {
  29793. this.quality = quality;
  29794. this.distance = distance;
  29795. this.optimizeMesh = optimizeMesh;
  29796. }
  29797. return SimplificationSettings;
  29798. })();
  29799. BABYLON.SimplificationSettings = SimplificationSettings;
  29800. var SimplificationQueue = (function () {
  29801. function SimplificationQueue() {
  29802. this.running = false;
  29803. this._simplificationArray = [];
  29804. }
  29805. SimplificationQueue.prototype.addTask = function (task) {
  29806. this._simplificationArray.push(task);
  29807. };
  29808. SimplificationQueue.prototype.executeNext = function () {
  29809. var task = this._simplificationArray.pop();
  29810. if (task) {
  29811. this.running = true;
  29812. this.runSimplification(task);
  29813. }
  29814. else {
  29815. this.running = false;
  29816. }
  29817. };
  29818. SimplificationQueue.prototype.runSimplification = function (task) {
  29819. var _this = this;
  29820. if (task.parallelProcessing) {
  29821. //parallel simplifier
  29822. task.settings.forEach(function (setting) {
  29823. var simplifier = _this.getSimplifier(task);
  29824. simplifier.simplify(setting, function (newMesh) {
  29825. task.mesh.addLODLevel(setting.distance, newMesh);
  29826. newMesh.isVisible = true;
  29827. //check if it is the last
  29828. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29829. //all done, run the success callback.
  29830. task.successCallback();
  29831. }
  29832. _this.executeNext();
  29833. });
  29834. });
  29835. }
  29836. else {
  29837. //single simplifier.
  29838. var simplifier = this.getSimplifier(task);
  29839. var runDecimation = function (setting, callback) {
  29840. simplifier.simplify(setting, function (newMesh) {
  29841. task.mesh.addLODLevel(setting.distance, newMesh);
  29842. newMesh.isVisible = true;
  29843. //run the next quality level
  29844. callback();
  29845. });
  29846. };
  29847. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29848. runDecimation(task.settings[loop.index], function () {
  29849. loop.executeNext();
  29850. });
  29851. }, function () {
  29852. //execution ended, run the success callback.
  29853. if (task.successCallback) {
  29854. task.successCallback();
  29855. }
  29856. _this.executeNext();
  29857. });
  29858. }
  29859. };
  29860. SimplificationQueue.prototype.getSimplifier = function (task) {
  29861. switch (task.simplificationType) {
  29862. case 0 /* QUADRATIC */:
  29863. default:
  29864. return new QuadraticErrorSimplification(task.mesh);
  29865. }
  29866. };
  29867. return SimplificationQueue;
  29868. })();
  29869. BABYLON.SimplificationQueue = SimplificationQueue;
  29870. /**
  29871. * The implemented types of simplification.
  29872. * At the moment only Quadratic Error Decimation is implemented.
  29873. */
  29874. (function (SimplificationType) {
  29875. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29876. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29877. var SimplificationType = BABYLON.SimplificationType;
  29878. var DecimationTriangle = (function () {
  29879. function DecimationTriangle(vertices) {
  29880. this.vertices = vertices;
  29881. this.error = new Array(4);
  29882. this.deleted = false;
  29883. this.isDirty = false;
  29884. this.deletePending = false;
  29885. this.borderFactor = 0;
  29886. }
  29887. return DecimationTriangle;
  29888. })();
  29889. BABYLON.DecimationTriangle = DecimationTriangle;
  29890. var DecimationVertex = (function () {
  29891. function DecimationVertex(position, id) {
  29892. this.position = position;
  29893. this.id = id;
  29894. this.isBorder = true;
  29895. this.q = new QuadraticMatrix();
  29896. this.triangleCount = 0;
  29897. this.triangleStart = 0;
  29898. this.originalOffsets = [];
  29899. }
  29900. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29901. this.position.copyFrom(newPosition);
  29902. };
  29903. return DecimationVertex;
  29904. })();
  29905. BABYLON.DecimationVertex = DecimationVertex;
  29906. var QuadraticMatrix = (function () {
  29907. function QuadraticMatrix(data) {
  29908. this.data = new Array(10);
  29909. for (var i = 0; i < 10; ++i) {
  29910. if (data && data[i]) {
  29911. this.data[i] = data[i];
  29912. }
  29913. else {
  29914. this.data[i] = 0;
  29915. }
  29916. }
  29917. }
  29918. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29919. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29920. return det;
  29921. };
  29922. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29923. for (var i = 0; i < 10; ++i) {
  29924. this.data[i] += matrix.data[i];
  29925. }
  29926. };
  29927. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29928. for (var i = 0; i < 10; ++i) {
  29929. this.data[i] += data[i];
  29930. }
  29931. };
  29932. QuadraticMatrix.prototype.add = function (matrix) {
  29933. var m = new QuadraticMatrix();
  29934. for (var i = 0; i < 10; ++i) {
  29935. m.data[i] = this.data[i] + matrix.data[i];
  29936. }
  29937. return m;
  29938. };
  29939. QuadraticMatrix.FromData = function (a, b, c, d) {
  29940. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29941. };
  29942. //returning an array to avoid garbage collection
  29943. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29944. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29945. };
  29946. return QuadraticMatrix;
  29947. })();
  29948. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29949. var Reference = (function () {
  29950. function Reference(vertexId, triangleId) {
  29951. this.vertexId = vertexId;
  29952. this.triangleId = triangleId;
  29953. }
  29954. return Reference;
  29955. })();
  29956. BABYLON.Reference = Reference;
  29957. /**
  29958. * An implementation of the Quadratic Error simplification algorithm.
  29959. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29960. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29961. * @author RaananW
  29962. */
  29963. var QuadraticErrorSimplification = (function () {
  29964. function QuadraticErrorSimplification(_mesh) {
  29965. this._mesh = _mesh;
  29966. this.initialized = false;
  29967. this.syncIterations = 5000;
  29968. this.aggressiveness = 7;
  29969. this.decimationIterations = 100;
  29970. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29971. }
  29972. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29973. var _this = this;
  29974. this.initDecimatedMesh();
  29975. //iterating through the submeshes array, one after the other.
  29976. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29977. _this.initWithMesh(loop.index, function () {
  29978. _this.runDecimation(settings, loop.index, function () {
  29979. loop.executeNext();
  29980. });
  29981. }, settings.optimizeMesh);
  29982. }, function () {
  29983. setTimeout(function () {
  29984. successCallback(_this._reconstructedMesh);
  29985. }, 0);
  29986. });
  29987. };
  29988. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29989. var _this = this;
  29990. var gCount = 0;
  29991. triangle.vertices.forEach(function (vertex) {
  29992. var count = 0;
  29993. var vPos = vertex.position;
  29994. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29995. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29996. ++count;
  29997. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  29998. ++count;
  29999. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30000. ++count;
  30001. if (count > 1) {
  30002. ++gCount;
  30003. }
  30004. ;
  30005. });
  30006. if (gCount > 1) {
  30007. console.log(triangle, gCount);
  30008. }
  30009. return gCount > 1;
  30010. };
  30011. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30012. var _this = this;
  30013. var targetCount = ~~(this.triangles.length * settings.quality);
  30014. var deletedTriangles = 0;
  30015. var triangleCount = this.triangles.length;
  30016. var iterationFunction = function (iteration, callback) {
  30017. setTimeout(function () {
  30018. if (iteration % 5 === 0) {
  30019. _this.updateMesh(iteration === 0);
  30020. }
  30021. for (var i = 0; i < _this.triangles.length; ++i) {
  30022. _this.triangles[i].isDirty = false;
  30023. }
  30024. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30025. var trianglesIterator = function (i) {
  30026. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30027. var t = _this.triangles[tIdx];
  30028. if (!t)
  30029. return;
  30030. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30031. return;
  30032. }
  30033. for (var j = 0; j < 3; ++j) {
  30034. if (t.error[j] < threshold) {
  30035. var deleted0 = [];
  30036. var deleted1 = [];
  30037. var v0 = t.vertices[j];
  30038. var v1 = t.vertices[(j + 1) % 3];
  30039. if (v0.isBorder !== v1.isBorder)
  30040. continue;
  30041. var p = BABYLON.Vector3.Zero();
  30042. var n = BABYLON.Vector3.Zero();
  30043. var uv = BABYLON.Vector2.Zero();
  30044. var color = new BABYLON.Color4(0, 0, 0, 1);
  30045. _this.calculateError(v0, v1, p, n, uv, color);
  30046. var delTr = [];
  30047. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30048. continue;
  30049. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30050. continue;
  30051. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30052. continue;
  30053. var uniqueArray = [];
  30054. delTr.forEach(function (deletedT) {
  30055. if (uniqueArray.indexOf(deletedT) === -1) {
  30056. deletedT.deletePending = true;
  30057. uniqueArray.push(deletedT);
  30058. }
  30059. });
  30060. if (uniqueArray.length % 2 != 0) {
  30061. continue;
  30062. }
  30063. v0.q = v1.q.add(v0.q);
  30064. v0.updatePosition(p);
  30065. var tStart = _this.references.length;
  30066. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30067. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30068. var tCount = _this.references.length - tStart;
  30069. if (tCount <= v0.triangleCount) {
  30070. if (tCount) {
  30071. for (var c = 0; c < tCount; c++) {
  30072. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30073. }
  30074. }
  30075. }
  30076. else {
  30077. v0.triangleStart = tStart;
  30078. }
  30079. v0.triangleCount = tCount;
  30080. break;
  30081. }
  30082. }
  30083. };
  30084. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  30085. return (triangleCount - deletedTriangles <= targetCount);
  30086. });
  30087. }, 0);
  30088. };
  30089. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30090. if (triangleCount - deletedTriangles <= targetCount)
  30091. loop.breakLoop();
  30092. else {
  30093. iterationFunction(loop.index, function () {
  30094. loop.executeNext();
  30095. });
  30096. }
  30097. }, function () {
  30098. setTimeout(function () {
  30099. //reconstruct this part of the mesh
  30100. _this.reconstructMesh(submeshIndex);
  30101. successCallback();
  30102. }, 0);
  30103. });
  30104. };
  30105. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30106. var _this = this;
  30107. this.vertices = [];
  30108. this.triangles = [];
  30109. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30110. var indices = this._mesh.getIndices();
  30111. var submesh = this._mesh.subMeshes[submeshIndex];
  30112. var findInVertices = function (positionToSearch) {
  30113. if (optimizeMesh) {
  30114. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30115. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30116. return _this.vertices[ii];
  30117. }
  30118. }
  30119. }
  30120. return null;
  30121. };
  30122. var vertexReferences = [];
  30123. var vertexInit = function (i) {
  30124. var offset = i + submesh.verticesStart;
  30125. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30126. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30127. vertex.originalOffsets.push(offset);
  30128. if (vertex.id == _this.vertices.length) {
  30129. _this.vertices.push(vertex);
  30130. }
  30131. vertexReferences.push(vertex.id);
  30132. };
  30133. //var totalVertices = mesh.getTotalVertices();
  30134. var totalVertices = submesh.verticesCount;
  30135. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30136. var indicesInit = function (i) {
  30137. var offset = (submesh.indexStart / 3) + i;
  30138. var pos = (offset * 3);
  30139. var i0 = indices[pos + 0];
  30140. var i1 = indices[pos + 1];
  30141. var i2 = indices[pos + 2];
  30142. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30143. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30144. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30145. var triangle = new DecimationTriangle([v0, v1, v2]);
  30146. triangle.originalOffset = pos;
  30147. _this.triangles.push(triangle);
  30148. };
  30149. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30150. _this.init(callback);
  30151. });
  30152. });
  30153. };
  30154. QuadraticErrorSimplification.prototype.init = function (callback) {
  30155. var _this = this;
  30156. var triangleInit1 = function (i) {
  30157. var t = _this.triangles[i];
  30158. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30159. for (var j = 0; j < 3; j++) {
  30160. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  30161. }
  30162. };
  30163. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30164. var triangleInit2 = function (i) {
  30165. var t = _this.triangles[i];
  30166. for (var j = 0; j < 3; ++j) {
  30167. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30168. }
  30169. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30170. };
  30171. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30172. _this.initialized = true;
  30173. callback();
  30174. });
  30175. });
  30176. };
  30177. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30178. var newTriangles = [];
  30179. var i;
  30180. for (i = 0; i < this.vertices.length; ++i) {
  30181. this.vertices[i].triangleCount = 0;
  30182. }
  30183. var t;
  30184. var j;
  30185. for (i = 0; i < this.triangles.length; ++i) {
  30186. if (!this.triangles[i].deleted) {
  30187. t = this.triangles[i];
  30188. for (j = 0; j < 3; ++j) {
  30189. t.vertices[j].triangleCount = 1;
  30190. }
  30191. newTriangles.push(t);
  30192. }
  30193. }
  30194. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30195. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30196. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30197. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30198. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30199. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30200. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30201. var vertexCount = 0;
  30202. for (i = 0; i < this.vertices.length; ++i) {
  30203. var vertex = this.vertices[i];
  30204. vertex.id = vertexCount;
  30205. if (vertex.triangleCount) {
  30206. vertex.originalOffsets.forEach(function (originalOffset) {
  30207. newPositionData.push(vertex.position.x);
  30208. newPositionData.push(vertex.position.y);
  30209. newPositionData.push(vertex.position.z);
  30210. newNormalData.push(normalData[originalOffset * 3]);
  30211. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30212. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30213. if (uvs && uvs.length) {
  30214. newUVsData.push(uvs[(originalOffset * 2)]);
  30215. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30216. }
  30217. else if (colorsData && colorsData.length) {
  30218. newColorsData.push(colorsData[(originalOffset * 4)]);
  30219. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30220. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30221. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30222. }
  30223. ++vertexCount;
  30224. });
  30225. }
  30226. }
  30227. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30228. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30229. var submeshesArray = this._reconstructedMesh.subMeshes;
  30230. this._reconstructedMesh.subMeshes = [];
  30231. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30232. var originalIndices = this._mesh.getIndices();
  30233. for (i = 0; i < newTriangles.length; ++i) {
  30234. var t = newTriangles[i];
  30235. //now get the new referencing point for each vertex
  30236. [0, 1, 2].forEach(function (idx) {
  30237. var id = originalIndices[t.originalOffset + idx];
  30238. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30239. if (offset < 0)
  30240. offset = 0;
  30241. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30242. });
  30243. }
  30244. //overwriting the old vertex buffers and indices.
  30245. this._reconstructedMesh.setIndices(newIndicesArray);
  30246. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30247. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30248. if (newUVsData.length > 0)
  30249. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30250. if (newColorsData.length > 0)
  30251. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30252. //create submesh
  30253. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30254. if (submeshIndex > 0) {
  30255. this._reconstructedMesh.subMeshes = [];
  30256. submeshesArray.forEach(function (submesh) {
  30257. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30258. });
  30259. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30260. }
  30261. };
  30262. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30263. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30264. this._reconstructedMesh.material = this._mesh.material;
  30265. this._reconstructedMesh.parent = this._mesh.parent;
  30266. this._reconstructedMesh.isVisible = false;
  30267. };
  30268. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30269. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30270. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30271. if (t.deleted)
  30272. continue;
  30273. var s = this.references[vertex1.triangleStart + i].vertexId;
  30274. var v1 = t.vertices[(s + 1) % 3];
  30275. var v2 = t.vertices[(s + 2) % 3];
  30276. if ((v1 === vertex2 || v2 === vertex2)) {
  30277. deletedArray[i] = true;
  30278. delTr.push(t);
  30279. continue;
  30280. }
  30281. var d1 = v1.position.subtract(point);
  30282. d1 = d1.normalize();
  30283. var d2 = v2.position.subtract(point);
  30284. d2 = d2.normalize();
  30285. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30286. return true;
  30287. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30288. deletedArray[i] = false;
  30289. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30290. return true;
  30291. }
  30292. return false;
  30293. };
  30294. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30295. var newDeleted = deletedTriangles;
  30296. for (var i = 0; i < vertex.triangleCount; ++i) {
  30297. var ref = this.references[vertex.triangleStart + i];
  30298. var t = this.triangles[ref.triangleId];
  30299. if (t.deleted)
  30300. continue;
  30301. if (deletedArray[i] && t.deletePending) {
  30302. t.deleted = true;
  30303. newDeleted++;
  30304. continue;
  30305. }
  30306. t.vertices[ref.vertexId] = origVertex;
  30307. t.isDirty = true;
  30308. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30309. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30310. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30311. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30312. this.references.push(ref);
  30313. }
  30314. return newDeleted;
  30315. };
  30316. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30317. for (var i = 0; i < this.vertices.length; ++i) {
  30318. var vCount = [];
  30319. var vId = [];
  30320. var v = this.vertices[i];
  30321. var j;
  30322. for (j = 0; j < v.triangleCount; ++j) {
  30323. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30324. for (var ii = 0; ii < 3; ii++) {
  30325. var ofs = 0;
  30326. var vv = triangle.vertices[ii];
  30327. while (ofs < vCount.length) {
  30328. if (vId[ofs] === vv.id)
  30329. break;
  30330. ++ofs;
  30331. }
  30332. if (ofs === vCount.length) {
  30333. vCount.push(1);
  30334. vId.push(vv.id);
  30335. }
  30336. else {
  30337. vCount[ofs]++;
  30338. }
  30339. }
  30340. }
  30341. for (j = 0; j < vCount.length; ++j) {
  30342. if (vCount[j] === 1) {
  30343. this.vertices[vId[j]].isBorder = true;
  30344. }
  30345. else {
  30346. this.vertices[vId[j]].isBorder = false;
  30347. }
  30348. }
  30349. }
  30350. };
  30351. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30352. if (identifyBorders === void 0) { identifyBorders = false; }
  30353. var i;
  30354. if (!identifyBorders) {
  30355. var newTrianglesVector = [];
  30356. for (i = 0; i < this.triangles.length; ++i) {
  30357. if (!this.triangles[i].deleted) {
  30358. newTrianglesVector.push(this.triangles[i]);
  30359. }
  30360. }
  30361. this.triangles = newTrianglesVector;
  30362. }
  30363. for (i = 0; i < this.vertices.length; ++i) {
  30364. this.vertices[i].triangleCount = 0;
  30365. this.vertices[i].triangleStart = 0;
  30366. }
  30367. var t;
  30368. var j;
  30369. var v;
  30370. for (i = 0; i < this.triangles.length; ++i) {
  30371. t = this.triangles[i];
  30372. for (j = 0; j < 3; ++j) {
  30373. v = t.vertices[j];
  30374. v.triangleCount++;
  30375. }
  30376. }
  30377. var tStart = 0;
  30378. for (i = 0; i < this.vertices.length; ++i) {
  30379. this.vertices[i].triangleStart = tStart;
  30380. tStart += this.vertices[i].triangleCount;
  30381. this.vertices[i].triangleCount = 0;
  30382. }
  30383. var newReferences = new Array(this.triangles.length * 3);
  30384. for (i = 0; i < this.triangles.length; ++i) {
  30385. t = this.triangles[i];
  30386. for (j = 0; j < 3; ++j) {
  30387. v = t.vertices[j];
  30388. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30389. v.triangleCount++;
  30390. }
  30391. }
  30392. this.references = newReferences;
  30393. if (identifyBorders) {
  30394. this.identifyBorder();
  30395. }
  30396. };
  30397. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30398. var x = point.x;
  30399. var y = point.y;
  30400. var z = point.z;
  30401. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30402. };
  30403. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30404. var q = vertex1.q.add(vertex2.q);
  30405. var border = vertex1.isBorder && vertex2.isBorder;
  30406. var error = 0;
  30407. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30408. if (qDet !== 0 && !border) {
  30409. if (!pointResult) {
  30410. pointResult = BABYLON.Vector3.Zero();
  30411. }
  30412. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30413. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30414. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30415. error = this.vertexError(q, pointResult);
  30416. }
  30417. else {
  30418. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30419. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30420. var error1 = this.vertexError(q, vertex1.position);
  30421. var error2 = this.vertexError(q, vertex2.position);
  30422. var error3 = this.vertexError(q, p3);
  30423. error = Math.min(error1, error2, error3);
  30424. if (error === error1) {
  30425. if (pointResult) {
  30426. pointResult.copyFrom(vertex1.position);
  30427. }
  30428. }
  30429. else if (error === error2) {
  30430. if (pointResult) {
  30431. pointResult.copyFrom(vertex2.position);
  30432. }
  30433. }
  30434. else {
  30435. if (pointResult) {
  30436. pointResult.copyFrom(p3);
  30437. }
  30438. }
  30439. }
  30440. return error;
  30441. };
  30442. return QuadraticErrorSimplification;
  30443. })();
  30444. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30445. })(BABYLON || (BABYLON = {}));
  30446. //# sourceMappingURL=babylon.meshSimplification.js.map
  30447. var BABYLON;
  30448. (function (BABYLON) {
  30449. var Analyser = (function () {
  30450. function Analyser(scene) {
  30451. this.SMOOTHING = 0.75;
  30452. this.FFT_SIZE = 512;
  30453. this.BARGRAPHAMPLITUDE = 256;
  30454. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30455. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30456. this._scene = scene;
  30457. this._audioEngine = BABYLON.Engine.audioEngine;
  30458. if (this._audioEngine.canUseWebAudio) {
  30459. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30460. this._webAudioAnalyser.minDecibels = -140;
  30461. this._webAudioAnalyser.maxDecibels = 0;
  30462. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30463. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30464. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30465. }
  30466. }
  30467. Analyser.prototype.getFrequencyBinCount = function () {
  30468. if (this._audioEngine.canUseWebAudio) {
  30469. return this._webAudioAnalyser.frequencyBinCount;
  30470. }
  30471. else {
  30472. return 0;
  30473. }
  30474. };
  30475. Analyser.prototype.getByteFrequencyData = function () {
  30476. if (this._audioEngine.canUseWebAudio) {
  30477. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30478. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30479. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30480. }
  30481. return this._byteFreqs;
  30482. };
  30483. Analyser.prototype.getByteTimeDomainData = function () {
  30484. if (this._audioEngine.canUseWebAudio) {
  30485. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30486. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30487. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30488. }
  30489. return this._byteTime;
  30490. };
  30491. Analyser.prototype.getFloatFrequencyData = function () {
  30492. if (this._audioEngine.canUseWebAudio) {
  30493. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30494. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30495. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30496. }
  30497. return this._floatFreqs;
  30498. };
  30499. Analyser.prototype.drawDebugCanvas = function () {
  30500. var _this = this;
  30501. if (this._audioEngine.canUseWebAudio) {
  30502. if (!this._debugCanvas) {
  30503. this._debugCanvas = document.createElement("canvas");
  30504. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30505. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30506. this._debugCanvas.style.position = "absolute";
  30507. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30508. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30509. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30510. document.body.appendChild(this._debugCanvas);
  30511. this._registerFunc = function () {
  30512. _this.drawDebugCanvas();
  30513. };
  30514. this._scene.registerBeforeRender(this._registerFunc);
  30515. }
  30516. if (this._registerFunc) {
  30517. var workingArray = this.getByteFrequencyData();
  30518. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30519. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30520. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30521. var value = workingArray[i];
  30522. var percent = value / this.BARGRAPHAMPLITUDE;
  30523. var height = this.DEBUGCANVASSIZE.height * percent;
  30524. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30525. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30526. var hue = i / this.getFrequencyBinCount() * 360;
  30527. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30528. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30529. }
  30530. }
  30531. }
  30532. };
  30533. Analyser.prototype.stopDebugCanvas = function () {
  30534. if (this._debugCanvas) {
  30535. this._scene.unregisterBeforeRender(this._registerFunc);
  30536. this._registerFunc = null;
  30537. document.body.removeChild(this._debugCanvas);
  30538. this._debugCanvas = null;
  30539. this._debugCanvasContext = null;
  30540. }
  30541. };
  30542. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30543. if (this._audioEngine.canUseWebAudio) {
  30544. inputAudioNode.connect(this._webAudioAnalyser);
  30545. this._webAudioAnalyser.connect(outputAudioNode);
  30546. }
  30547. };
  30548. Analyser.prototype.dispose = function () {
  30549. if (this._audioEngine.canUseWebAudio) {
  30550. this._webAudioAnalyser.disconnect();
  30551. }
  30552. };
  30553. return Analyser;
  30554. })();
  30555. BABYLON.Analyser = Analyser;
  30556. })(BABYLON || (BABYLON = {}));
  30557. //# sourceMappingURL=babylon.analyser.js.map
  30558. var BABYLON;
  30559. (function (BABYLON) {
  30560. var DepthRenderer = (function () {
  30561. function DepthRenderer(scene, type) {
  30562. var _this = this;
  30563. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30564. this._viewMatrix = BABYLON.Matrix.Zero();
  30565. this._projectionMatrix = BABYLON.Matrix.Zero();
  30566. this._transformMatrix = BABYLON.Matrix.Zero();
  30567. this._worldViewProjection = BABYLON.Matrix.Zero();
  30568. this._scene = scene;
  30569. var engine = scene.getEngine();
  30570. // Render target
  30571. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30572. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30573. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30574. this._depthMap.refreshRate = 1;
  30575. this._depthMap.renderParticles = false;
  30576. this._depthMap.renderList = null;
  30577. // set default depth value to 1.0 (far away)
  30578. this._depthMap.onClear = function (engine) {
  30579. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30580. };
  30581. // Custom render function
  30582. var renderSubMesh = function (subMesh) {
  30583. var mesh = subMesh.getRenderingMesh();
  30584. var scene = _this._scene;
  30585. var engine = scene.getEngine();
  30586. // Culling
  30587. engine.setState(subMesh.getMaterial().backFaceCulling);
  30588. // Managing instances
  30589. var batch = mesh._getInstancesRenderList(subMesh._id);
  30590. if (batch.mustReturn) {
  30591. return;
  30592. }
  30593. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30594. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30595. engine.enableEffect(_this._effect);
  30596. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30597. var material = subMesh.getMaterial();
  30598. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30599. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30600. // Alpha test
  30601. if (material && material.needAlphaTesting()) {
  30602. var alphaTexture = material.getAlphaTestTexture();
  30603. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30604. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30605. }
  30606. // Bones
  30607. if (mesh.useBones) {
  30608. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30609. }
  30610. // Draw
  30611. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30612. }
  30613. };
  30614. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30615. var index;
  30616. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30617. renderSubMesh(opaqueSubMeshes.data[index]);
  30618. }
  30619. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30620. renderSubMesh(alphaTestSubMeshes.data[index]);
  30621. }
  30622. };
  30623. }
  30624. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30625. var defines = [];
  30626. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30627. var mesh = subMesh.getMesh();
  30628. var scene = mesh.getScene();
  30629. var material = subMesh.getMaterial();
  30630. // Alpha test
  30631. if (material && material.needAlphaTesting()) {
  30632. defines.push("#define ALPHATEST");
  30633. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30634. attribs.push(BABYLON.VertexBuffer.UVKind);
  30635. defines.push("#define UV1");
  30636. }
  30637. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30638. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30639. defines.push("#define UV2");
  30640. }
  30641. }
  30642. // Bones
  30643. if (mesh.useBones) {
  30644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30646. defines.push("#define BONES");
  30647. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30648. }
  30649. // Instances
  30650. if (useInstances) {
  30651. defines.push("#define INSTANCES");
  30652. attribs.push("world0");
  30653. attribs.push("world1");
  30654. attribs.push("world2");
  30655. attribs.push("world3");
  30656. }
  30657. // Get correct effect
  30658. var join = defines.join("\n");
  30659. if (this._cachedDefines !== join) {
  30660. this._cachedDefines = join;
  30661. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  30662. }
  30663. return this._effect.isReady();
  30664. };
  30665. DepthRenderer.prototype.getDepthMap = function () {
  30666. return this._depthMap;
  30667. };
  30668. // Methods
  30669. DepthRenderer.prototype.dispose = function () {
  30670. this._depthMap.dispose();
  30671. };
  30672. return DepthRenderer;
  30673. })();
  30674. BABYLON.DepthRenderer = DepthRenderer;
  30675. })(BABYLON || (BABYLON = {}));
  30676. //# sourceMappingURL=babylon.depthRenderer.js.map
  30677. var __extends = this.__extends || function (d, b) {
  30678. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30679. function __() { this.constructor = d; }
  30680. __.prototype = b.prototype;
  30681. d.prototype = new __();
  30682. };
  30683. var BABYLON;
  30684. (function (BABYLON) {
  30685. var SSAORenderingPipeline = (function (_super) {
  30686. __extends(SSAORenderingPipeline, _super);
  30687. /**
  30688. * @constructor
  30689. * @param {string} name - The rendering pipeline name
  30690. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30691. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  30692. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30693. */
  30694. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  30695. var _this = this;
  30696. _super.call(this, scene.getEngine(), name);
  30697. // Members
  30698. /**
  30699. * The PassPostProcess id in the pipeline that contains the original scene color
  30700. * @type {string}
  30701. */
  30702. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  30703. /**
  30704. * The SSAO PostProcess id in the pipeline
  30705. * @type {string}
  30706. */
  30707. this.SSAORenderEffect = "SSAORenderEffect";
  30708. /**
  30709. * The horizontal blur PostProcess id in the pipeline
  30710. * @type {string}
  30711. */
  30712. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  30713. /**
  30714. * The vertical blur PostProcess id in the pipeline
  30715. * @type {string}
  30716. */
  30717. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  30718. /**
  30719. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  30720. * @type {string}
  30721. */
  30722. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  30723. /**
  30724. * The output strength of the SSAO post-process. Default value is 1.0.
  30725. * @type {number}
  30726. */
  30727. this.totalStrength = 1.0;
  30728. /**
  30729. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  30730. * @type {number}
  30731. */
  30732. this.radius = 0.0002;
  30733. /**
  30734. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  30735. * Must not be equal to fallOff and superior to fallOff.
  30736. * Default value is 0.0075
  30737. * @type {number}
  30738. */
  30739. this.area = 0.0075;
  30740. /**
  30741. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  30742. * Must not be equal to area and inferior to area.
  30743. * Default value is 0.0002
  30744. * @type {number}
  30745. */
  30746. this.fallOff = 0.0002;
  30747. this._firstUpdate = true;
  30748. this._scene = scene;
  30749. // Set up assets
  30750. this._createRandomTexture();
  30751. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30752. var ssaoRatio = ratio.ssaoRatio || ratio;
  30753. var combineRatio = ratio.combineRatio || ratio;
  30754. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30755. this._createSSAOPostProcess(ssaoRatio);
  30756. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30757. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30758. this._createSSAOCombinePostProcess(combineRatio);
  30759. // Set up pipeline
  30760. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  30761. return _this._originalColorPostProcess;
  30762. }, true));
  30763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  30764. return _this._ssaoPostProcess;
  30765. }, true));
  30766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  30767. return _this._blurHPostProcess;
  30768. }, true));
  30769. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  30770. return _this._blurVPostProcess;
  30771. }, true));
  30772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  30773. return _this._ssaoCombinePostProcess;
  30774. }, true));
  30775. // Finish
  30776. scene.postProcessRenderPipelineManager.addPipeline(this);
  30777. if (cameras)
  30778. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30779. }
  30780. // Public Methods
  30781. /**
  30782. * Returns the horizontal blur PostProcess
  30783. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  30784. */
  30785. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  30786. return this._blurHPostProcess;
  30787. };
  30788. /**
  30789. * Returns the vertical blur PostProcess
  30790. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  30791. */
  30792. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  30793. return this._blurVPostProcess;
  30794. };
  30795. /**
  30796. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  30797. */
  30798. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30799. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30800. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30801. this._originalColorPostProcess = undefined;
  30802. this._ssaoPostProcess = undefined;
  30803. this._blurHPostProcess = undefined;
  30804. this._blurVPostProcess = undefined;
  30805. this._ssaoCombinePostProcess = undefined;
  30806. this._randomTexture.dispose();
  30807. if (disableDepthRender)
  30808. this._scene.disableDepthRenderer();
  30809. };
  30810. // Private Methods
  30811. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  30812. var _this = this;
  30813. var sampleSphere = [
  30814. 0.5381,
  30815. 0.1856,
  30816. -0.4319,
  30817. 0.1379,
  30818. 0.2486,
  30819. 0.4430,
  30820. 0.3371,
  30821. 0.5679,
  30822. -0.0057,
  30823. -0.6999,
  30824. -0.0451,
  30825. -0.0019,
  30826. 0.0689,
  30827. -0.1598,
  30828. -0.8547,
  30829. 0.0560,
  30830. 0.0069,
  30831. -0.1843,
  30832. -0.0146,
  30833. 0.1402,
  30834. 0.0762,
  30835. 0.0100,
  30836. -0.1924,
  30837. -0.0344,
  30838. -0.3577,
  30839. -0.5301,
  30840. -0.4358,
  30841. -0.3169,
  30842. 0.1063,
  30843. 0.0158,
  30844. 0.0103,
  30845. -0.5869,
  30846. 0.0046,
  30847. -0.0897,
  30848. -0.4940,
  30849. 0.3287,
  30850. 0.7119,
  30851. -0.0154,
  30852. -0.0918,
  30853. -0.0533,
  30854. 0.0596,
  30855. -0.5411,
  30856. 0.0352,
  30857. -0.0631,
  30858. 0.5460,
  30859. -0.4776,
  30860. 0.2847,
  30861. -0.0271
  30862. ];
  30863. var samplesFactor = 1.0 / 16.0;
  30864. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30865. this._ssaoPostProcess.onApply = function (effect) {
  30866. if (_this._firstUpdate) {
  30867. effect.setArray3("sampleSphere", sampleSphere);
  30868. effect.setFloat("samplesFactor", samplesFactor);
  30869. effect.setFloat("randTextureTiles", 4.0 / ratio);
  30870. _this._firstUpdate = false;
  30871. }
  30872. effect.setFloat("totalStrength", _this.totalStrength);
  30873. effect.setFloat("radius", _this.radius);
  30874. effect.setFloat("area", _this.area);
  30875. effect.setFloat("fallOff", _this.fallOff);
  30876. effect.setTexture("textureSampler", _this._depthTexture);
  30877. effect.setTexture("randomSampler", _this._randomTexture);
  30878. };
  30879. };
  30880. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  30881. var _this = this;
  30882. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30883. this._ssaoCombinePostProcess.onApply = function (effect) {
  30884. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  30885. };
  30886. };
  30887. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  30888. var size = 512;
  30889. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30890. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30891. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30892. var context = this._randomTexture.getContext();
  30893. var rand = function (min, max) {
  30894. return Math.random() * (max - min) + min;
  30895. };
  30896. for (var x = 0; x < size; x++) {
  30897. for (var y = 0; y < size; y++) {
  30898. var randVector = BABYLON.Vector3.Zero();
  30899. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  30900. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  30901. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  30902. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  30903. context.fillRect(x, y, 1, 1);
  30904. }
  30905. }
  30906. this._randomTexture.update(false);
  30907. };
  30908. return SSAORenderingPipeline;
  30909. })(BABYLON.PostProcessRenderPipeline);
  30910. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  30911. })(BABYLON || (BABYLON = {}));
  30912. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  30913. var __extends = this.__extends || function (d, b) {
  30914. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30915. function __() { this.constructor = d; }
  30916. __.prototype = b.prototype;
  30917. d.prototype = new __();
  30918. };
  30919. var BABYLON;
  30920. (function (BABYLON) {
  30921. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  30922. var VolumetricLightScatteringPostProcess = (function (_super) {
  30923. __extends(VolumetricLightScatteringPostProcess, _super);
  30924. /**
  30925. * @constructor
  30926. * @param {string} name - The post-process name
  30927. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  30928. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  30929. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  30930. * @param {number} samples - The post-process quality, default 100
  30931. * @param {number} samplingMode - The post-process filtering mode
  30932. * @param {BABYLON.Engine} engine - The babylon engine
  30933. * @param {boolean} reusable - If the post-process is reusable
  30934. */
  30935. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  30936. var _this = this;
  30937. if (samples === void 0) { samples = 100; }
  30938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  30939. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  30940. this._screenCoordinates = BABYLON.Vector2.Zero();
  30941. /**
  30942. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  30943. * @type {boolean}
  30944. */
  30945. this.useCustomMeshPosition = false;
  30946. /**
  30947. * If the post-process should inverse the light scattering direction
  30948. * @type {boolean}
  30949. */
  30950. this.invert = true;
  30951. /**
  30952. * Array containing the excluded meshes not rendered in the internal pass
  30953. */
  30954. this.excludedMeshes = new Array();
  30955. this.exposure = 0.3;
  30956. this.decay = 0.96815;
  30957. this.weight = 0.58767;
  30958. this.density = 0.926;
  30959. var scene = camera.getScene();
  30960. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  30961. // Configure mesh
  30962. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  30963. // Configure
  30964. this._createPass(scene, ratio.passRatio || ratio);
  30965. this.onApply = function (effect) {
  30966. _this._updateMeshScreenCoordinates(scene);
  30967. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  30968. effect.setFloat("exposure", _this.exposure);
  30969. effect.setFloat("decay", _this.decay);
  30970. effect.setFloat("weight", _this.weight);
  30971. effect.setFloat("density", _this.density);
  30972. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  30973. };
  30974. }
  30975. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  30976. var mesh = subMesh.getMesh();
  30977. var defines = [];
  30978. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30979. var material = subMesh.getMaterial();
  30980. var needUV = false;
  30981. // Render this.mesh as default
  30982. if (mesh === this.mesh) {
  30983. defines.push("#define BASIC_RENDER");
  30984. defines.push("#define NEED_UV");
  30985. needUV = true;
  30986. }
  30987. // Alpha test
  30988. if (material) {
  30989. if (material.needAlphaTesting() || mesh === this.mesh)
  30990. defines.push("#define ALPHATEST");
  30991. if (material.opacityTexture !== undefined) {
  30992. defines.push("#define OPACITY");
  30993. if (material.opacityTexture.getAlphaFromRGB)
  30994. defines.push("#define OPACITYRGB");
  30995. if (!needUV)
  30996. defines.push("#define NEED_UV");
  30997. }
  30998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30999. attribs.push(BABYLON.VertexBuffer.UVKind);
  31000. defines.push("#define UV1");
  31001. }
  31002. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31003. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31004. defines.push("#define UV2");
  31005. }
  31006. }
  31007. // Bones
  31008. if (mesh.useBones) {
  31009. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31010. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31011. defines.push("#define BONES");
  31012. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31013. }
  31014. // Instances
  31015. if (useInstances) {
  31016. defines.push("#define INSTANCES");
  31017. attribs.push("world0");
  31018. attribs.push("world1");
  31019. attribs.push("world2");
  31020. attribs.push("world3");
  31021. }
  31022. // Get correct effect
  31023. var join = defines.join("\n");
  31024. if (this._cachedDefines !== join) {
  31025. this._cachedDefines = join;
  31026. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31027. }
  31028. return this._volumetricLightScatteringPass.isReady();
  31029. };
  31030. /**
  31031. * Sets the new light position for light scattering effect
  31032. * @param {BABYLON.Vector3} The new custom light position
  31033. */
  31034. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31035. this._customMeshPosition = position;
  31036. };
  31037. /**
  31038. * Returns the light position for light scattering effect
  31039. * @return {BABYLON.Vector3} The custom light position
  31040. */
  31041. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31042. return this._customMeshPosition;
  31043. };
  31044. /**
  31045. * Disposes the internal assets and detaches the post-process from the camera
  31046. */
  31047. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31048. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31049. if (rttIndex !== -1) {
  31050. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31051. }
  31052. this._volumetricLightScatteringRTT.dispose();
  31053. _super.prototype.dispose.call(this, camera);
  31054. };
  31055. /**
  31056. * Returns the render target texture used by the post-process
  31057. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31058. */
  31059. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31060. return this._volumetricLightScatteringRTT;
  31061. };
  31062. // Private methods
  31063. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31064. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31065. return true;
  31066. }
  31067. return false;
  31068. };
  31069. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31070. var _this = this;
  31071. var engine = scene.getEngine();
  31072. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31073. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31074. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31075. this._volumetricLightScatteringRTT.renderList = null;
  31076. this._volumetricLightScatteringRTT.renderParticles = false;
  31077. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31078. // Custom render function for submeshes
  31079. var renderSubMesh = function (subMesh) {
  31080. var mesh = subMesh.getRenderingMesh();
  31081. if (_this._meshExcluded(mesh)) {
  31082. return;
  31083. }
  31084. var scene = mesh.getScene();
  31085. var engine = scene.getEngine();
  31086. // Culling
  31087. engine.setState(subMesh.getMaterial().backFaceCulling);
  31088. // Managing instances
  31089. var batch = mesh._getInstancesRenderList(subMesh._id);
  31090. if (batch.mustReturn) {
  31091. return;
  31092. }
  31093. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31094. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31095. engine.enableEffect(_this._volumetricLightScatteringPass);
  31096. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31097. var material = subMesh.getMaterial();
  31098. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31099. // Alpha test
  31100. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31101. var alphaTexture = material.getAlphaTestTexture();
  31102. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31103. if (alphaTexture) {
  31104. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31105. }
  31106. if (material.opacityTexture !== undefined) {
  31107. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31108. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31109. }
  31110. }
  31111. // Bones
  31112. if (mesh.useBones) {
  31113. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31114. }
  31115. // Draw
  31116. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31117. }
  31118. };
  31119. // Render target texture callbacks
  31120. var savedSceneClearColor;
  31121. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31122. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31123. savedSceneClearColor = scene.clearColor;
  31124. scene.clearColor = sceneClearColor;
  31125. };
  31126. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31127. scene.clearColor = savedSceneClearColor;
  31128. };
  31129. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31130. var engine = scene.getEngine();
  31131. var index;
  31132. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31133. renderSubMesh(opaqueSubMeshes.data[index]);
  31134. }
  31135. engine.setAlphaTesting(true);
  31136. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31137. renderSubMesh(alphaTestSubMeshes.data[index]);
  31138. }
  31139. engine.setAlphaTesting(false);
  31140. if (transparentSubMeshes.length) {
  31141. for (index = 0; index < transparentSubMeshes.length; index++) {
  31142. var submesh = transparentSubMeshes.data[index];
  31143. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31144. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31145. }
  31146. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31147. sortedArray.sort(function (a, b) {
  31148. // Alpha index first
  31149. if (a._alphaIndex > b._alphaIndex) {
  31150. return 1;
  31151. }
  31152. if (a._alphaIndex < b._alphaIndex) {
  31153. return -1;
  31154. }
  31155. // Then distance to camera
  31156. if (a._distanceToCamera < b._distanceToCamera) {
  31157. return 1;
  31158. }
  31159. if (a._distanceToCamera > b._distanceToCamera) {
  31160. return -1;
  31161. }
  31162. return 0;
  31163. });
  31164. // Render sub meshes
  31165. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31166. for (index = 0; index < sortedArray.length; index++) {
  31167. renderSubMesh(sortedArray[index]);
  31168. }
  31169. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31170. }
  31171. };
  31172. };
  31173. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31174. var transform = scene.getTransformMatrix();
  31175. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31176. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31177. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31178. if (this.invert)
  31179. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31180. };
  31181. // Static methods
  31182. /**
  31183. * Creates a default mesh for the Volumeric Light Scattering post-process
  31184. * @param {string} The mesh name
  31185. * @param {BABYLON.Scene} The scene where to create the mesh
  31186. * @return {BABYLON.Mesh} the default mesh
  31187. */
  31188. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31189. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31190. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31191. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31192. return mesh;
  31193. };
  31194. return VolumetricLightScatteringPostProcess;
  31195. })(BABYLON.PostProcess);
  31196. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31197. })(BABYLON || (BABYLON = {}));
  31198. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31199. var __extends = this.__extends || function (d, b) {
  31200. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31201. function __() { this.constructor = d; }
  31202. __.prototype = b.prototype;
  31203. d.prototype = new __();
  31204. };
  31205. var BABYLON;
  31206. (function (BABYLON) {
  31207. var LensRenderingPipeline = (function (_super) {
  31208. __extends(LensRenderingPipeline, _super);
  31209. /**
  31210. * @constructor
  31211. *
  31212. * Effect parameters are as follow:
  31213. * {
  31214. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31215. * edge_blur: number; // from 0 to x (1 for realism)
  31216. * distortion: number; // from 0 to x (1 for realism)
  31217. * grain_amount: number; // from 0 to 1
  31218. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31219. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31220. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31221. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31222. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31223. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31224. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31225. * }
  31226. * Note: if an effect parameter is unset, effect is disabled
  31227. *
  31228. * @param {string} name - The rendering pipeline name
  31229. * @param {object} parameters - An object containing all parameters (see above)
  31230. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31231. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  31232. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31233. */
  31234. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31235. var _this = this;
  31236. if (ratio === void 0) { ratio = 1.0; }
  31237. _super.call(this, scene.getEngine(), name);
  31238. // Lens effects can be of the following:
  31239. // - chromatic aberration (slight shift of RGB colors)
  31240. // - blur on the edge of the lens
  31241. // - lens distortion
  31242. // - depth-of-field blur & highlights enhancing
  31243. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31244. // - grain effect (noise or custom texture)
  31245. // Two additional texture samplers are needed:
  31246. // - depth map (for depth-of-field)
  31247. // - grain texture
  31248. /**
  31249. * The chromatic aberration PostProcess id in the pipeline
  31250. * @type {string}
  31251. */
  31252. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31253. /**
  31254. * The highlights enhancing PostProcess id in the pipeline
  31255. * @type {string}
  31256. */
  31257. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31258. /**
  31259. * The depth-of-field PostProcess id in the pipeline
  31260. * @type {string}
  31261. */
  31262. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31263. this._scene = scene;
  31264. // Fetch texture samplers
  31265. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31266. if (parameters.grain_texture) {
  31267. this._grainTexture = parameters.grain_texture;
  31268. }
  31269. else {
  31270. this._createGrainTexture();
  31271. }
  31272. // save parameters
  31273. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31274. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31275. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31276. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31277. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31278. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31279. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31280. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31281. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31282. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31283. // Create effects
  31284. this._createChromaticAberrationPostProcess(ratio);
  31285. this._createHighlightsPostProcess(ratio);
  31286. this._createDepthOfFieldPostProcess(ratio);
  31287. // Set up pipeline
  31288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  31289. return _this._chromaticAberrationPostProcess;
  31290. }, true));
  31291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  31292. return _this._highlightsPostProcess;
  31293. }, true));
  31294. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  31295. return _this._depthOfFieldPostProcess;
  31296. }, true));
  31297. if (this._highlightsGain == -1) {
  31298. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31299. }
  31300. // Finish
  31301. scene.postProcessRenderPipelineManager.addPipeline(this);
  31302. if (cameras) {
  31303. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31304. }
  31305. }
  31306. // public methods (self explanatory)
  31307. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  31308. this._edgeBlur = amount;
  31309. };
  31310. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  31311. this._edgeBlur = 0;
  31312. };
  31313. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  31314. this._grainAmount = amount;
  31315. };
  31316. LensRenderingPipeline.prototype.disableGrain = function () {
  31317. this._grainAmount = 0;
  31318. };
  31319. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  31320. this._chromaticAberration = amount;
  31321. };
  31322. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  31323. this._chromaticAberration = 0;
  31324. };
  31325. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  31326. this._distortion = amount;
  31327. };
  31328. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  31329. this._distortion = 0;
  31330. };
  31331. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  31332. this._dofDepth = amount;
  31333. };
  31334. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  31335. this._dofDepth = -1;
  31336. };
  31337. LensRenderingPipeline.prototype.setAperture = function (amount) {
  31338. this._dofAperture = amount;
  31339. };
  31340. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  31341. this._dofPentagon = true;
  31342. };
  31343. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  31344. this._dofPentagon = false;
  31345. };
  31346. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  31347. this._blurNoise = true;
  31348. };
  31349. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  31350. this._blurNoise = false;
  31351. };
  31352. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31353. this._highlightsGain = amount;
  31354. };
  31355. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31356. if (this._highlightsGain == -1) {
  31357. this._highlightsGain = 1.0;
  31358. }
  31359. this._highlightsThreshold = amount;
  31360. };
  31361. LensRenderingPipeline.prototype.disableHighlights = function () {
  31362. this._highlightsGain = -1;
  31363. };
  31364. /**
  31365. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31366. */
  31367. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31368. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31369. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31370. this._chromaticAberrationPostProcess = undefined;
  31371. this._highlightsPostProcess = undefined;
  31372. this._depthOfFieldPostProcess = undefined;
  31373. this._grainTexture.dispose();
  31374. if (disableDepthRender)
  31375. this._scene.disableDepthRenderer();
  31376. };
  31377. // colors shifting and distortion
  31378. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31379. var _this = this;
  31380. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31381. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31382. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31383. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31384. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31385. };
  31386. };
  31387. // highlights enhancing
  31388. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31389. var _this = this;
  31390. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31391. this._highlightsPostProcess.onApply = function (effect) {
  31392. effect.setFloat('gain', _this._highlightsGain);
  31393. effect.setFloat('threshold', _this._highlightsThreshold);
  31394. effect.setBool('pentagon', _this._dofPentagon);
  31395. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31396. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31397. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31398. };
  31399. };
  31400. // colors shifting and distortion
  31401. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31402. var _this = this;
  31403. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31404. "focus_depth",
  31405. "aperture",
  31406. "pentagon",
  31407. "maxZ",
  31408. "edge_blur",
  31409. "chromatic_aberration",
  31410. "distortion",
  31411. "blur_noise",
  31412. "grain_amount",
  31413. "screen_width",
  31414. "screen_height",
  31415. "highlights"
  31416. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31417. this._depthOfFieldPostProcess.onApply = function (effect) {
  31418. effect.setBool('blur_noise', _this._blurNoise);
  31419. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31420. effect.setFloat('grain_amount', _this._grainAmount);
  31421. effect.setTexture("depthSampler", _this._depthTexture);
  31422. effect.setTexture("grainSampler", _this._grainTexture);
  31423. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31424. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31425. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31426. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31427. effect.setFloat('distortion', _this._distortion);
  31428. effect.setFloat('focus_depth', _this._dofDepth);
  31429. effect.setFloat('aperture', _this._dofAperture);
  31430. effect.setFloat('edge_blur', _this._edgeBlur);
  31431. effect.setBool('highlights', (_this._highlightsGain != -1));
  31432. };
  31433. };
  31434. // creates a black and white random noise texture, 512x512
  31435. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31436. var size = 512;
  31437. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31438. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31439. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31440. var context = this._grainTexture.getContext();
  31441. var rand = function (min, max) {
  31442. return Math.random() * (max - min) + min;
  31443. };
  31444. var value;
  31445. for (var x = 0; x < size; x++) {
  31446. for (var y = 0; y < size; y++) {
  31447. value = Math.floor(rand(0.42, 0.58) * 255);
  31448. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31449. context.fillRect(x, y, 1, 1);
  31450. }
  31451. }
  31452. this._grainTexture.update(false);
  31453. };
  31454. return LensRenderingPipeline;
  31455. })(BABYLON.PostProcessRenderPipeline);
  31456. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31457. })(BABYLON || (BABYLON = {}));
  31458. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31459. //
  31460. // This post-process allows the modification of rendered colors by using
  31461. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31462. //
  31463. // The object needs to be provided an url to a texture containing the color
  31464. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31465. // Use an image editing software to tweak the LUT to match your needs.
  31466. //
  31467. // For an example of a color LUT, see here:
  31468. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31469. // For explanations on color grading, see here:
  31470. // http://udn.epicgames.com/Three/ColorGrading.html
  31471. //
  31472. var __extends = this.__extends || function (d, b) {
  31473. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31474. function __() { this.constructor = d; }
  31475. __.prototype = b.prototype;
  31476. d.prototype = new __();
  31477. };
  31478. var BABYLON;
  31479. (function (BABYLON) {
  31480. var ColorCorrectionPostProcess = (function (_super) {
  31481. __extends(ColorCorrectionPostProcess, _super);
  31482. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31483. var _this = this;
  31484. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31485. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31486. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31487. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31488. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31489. this.onApply = function (effect) {
  31490. effect.setTexture("colorTable", _this._colorTableTexture);
  31491. };
  31492. }
  31493. return ColorCorrectionPostProcess;
  31494. })(BABYLON.PostProcess);
  31495. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31496. })(BABYLON || (BABYLON = {}));
  31497. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31498. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 skyColor;\r\nuniform vec3 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec3 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = vec4(c, 1);\r\n\r\n}","colorPixelShader":"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n\tgl_FragColor = color;\n}","colorVertexShader":"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn visibility;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn 1.0 - ChebychevInequality(moments, depth.z, bias);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., vSpecularColor.a));\r\n\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n\tresult.specular = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\tresult.specular = specComp * specularColor;\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform float maxZ;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform float focus_depth;\r\nuniform float aperture;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI 3.14159265\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(vec2 coords, float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = min(3.0, ceil(size / 1.0));\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\r\n\ttotal_weight += 8.18;\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\r\n\t\ttotal_weight += 5.96;\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\r\n\t\ttotal_weight += 2.97;\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\tcol.a = 1.0;\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b = 0.0; }\r\n\t// if(blur_level == 2.0) { col.r = 0.0; }\r\n\t// if(blur_level == 3.0) { col.g = 0.0; }\r\n\r\n\treturn col;\r\n}\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\r\n\tvec4 final_color;\r\n\tvec2 distorted_coords = getDistortedCoords(vUV);\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\t// blur from depth of field effect\r\n\tfloat dof_blur_amount = 0.0;\r\n\tfloat depth_bias = 0.0;\t\t// positive if the pixel is further than focus depth; negative if closer\r\n\tif (focus_depth != -1.0) {\r\n\t\tvec4 depth_sample = texture2D(depthSampler, distorted_coords);\r\n\t\tfloat depth = depth_sample.r;\r\n\t\tdepth_bias = depth - focus_depth;\r\n\r\n\t\t// compute blur amount with distance\r\n\t\tif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\r\n\t\telse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\r\n\r\n\t\tif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; }\t// no blur at all\r\n\t}\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\r\n\r\n\t\t// if further than focus depth & we have computed highlights: enhance highlights\r\n\t\tif (depth_bias > 0.0 && highlights) {\r\n\t\t\tgl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\r\n\t}\r\n}","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","oculusDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\t#ifndef BASIC_RENDER\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = diffuseColor;\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  31499. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var i=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=i;var e=function(){function i(i,e,r){this.collider=i,this._collisionCache=e,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return i.prototype.collideWithWorld=function(o,i,e,r){var t=.01;if(this.collider.retry>=e)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,i,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&this.collider._getResponse(o,i),i.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,i,e,r))):void o.addToRef(i,this.finalPosition)},i.prototype.checkCollision=function(i){if(this.collider._canDoCollision(o.Vector3.FromArray(i.sphereCenter),i.sphereRadius,o.Vector3.FromArray(i.boxMinimum),o.Vector3.FromArray(i.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var e=o.Matrix.FromArray(i.worldMatrixFromCache);e.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,i)}},i.prototype.processCollisionsForSubMeshes=function(o,i){var e,r;if(r=i.subMeshes,e=r.length,!i.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(i.geometryId);if(!t)return void console.log(\"couldn't find geometry\",i.geometryId);for(var s=0;e>s;s++){var l=r[s];e>1&&!this.checkSubmeshCollision(l)||this.collideForSubMesh(l,o,t)}},i.prototype.collideForSubMesh=function(i,e,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!i._lastColliderWorldVertices||!i._lastColliderTransformMatrix.equals(e)){i._lastColliderTransformMatrix=e.clone(),i._lastColliderWorldVertices=[],i._trianglePlanes=[];for(var n=i.verticesStart,a=i.verticesStart+i.verticesCount,t=n;a>t;t++)i._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],e))}this.collider._collide(i._trianglePlanes,i._lastColliderWorldVertices,r.indices,i.indexStart,i.indexStart+i.indexCount,i.verticesStart,i.hasMaterial)},i.prototype.checkSubmeshCollision=function(i){return this.collider._canDoCollision(o.Vector3.FromArray(i.sphereCenter),i.sphereRadius,o.Vector3.FromArray(i.boxMinimum),o.Vector3.FromArray(i.boxMaximum))},i}();o.CollideWorker=e;var r=function(){function r(){}return r.prototype.onInit=function(o){this._collisionCache=new i;var e={error:0,taskType:0};postMessage(e,void 0)},r.prototype.onUpdate=function(o){for(var i in o.updatedGeometries)o.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(o.updatedGeometries[i]);for(var e in o.updatedMeshes)o.updatedMeshes.hasOwnProperty(e)&&this._collisionCache.addMesh(o.updatedMeshes[e]);var r={error:0,taskType:1};postMessage(r,void 0)},r.prototype.onCollision=function(i){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(i.collider.radius);var s=new e(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(i.collider.position),o.Vector3.FromArray(i.collider.velocity),i.maximumRetry,i.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:i.collisionId,newPosition:r.asArray()},n={error:0,taskType:2,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(o){var i=o.data;switch(i.taskType){case 0:t.onInit(i.payload);break;case 2:t.onCollision(i.payload);break;case 1:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var o=(e.WorkerReplyType,function(){function o(){var i=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){i._addUpdateMeshesList[e.uniqueId]=o.SerializeMesh(e)},this.onGeometryUpdated=function(e){i._addUpdateGeometriesList[e.id]=o.SerializeGeometry(e)},this._afterRender=function(){if(i._init&&!(0==i._toRemoveGeometryArray.length&&0==i._toRemoveMeshesArray.length&&0==Object.keys(i._addUpdateGeometriesList).length&&0==Object.keys(i._addUpdateMeshesList).length||i._runningUpdated>4)){++i._runningUpdated;var e={updatedMeshes:i._addUpdateMeshesList,updatedGeometries:i._addUpdateGeometriesList,removedGeometries:i._toRemoveGeometryArray,removedMeshes:i._toRemoveMeshesArray},o={payload:e,taskType:1},t=[];for(var r in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(r)&&(t.push(o.payload.updatedGeometries[r].indices.buffer),t.push(o.payload.updatedGeometries[r].normals.buffer),t.push(o.payload.updatedGeometries[r].positions.buffer));i._worker.postMessage(o,t),i._addUpdateMeshesList={},i._addUpdateGeometriesList={},i._toRemoveGeometryArray=[],i._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(o){var t=o.data;if(0!=t.error)return void e.Tools.Warn(\"error returned from worker!\");switch(t.taskType){case 0:i._init=!0,i._scene.meshes.forEach(function(e){i.onMeshAdded(e)}),i._scene.getGeometries().forEach(function(e){i.onGeometryAdded(e)});break;case 1:i._runningUpdated--;break;case 2:i._runningCollisionTask=!1;var r=t.payload;if(!i._collisionsCallbackArray[r.collisionId])return;i._collisionsCallbackArray[r.collisionId](r.collisionId,e.Vector3.FromArray(r.newPosition),i._scene.getMeshByUniqueID(r.collidedMeshUniqueId)),i._collisionsCallbackArray[r.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){if(this._init&&!this._collisionsCallbackArray[n]&&!this._collisionsCallbackArray[n+1e5]){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),this._collisionsCallbackArray[n]=s;var a={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:i.radius.asArray()},collisionId:n,excludedMeshUniqueId:r?r.uniqueId:null,maximumRetry:t},d={payload:a,taskType:2};this._worker.postMessage(d)}},o.prototype.init=function(o){this._scene=o,this._scene.registerAfterRender(this._afterRender);var i=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(i),this._worker.onmessage=this._onMessageFromWorker;var t={payload:{},taskType:0};this._worker.postMessage(t)},o.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},o.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},o.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},o.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},o.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},o.SerializeMesh=function(e){var o=[];e.subMeshes&&(o=e.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var i=e.geometry?e.geometry.id:null;return{uniqueId:e.uniqueId,id:e.id,name:e.name,geometryId:i,sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:e.worldMatrixFromCache.asArray(),subMeshes:o,checkCollisions:e.checkCollisions}},o.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},o}());e.CollisionCoordinatorWorker=o;var i=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=i}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function t(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},t.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},t.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b)},t.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},t.prototype.clone=function(){return new t(this.r,this.g,this.b)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},t.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2])},t.FromInts=function(i,o,n){return new t(i/255,o/255,n/255)},t.Lerp=function(i,o,n){var r=i.r+(o.r-i.r)*n,s=i.g+(o.g-i.g)*n,e=i.b+(o.b-i.b)*n;return new t(r,s,e)},t.Red=function(){return new t(1,0,0)},t.Green=function(){return new t(0,1,0)},t.Blue=function(){return new t(0,0,1)},t.Black=function(){return new t(0,0,0)},t.White=function(){return new t(1,1,1)},t.Purple=function(){return new t(.5,0,.5)},t.Magenta=function(){return new t(1,0,1)},t.Yellow=function(){return new t(1,1,0)},t.Gray=function(){return new t(.5,.5,.5)},t}();t.Color3=i;var o=function(){function t(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.Lerp=function(i,o,n){var r=new t(0,0,0,0);return t.LerpToRef(i,o,n,r),r},t.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.FromInts=function(i,o,n,r){return new t(i/255,o/255,n/255,r/255)},t}();t.Color4=o;var n=function(){function t(t,i){this.x=t,this.y=i}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},t.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y)},t.prototype.addVector3=function(i){return new t(this.x+i.x,this.y+i.y)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y)},t.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},t.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},t.prototype.multiply=function(i){return new t(this.x*i.x,this.y*i.y)},t.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},t.prototype.multiplyByFloats=function(i,o){return new t(this.x*i,this.y*o)},t.prototype.divide=function(i){return new t(this.x/i.x,this.y/i.y)},t.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},t.prototype.negate=function(){return new t(-this.x,-this.y)},t.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},t.prototype.scale=function(i){return new t(this.x*i,this.y*i)},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},t.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},t.prototype.clone=function(){return new t(this.x,this.y)},t.Zero=function(){return new t(0,0)},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1])},t.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},t.CatmullRom=function(i,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-i.x+n.x)*s+(2*i.x-5*o.x+4*n.x-r.x)*e+(-i.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-i.y+n.y)*s+(2*i.y-5*o.y+4*n.y-r.y)*e+(-i.y+3*o.y-3*n.y+r.y)*a);return new t(h,u)},t.Clamp=function(i,o,n){var r=i.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=i.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new t(r,s)},t.Hermite=function(i,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,m=a-2*e+s,l=a-e,f=i.x*h+n.x*u+o.x*m+r.x*l,x=i.y*h+n.y*u+o.y*m+r.y*l;return new t(f,x)},t.Lerp=function(i,o,n){var r=i.x+(o.x-i.x)*n,s=i.y+(o.y-i.y)*n;return new t(r,s)},t.Dot=function(t,i){return t.x*i.x+t.y*i.y},t.Normalize=function(t){var i=t.clone();return i.normalize(),i},t.Minimize=function(i,o){var n=i.x<o.x?i.x:o.x,r=i.y<o.y?i.y:o.y;return new t(n,r)},t.Maximize=function(i,o){var n=i.x>o.x?i.x:o.x,r=i.y>o.y?i.y:o.y;return new t(n,r)},t.Transform=function(i,o){var n=i.x*o.m[0]+i.y*o.m[4],r=i.x*o.m[1]+i.y*o.m[5];return new t(n,r)},t.Distance=function(i,o){return Math.sqrt(t.DistanceSquared(i,o))},t.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},t}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i){return Math.abs(this.x-i.x)<t.Engine.Epsilon&&Math.abs(this.y-i.y)<t.Engine.Epsilon&&Math.abs(this.z-i.z)<t.Engine.Epsilon},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),m=SIMD.float32x4.load(n.m,8),l=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,m),l));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),m=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,m)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,m=a-2*e+s,l=a-e,f=t.x*h+n.x*u+o.x*m+r.x*l,x=t.y*h+n.y*u+o.y*m+r.y*l,y=t.z*h+n.z*u+o.z*m+r.z*l;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),l=o.multiply(n).multiply(m);return i.TransformCoordinates(t,l)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var u=i.TransformCoordinates(o,h),m=o.x*h.m[3]+o.y*h.m[7]+o.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(u=u.scale(1/m)),u},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i){return Math.abs(this.x-i.x)<t.Engine.Epsilon&&Math.abs(this.y-i.y)<t.Engine.Epsilon&&Math.abs(this.z-i.z)<t.Engine.Epsilon&&Math.abs(this.w-i.w)<t.Engine.Epsilon},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,i.y=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,i.z=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,i.w=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w,this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,m=o*n,l=i*i,f=o*o,x=l+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-m),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+m)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],m=n[2],l=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(l-u)*o,i.y=(e-m)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(l-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+m)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-m)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+l)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+m)/o,i.y=(u+l)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),m=Math.cos(s),l=Math.sin(e),f=Math.cos(e);n.x=f*u*h+l*m*a,n.y=l*m*h-f*u*a,n.z=f*m*a-l*u*h,n.w=f*m*h+l*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,r=h?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==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[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],m=this.m[9],l=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=l*p-f*c,M=m*p-f*y,w=m*c-l*y,d=u*p-f*x,I=u*c-l*x,D=u*y-m*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,A=e*c-a*y,F=s*p-h*x,P=s*c-a*x,C=s*y-e*x,L=a*f-h*l,q=e*f-h*m,E=e*l-a*m,Z=s*f-h*u,V=s*l-a*u,N=s*m-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*A)*R,t.m[6]=-(i*_-n*F+r*P)*R,t.m[10]=(i*b-o*F+r*C)*R,t.m[14]=-(i*A-o*P+n*C)*R,t.m[3]=-(o*L-n*q+r*E)*R,t.m[7]=(i*L-n*Z+r*V)*R,t.m[11]=-(i*q-o*Z+r*N)*R,t.m[15]=(i*E-o*V+n*N)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,m,l=this.m,f=t.m,x=SIMD.float32x4.load(l,0),y=SIMD.float32x4.load(l,4),c=SIMD.float32x4.load(l,8),p=SIMD.float32x4.load(l,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),m=SIMD.float32x4.mul(i,e),m=SIMD.float32x4.add(SIMD.float32x4.swizzle(m,2,3,0,1),m),m=SIMD.float32x4.add(SIMD.float32x4.swizzle(m,1,0,3,2),m),s=SIMD.float32x4.reciprocalApproximation(m),m=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(m,SIMD.float32x4.mul(s,s))),m=SIMD.float32x4.swizzle(m,0,0,0,0),e=SIMD.float32x4.mul(m,e),a=SIMD.float32x4.mul(m,a),h=SIMD.float32x4.mul(m,h),u=SIMD.float32x4.mul(m,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],m=this.m[7],l=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],A=t.m[11],F=t.m[12],P=t.m[13],C=t.m[14],L=t.m[15];return i[o]=n*w+r*S+s*R+e*F,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*A+e*L,i[o+4]=a*w+h*S+u*R+m*F,i[o+5]=a*d+h*v+u*_+m*P,i[o+6]=a*I+h*g+u*b+m*C,i[o+7]=a*D+h*T+u*A+m*L,i[o+8]=l*w+f*S+x*R+y*F,i[o+9]=l*d+f*v+x*_+y*P,i[o+10]=l*I+f*g+x*b+y*C,i[o+11]=l*D+f*T+x*A+y*L,i[o+12]=c*w+p*S+z*R+M*F,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*A+M*L,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var l=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,m,l,f,x,y,c,p){\np.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=m,p.m[11]=l,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,m,l,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=m,z.m[10]=l,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(m,m),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),m=SIMD.float32x4.mul(m,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(m,m),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),m=SIMD.float32x4.mul(m,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);m=SIMD.float32x4.neg(m);var x=SIMD.float32x4.shuffle(m,l,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(m,l,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,m=t.y,l=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+m,s,1);return o.multiply(n).multiply(r).multiply(l)},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],m=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],l=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,m,l)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,m=s*u-e*h,l=e*a-r*u,f=r*h-s*a,x=Math.sqrt(m*m+l*l+f*f);return n=0!==x?1/x:0,this.normal.x=m*n,this.normal.y=l*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[10]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=m;var l=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o=0,n=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else{var r=1/this.direction.x,s=(t.x-this.origin.x)*r,e=(i.x-this.origin.x)*r;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(o=Math.max(s,o),n=Math.min(e,n),o>n)return!1}if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(r=1/this.direction.y,s=(t.y-this.origin.y)*r,e=(i.y-this.origin.y)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(r=1/this.direction.z,s=(t.z-this.origin.z)*r,e=(i.z-this.origin.z)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),m=r.Unproject(new r(t,o,1),n,s,e,a,h),l=m.subtract(u);return l.normalize(),new i(u,l)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=l,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var m=h*h,l=m*h,f=s*l+e*m+a*h,x=1/(3*s*m+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=(t.Orientation,function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}());t.Angle=y;var c=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=y.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=y.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=y.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-h?0:1,this.angle=y.FromDegrees(0===this.orientation?h-m:m-h)}return t}();t.Arc2=c;var p=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=p;var z=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),m=new c(a,h,u),l=m.angle.radians()/e;0===m.orientation&&(l*=-1);for(var f=m.startAngle.radians()+l,x=0;e>x;x++){var y=Math.cos(f)*m.radius+m.centerPoint.x,p=Math.sin(f)*m.radius+m.centerPoint.y;this.addLineTo(y,p),f+=l}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),m=u.length()+r;if(o>=r&&m>=o){var l=u.normalize(),f=o-r;return new n(a.x+l.x*f,a.y+l.y*f)}r=m}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=z;var M=function(){function t(t,i){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return t.prototype.getCurve=function(){return this._curve},t.prototype.getTangents=function(){return this._tangents},t.prototype.getNormals=function(){return this._normals},t.prototype.getBinormals=function(){return this._binormals},t.prototype.getDistances=function(){return this._distances},t.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},t.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u,m=1;i>m;m++)s=this._getLastNonNullVector(m),i-1>m&&(e=this._getFirstNonNullVector(m),this._tangents[m]=s.add(e),this._tangents[m].normalize()),this._distances[m]=this._distances[m-1]+s.length(),a=this._tangents[m],h=this._normals[m-1],u=this._binormals[m-1],this._normals[m]=r.Cross(u,a),this._normals[m].normalize(),this._binormals[m]=r.Cross(a,this._normals[m]),this._binormals[m].normalize()},t.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0==o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},t.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0==o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},t.prototype._normalVector=function(t,i,o){var n;if(void 0===o||null===o){var s;1!==i.x?s=new r(1,0,0):1!==i.y?s=new r(0,1,0):1!==i.z&&(s=new r(0,0,1)),n=r.Cross(i,s)}else n=r.Cross(i,o),r.CrossToRef(n,i,n);return n.normalize(),n},t}();t.Path3D=M;var w=function(){function i(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return i.CreateQuadraticBezier=function(t,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,t.x,o.x,n.x),a(h/s,t.y,o.y,n.y),a(h/s,t.z,o.z,n.z)));return new i(e)},i.CreateCubicBezier=function(t,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,t.x,o.x,n.x,s.x),h(u/e,t.y,o.y,n.y,s.y),h(u/e,t.z,o.z,n.z,s.z)));return new i(a)},i.CreateHermiteSpline=function(o,n,r,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(t.Vector3.Hermite(o,n,r,s,u*h));return new i(a)},i.prototype.getPoints=function(){return this._points},i.prototype.length=function(){return this._length},i.prototype[\"continue\"]=function(t){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=t.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new i(n);return e},i.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},i}();t.Curve3=w;var d=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var I=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=I;var D=a.prototype.multiplyToArray,S=a.prototype.invertToRef,v=a.LookAtLHToRef,g=r.TransformCoordinatesToRef,T=r.TransformCoordinatesFromFloatsToRef,R=function(){function i(){}return Object.defineProperty(i,\"IsEnabled\",{get:function(){return i._isEnabled},enumerable:!0,configurable:!0}),i.DisableSIMD=function(){a.prototype.multiplyToArray=D,a.prototype.invertToRef=S,a.LookAtLHToRef=v,r.TransformCoordinatesToRef=g,r.TransformCoordinatesFromFloatsToRef=T,i._isEnabled=!1},i.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(t.Vector3.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(t.Vector3.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(t.Vector3.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),i._isEnabled=!0)},i._isEnabled=!1,i}();t.SIMDHelper=R,void 0!==window.SIMD&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&R.EnableSIMD()}(BABYLON||(BABYLON={}));";