babylon.2.1-beta.debug.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392
  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 () { return new Color3(1, 0, 0); };
  106. Color3.Green = function () { return new Color3(0, 1, 0); };
  107. Color3.Blue = function () { return new Color3(0, 0, 1); };
  108. Color3.Black = function () { return new Color3(0, 0, 0); };
  109. Color3.White = function () { return new Color3(1, 1, 1); };
  110. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  111. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  112. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  113. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  114. return Color3;
  115. })();
  116. BABYLON.Color3 = Color3;
  117. var Color4 = (function () {
  118. function Color4(r, g, b, a) {
  119. this.r = r;
  120. this.g = g;
  121. this.b = b;
  122. this.a = a;
  123. }
  124. // Operators
  125. Color4.prototype.addInPlace = function (right) {
  126. this.r += right.r;
  127. this.g += right.g;
  128. this.b += right.b;
  129. this.a += right.a;
  130. return this;
  131. };
  132. Color4.prototype.asArray = function () {
  133. var result = [];
  134. this.toArray(result, 0);
  135. return result;
  136. };
  137. Color4.prototype.toArray = function (array, index) {
  138. if (index === undefined) {
  139. index = 0;
  140. }
  141. array[index] = this.r;
  142. array[index + 1] = this.g;
  143. array[index + 2] = this.b;
  144. array[index + 3] = this.a;
  145. return this;
  146. };
  147. Color4.prototype.add = function (right) {
  148. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  149. };
  150. Color4.prototype.subtract = function (right) {
  151. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  152. };
  153. Color4.prototype.subtractToRef = function (right, result) {
  154. result.r = this.r - right.r;
  155. result.g = this.g - right.g;
  156. result.b = this.b - right.b;
  157. result.a = this.a - right.a;
  158. return this;
  159. };
  160. Color4.prototype.scale = function (scale) {
  161. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  162. };
  163. Color4.prototype.scaleToRef = function (scale, result) {
  164. result.r = this.r * scale;
  165. result.g = this.g * scale;
  166. result.b = this.b * scale;
  167. result.a = this.a * scale;
  168. return this;
  169. };
  170. Color4.prototype.toString = function () {
  171. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  172. };
  173. Color4.prototype.clone = function () {
  174. return new Color4(this.r, this.g, this.b, this.a);
  175. };
  176. Color4.prototype.copyFrom = function (source) {
  177. this.r = source.r;
  178. this.g = source.g;
  179. this.b = source.b;
  180. this.a = source.a;
  181. return this;
  182. };
  183. // Statics
  184. Color4.Lerp = function (left, right, amount) {
  185. var result = new Color4(0, 0, 0, 0);
  186. Color4.LerpToRef(left, right, amount, result);
  187. return result;
  188. };
  189. Color4.LerpToRef = function (left, right, amount, result) {
  190. result.r = left.r + (right.r - left.r) * amount;
  191. result.g = left.g + (right.g - left.g) * amount;
  192. result.b = left.b + (right.b - left.b) * amount;
  193. result.a = left.a + (right.a - left.a) * amount;
  194. };
  195. Color4.FromArray = function (array, offset) {
  196. if (offset === void 0) { offset = 0; }
  197. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  198. };
  199. Color4.FromInts = function (r, g, b, a) {
  200. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  201. };
  202. return Color4;
  203. })();
  204. BABYLON.Color4 = Color4;
  205. var Vector2 = (function () {
  206. function Vector2(x, y) {
  207. this.x = x;
  208. this.y = y;
  209. }
  210. Vector2.prototype.toString = function () {
  211. return "{X: " + this.x + " Y:" + this.y + "}";
  212. };
  213. // Operators
  214. Vector2.prototype.toArray = function (array, index) {
  215. if (index === void 0) { index = 0; }
  216. array[index] = this.x;
  217. array[index + 1] = this.y;
  218. return this;
  219. };
  220. Vector2.prototype.asArray = function () {
  221. var result = [];
  222. this.toArray(result, 0);
  223. return result;
  224. };
  225. Vector2.prototype.copyFrom = function (source) {
  226. this.x = source.x;
  227. this.y = source.y;
  228. return this;
  229. };
  230. Vector2.prototype.copyFromFloats = function (x, y) {
  231. this.x = x;
  232. this.y = y;
  233. return this;
  234. };
  235. Vector2.prototype.add = function (otherVector) {
  236. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  237. };
  238. Vector2.prototype.addVector3 = function (otherVector) {
  239. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  240. };
  241. Vector2.prototype.subtract = function (otherVector) {
  242. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  243. };
  244. Vector2.prototype.subtractInPlace = function (otherVector) {
  245. this.x -= otherVector.x;
  246. this.y -= otherVector.y;
  247. return this;
  248. };
  249. Vector2.prototype.multiplyInPlace = function (otherVector) {
  250. this.x *= otherVector.x;
  251. this.y *= otherVector.y;
  252. return this;
  253. };
  254. Vector2.prototype.multiply = function (otherVector) {
  255. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  256. };
  257. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  258. result.x = this.x * otherVector.x;
  259. result.y = this.y * otherVector.y;
  260. return this;
  261. };
  262. Vector2.prototype.multiplyByFloats = function (x, y) {
  263. return new Vector2(this.x * x, this.y * y);
  264. };
  265. Vector2.prototype.divide = function (otherVector) {
  266. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  267. };
  268. Vector2.prototype.divideToRef = function (otherVector, result) {
  269. result.x = this.x / otherVector.x;
  270. result.y = this.y / otherVector.y;
  271. return this;
  272. };
  273. Vector2.prototype.negate = function () {
  274. return new Vector2(-this.x, -this.y);
  275. };
  276. Vector2.prototype.scaleInPlace = function (scale) {
  277. this.x *= scale;
  278. this.y *= scale;
  279. return this;
  280. };
  281. Vector2.prototype.scale = function (scale) {
  282. return new Vector2(this.x * scale, this.y * scale);
  283. };
  284. Vector2.prototype.equals = function (otherVector) {
  285. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  286. };
  287. // Properties
  288. Vector2.prototype.length = function () {
  289. return Math.sqrt(this.x * this.x + this.y * this.y);
  290. };
  291. Vector2.prototype.lengthSquared = function () {
  292. return (this.x * this.x + this.y * this.y);
  293. };
  294. // Methods
  295. Vector2.prototype.normalize = function () {
  296. var len = this.length();
  297. if (len === 0)
  298. return this;
  299. var num = 1.0 / len;
  300. this.x *= num;
  301. this.y *= num;
  302. return this;
  303. };
  304. Vector2.prototype.clone = function () {
  305. return new Vector2(this.x, this.y);
  306. };
  307. // Statics
  308. Vector2.Zero = function () {
  309. return new Vector2(0, 0);
  310. };
  311. Vector2.FromArray = function (array, offset) {
  312. if (offset === void 0) { offset = 0; }
  313. return new Vector2(array[offset], array[offset + 1]);
  314. };
  315. Vector2.FromArrayToRef = function (array, offset, result) {
  316. result.x = array[offset];
  317. result.y = array[offset + 1];
  318. };
  319. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  320. var squared = amount * amount;
  321. var cubed = amount * squared;
  322. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  323. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  324. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  325. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  326. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  327. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  328. return new Vector2(x, y);
  329. };
  330. Vector2.Clamp = function (value, min, max) {
  331. var x = value.x;
  332. x = (x > max.x) ? max.x : x;
  333. x = (x < min.x) ? min.x : x;
  334. var y = value.y;
  335. y = (y > max.y) ? max.y : y;
  336. y = (y < min.y) ? min.y : y;
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  340. var squared = amount * amount;
  341. var cubed = amount * squared;
  342. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  343. var part2 = (-2.0 * cubed) + (3.0 * squared);
  344. var part3 = (cubed - (2.0 * squared)) + amount;
  345. var part4 = cubed - squared;
  346. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  347. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  348. return new Vector2(x, y);
  349. };
  350. Vector2.Lerp = function (start, end, amount) {
  351. var x = start.x + ((end.x - start.x) * amount);
  352. var y = start.y + ((end.y - start.y) * amount);
  353. return new Vector2(x, y);
  354. };
  355. Vector2.Dot = function (left, right) {
  356. return left.x * right.x + left.y * right.y;
  357. };
  358. Vector2.Normalize = function (vector) {
  359. var newVector = vector.clone();
  360. newVector.normalize();
  361. return newVector;
  362. };
  363. Vector2.Minimize = function (left, right) {
  364. var x = (left.x < right.x) ? left.x : right.x;
  365. var y = (left.y < right.y) ? left.y : right.y;
  366. return new Vector2(x, y);
  367. };
  368. Vector2.Maximize = function (left, right) {
  369. var x = (left.x > right.x) ? left.x : right.x;
  370. var y = (left.y > right.y) ? left.y : right.y;
  371. return new Vector2(x, y);
  372. };
  373. Vector2.Transform = function (vector, transformation) {
  374. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  375. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  376. return new Vector2(x, y);
  377. };
  378. Vector2.Distance = function (value1, value2) {
  379. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  380. };
  381. Vector2.DistanceSquared = function (value1, value2) {
  382. var x = value1.x - value2.x;
  383. var y = value1.y - value2.y;
  384. return (x * x) + (y * y);
  385. };
  386. return Vector2;
  387. })();
  388. BABYLON.Vector2 = Vector2;
  389. var Vector3 = (function () {
  390. function Vector3(x, y, z) {
  391. this.x = x;
  392. this.y = y;
  393. this.z = z;
  394. }
  395. Vector3.prototype.toString = function () {
  396. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  397. };
  398. // Operators
  399. Vector3.prototype.asArray = function () {
  400. var result = [];
  401. this.toArray(result, 0);
  402. return result;
  403. };
  404. Vector3.prototype.toArray = function (array, index) {
  405. if (index === void 0) { index = 0; }
  406. array[index] = this.x;
  407. array[index + 1] = this.y;
  408. array[index + 2] = this.z;
  409. return this;
  410. };
  411. Vector3.prototype.toQuaternion = function () {
  412. var result = new Quaternion(0, 0, 0, 1);
  413. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  414. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  415. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  416. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  417. var cosy = Math.cos(this.y * 0.5);
  418. var siny = Math.sin(this.y * 0.5);
  419. result.x = coszMinusx * siny;
  420. result.y = -sinzMinusx * siny;
  421. result.z = sinxPlusz * cosy;
  422. result.w = cosxPlusz * cosy;
  423. return result;
  424. };
  425. Vector3.prototype.addInPlace = function (otherVector) {
  426. this.x += otherVector.x;
  427. this.y += otherVector.y;
  428. this.z += otherVector.z;
  429. return this;
  430. };
  431. Vector3.prototype.add = function (otherVector) {
  432. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  433. };
  434. Vector3.prototype.addToRef = function (otherVector, result) {
  435. result.x = this.x + otherVector.x;
  436. result.y = this.y + otherVector.y;
  437. result.z = this.z + otherVector.z;
  438. return this;
  439. };
  440. Vector3.prototype.subtractInPlace = function (otherVector) {
  441. this.x -= otherVector.x;
  442. this.y -= otherVector.y;
  443. this.z -= otherVector.z;
  444. return this;
  445. };
  446. Vector3.prototype.subtract = function (otherVector) {
  447. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  448. };
  449. Vector3.prototype.subtractToRef = function (otherVector, result) {
  450. result.x = this.x - otherVector.x;
  451. result.y = this.y - otherVector.y;
  452. result.z = this.z - otherVector.z;
  453. return this;
  454. };
  455. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  456. return new Vector3(this.x - x, this.y - y, this.z - z);
  457. };
  458. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  459. result.x = this.x - x;
  460. result.y = this.y - y;
  461. result.z = this.z - z;
  462. return this;
  463. };
  464. Vector3.prototype.negate = function () {
  465. return new Vector3(-this.x, -this.y, -this.z);
  466. };
  467. Vector3.prototype.scaleInPlace = function (scale) {
  468. this.x *= scale;
  469. this.y *= scale;
  470. this.z *= scale;
  471. return this;
  472. };
  473. Vector3.prototype.scale = function (scale) {
  474. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  475. };
  476. Vector3.prototype.scaleToRef = function (scale, result) {
  477. result.x = this.x * scale;
  478. result.y = this.y * scale;
  479. result.z = this.z * scale;
  480. };
  481. Vector3.prototype.equals = function (otherVector) {
  482. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  483. };
  484. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  485. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon &&
  486. Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon &&
  487. Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  488. };
  489. Vector3.prototype.equalsToFloats = function (x, y, z) {
  490. return this.x === x && this.y === y && this.z === z;
  491. };
  492. Vector3.prototype.multiplyInPlace = function (otherVector) {
  493. this.x *= otherVector.x;
  494. this.y *= otherVector.y;
  495. this.z *= otherVector.z;
  496. return this;
  497. };
  498. Vector3.prototype.multiply = function (otherVector) {
  499. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  500. };
  501. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  502. result.x = this.x * otherVector.x;
  503. result.y = this.y * otherVector.y;
  504. result.z = this.z * otherVector.z;
  505. return this;
  506. };
  507. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  508. return new Vector3(this.x * x, this.y * y, this.z * z);
  509. };
  510. Vector3.prototype.divide = function (otherVector) {
  511. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  512. };
  513. Vector3.prototype.divideToRef = 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.MinimizeInPlace = function (other) {
  520. if (other.x < this.x)
  521. this.x = other.x;
  522. if (other.y < this.y)
  523. this.y = other.y;
  524. if (other.z < this.z)
  525. this.z = other.z;
  526. return this;
  527. };
  528. Vector3.prototype.MaximizeInPlace = function (other) {
  529. if (other.x > this.x)
  530. this.x = other.x;
  531. if (other.y > this.y)
  532. this.y = other.y;
  533. if (other.z > this.z)
  534. this.z = other.z;
  535. return this;
  536. };
  537. // Properties
  538. Vector3.prototype.length = function () {
  539. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  540. };
  541. Vector3.prototype.lengthSquared = function () {
  542. return (this.x * this.x + this.y * this.y + this.z * this.z);
  543. };
  544. // Methods
  545. Vector3.prototype.normalize = function () {
  546. var len = this.length();
  547. if (len === 0)
  548. return this;
  549. var num = 1.0 / len;
  550. this.x *= num;
  551. this.y *= num;
  552. this.z *= num;
  553. return this;
  554. };
  555. Vector3.prototype.clone = function () {
  556. return new Vector3(this.x, this.y, this.z);
  557. };
  558. Vector3.prototype.copyFrom = function (source) {
  559. this.x = source.x;
  560. this.y = source.y;
  561. this.z = source.z;
  562. return this;
  563. };
  564. Vector3.prototype.copyFromFloats = function (x, y, z) {
  565. this.x = x;
  566. this.y = y;
  567. this.z = z;
  568. return this;
  569. };
  570. // Statics
  571. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  572. var d0 = Vector3.Dot(vector0, axis) - size;
  573. var d1 = Vector3.Dot(vector1, axis) - size;
  574. var s = d0 / (d0 - d1);
  575. return s;
  576. };
  577. Vector3.FromArray = function (array, offset) {
  578. if (!offset) {
  579. offset = 0;
  580. }
  581. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  582. };
  583. Vector3.FromArrayToRef = function (array, offset, result) {
  584. result.x = array[offset];
  585. result.y = array[offset + 1];
  586. result.z = array[offset + 2];
  587. };
  588. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  589. result.x = array[offset];
  590. result.y = array[offset + 1];
  591. result.z = array[offset + 2];
  592. };
  593. Vector3.FromFloatsToRef = function (x, y, z, result) {
  594. result.x = x;
  595. result.y = y;
  596. result.z = z;
  597. };
  598. Vector3.Zero = function () {
  599. return new Vector3(0, 0, 0);
  600. };
  601. Vector3.Up = function () {
  602. return new Vector3(0, 1.0, 0);
  603. };
  604. Vector3.TransformCoordinates = function (vector, transformation) {
  605. var result = Vector3.Zero();
  606. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  607. return result;
  608. };
  609. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  610. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  611. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  612. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  613. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  614. result.x = x / w;
  615. result.y = y / w;
  616. result.z = z / w;
  617. };
  618. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  619. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  620. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  621. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  622. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  623. result.x = rx / rw;
  624. result.y = ry / rw;
  625. result.z = rz / rw;
  626. };
  627. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  628. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  629. var m0 = SIMD.float32x4.load(transformation.m, 0);
  630. var m1 = SIMD.float32x4.load(transformation.m, 4);
  631. var m2 = SIMD.float32x4.load(transformation.m, 8);
  632. var m3 = SIMD.float32x4.load(transformation.m, 12);
  633. 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));
  634. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  635. SIMD.float32x4.storeXYZ(result._data, 0, r);
  636. };
  637. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  638. var v0 = SIMD.float32x4.splat(x);
  639. var v1 = SIMD.float32x4.splat(y);
  640. var v2 = SIMD.float32x4.splat(z);
  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(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, 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.TransformNormal = function (vector, transformation) {
  650. var result = Vector3.Zero();
  651. Vector3.TransformNormalToRef(vector, transformation, result);
  652. return result;
  653. };
  654. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  655. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  656. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  657. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  658. };
  659. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  660. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  661. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  662. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  663. };
  664. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  665. var squared = amount * amount;
  666. var cubed = amount * squared;
  667. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  668. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  669. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  670. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  671. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  672. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  673. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  674. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  675. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  676. return new Vector3(x, y, z);
  677. };
  678. Vector3.Clamp = function (value, min, max) {
  679. var x = value.x;
  680. x = (x > max.x) ? max.x : x;
  681. x = (x < min.x) ? min.x : x;
  682. var y = value.y;
  683. y = (y > max.y) ? max.y : y;
  684. y = (y < min.y) ? min.y : y;
  685. var z = value.z;
  686. z = (z > max.z) ? max.z : z;
  687. z = (z < min.z) ? min.z : z;
  688. return new Vector3(x, y, z);
  689. };
  690. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  691. var squared = amount * amount;
  692. var cubed = amount * squared;
  693. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  694. var part2 = (-2.0 * cubed) + (3.0 * squared);
  695. var part3 = (cubed - (2.0 * squared)) + amount;
  696. var part4 = cubed - squared;
  697. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  698. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  699. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  700. return new Vector3(x, y, z);
  701. };
  702. Vector3.Lerp = function (start, end, amount) {
  703. var x = start.x + ((end.x - start.x) * amount);
  704. var y = start.y + ((end.y - start.y) * amount);
  705. var z = start.z + ((end.z - start.z) * amount);
  706. return new Vector3(x, y, z);
  707. };
  708. Vector3.Dot = function (left, right) {
  709. return (left.x * right.x + left.y * right.y + left.z * right.z);
  710. };
  711. Vector3.Cross = function (left, right) {
  712. var result = Vector3.Zero();
  713. Vector3.CrossToRef(left, right, result);
  714. return result;
  715. };
  716. Vector3.CrossToRef = function (left, right, result) {
  717. result.x = left.y * right.z - left.z * right.y;
  718. result.y = left.z * right.x - left.x * right.z;
  719. result.z = left.x * right.y - left.y * right.x;
  720. };
  721. Vector3.Normalize = function (vector) {
  722. var result = Vector3.Zero();
  723. Vector3.NormalizeToRef(vector, result);
  724. return result;
  725. };
  726. Vector3.NormalizeToRef = function (vector, result) {
  727. result.copyFrom(vector);
  728. result.normalize();
  729. };
  730. Vector3.Project = function (vector, world, transform, viewport) {
  731. var cw = viewport.width;
  732. var ch = viewport.height;
  733. var cx = viewport.x;
  734. var cy = viewport.y;
  735. 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);
  736. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  737. return Vector3.TransformCoordinates(vector, finalMatrix);
  738. };
  739. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  740. var matrix = world.multiply(transform);
  741. matrix.invert();
  742. source.x = source.x / viewportWidth * 2 - 1;
  743. source.y = -(source.y / viewportHeight * 2 - 1);
  744. var vector = Vector3.TransformCoordinates(source, matrix);
  745. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  746. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  747. vector = vector.scale(1.0 / num);
  748. }
  749. return vector;
  750. };
  751. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  752. var matrix = world.multiply(view).multiply(projection);
  753. matrix.invert();
  754. source.x = source.x / viewportWidth * 2 - 1;
  755. source.y = -(source.y / viewportHeight * 2 - 1);
  756. var vector = Vector3.TransformCoordinates(source, matrix);
  757. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  758. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  759. vector = vector.scale(1.0 / num);
  760. }
  761. return vector;
  762. };
  763. Vector3.Minimize = function (left, right) {
  764. var min = left.clone();
  765. min.MinimizeInPlace(right);
  766. return min;
  767. };
  768. Vector3.Maximize = function (left, right) {
  769. var max = left.clone();
  770. max.MaximizeInPlace(right);
  771. return max;
  772. };
  773. Vector3.Distance = function (value1, value2) {
  774. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  775. };
  776. Vector3.DistanceSquared = function (value1, value2) {
  777. var x = value1.x - value2.x;
  778. var y = value1.y - value2.y;
  779. var z = value1.z - value2.z;
  780. return (x * x) + (y * y) + (z * z);
  781. };
  782. Vector3.Center = function (value1, value2) {
  783. var center = value1.add(value2);
  784. center.scaleInPlace(0.5);
  785. return center;
  786. };
  787. return Vector3;
  788. })();
  789. BABYLON.Vector3 = Vector3;
  790. //Vector4 class created for EulerAngle class conversion to Quaternion
  791. var Vector4 = (function () {
  792. function Vector4(x, y, z, w) {
  793. this.x = x;
  794. this.y = y;
  795. this.z = z;
  796. this.w = w;
  797. }
  798. Vector4.prototype.toString = function () {
  799. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  800. };
  801. // Operators
  802. Vector4.prototype.asArray = function () {
  803. var result = [];
  804. this.toArray(result, 0);
  805. return result;
  806. };
  807. Vector4.prototype.toArray = function (array, index) {
  808. if (index === undefined) {
  809. index = 0;
  810. }
  811. array[index] = this.x;
  812. array[index + 1] = this.y;
  813. array[index + 2] = this.z;
  814. array[index + 3] = this.w;
  815. return this;
  816. };
  817. Vector4.prototype.addInPlace = function (otherVector) {
  818. this.x += otherVector.x;
  819. this.y += otherVector.y;
  820. this.z += otherVector.z;
  821. this.w += otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.add = function (otherVector) {
  825. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  826. };
  827. Vector4.prototype.addToRef = function (otherVector, result) {
  828. result.x = this.x + otherVector.x;
  829. result.y = this.y + otherVector.y;
  830. result.z = this.z + otherVector.z;
  831. result.w = this.w + otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractInPlace = function (otherVector) {
  835. this.x -= otherVector.x;
  836. this.y -= otherVector.y;
  837. this.z -= otherVector.z;
  838. this.w -= otherVector.w;
  839. return this;
  840. };
  841. Vector4.prototype.subtract = function (otherVector) {
  842. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  843. };
  844. Vector4.prototype.subtractToRef = function (otherVector, result) {
  845. result.x = this.x - otherVector.x;
  846. result.y = this.y - otherVector.y;
  847. result.z = this.z - otherVector.z;
  848. result.w = this.w - otherVector.w;
  849. return this;
  850. };
  851. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  852. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  853. };
  854. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  855. result.x = this.x - x;
  856. result.y = this.y - y;
  857. result.z = this.z - z;
  858. result.w = this.w - w;
  859. return this;
  860. };
  861. Vector4.prototype.negate = function () {
  862. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  863. };
  864. Vector4.prototype.scaleInPlace = function (scale) {
  865. this.x *= scale;
  866. this.y *= scale;
  867. this.z *= scale;
  868. this.w *= scale;
  869. return this;
  870. };
  871. Vector4.prototype.scale = function (scale) {
  872. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  873. };
  874. Vector4.prototype.scaleToRef = function (scale, result) {
  875. result.x = this.x * scale;
  876. result.y = this.y * scale;
  877. result.z = this.z * scale;
  878. result.w = this.w * scale;
  879. };
  880. Vector4.prototype.equals = function (otherVector) {
  881. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  882. };
  883. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  884. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon &&
  885. Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon &&
  886. Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon &&
  887. Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  888. };
  889. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  890. return this.x === x && this.y === y && this.z === z && this.w === w;
  891. };
  892. Vector4.prototype.multiplyInPlace = function (otherVector) {
  893. this.x *= otherVector.x;
  894. this.y *= otherVector.y;
  895. this.z *= otherVector.z;
  896. this.w *= otherVector.w;
  897. return this;
  898. };
  899. Vector4.prototype.multiply = function (otherVector) {
  900. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  901. };
  902. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  903. result.x = this.x * otherVector.x;
  904. result.y = this.y * otherVector.y;
  905. result.z = this.z * otherVector.z;
  906. result.w = this.w * otherVector.w;
  907. return this;
  908. };
  909. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  910. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  911. };
  912. Vector4.prototype.divide = function (otherVector) {
  913. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  914. };
  915. Vector4.prototype.divideToRef = function (otherVector, result) {
  916. result.x = this.x / otherVector.x;
  917. result.y = this.y / otherVector.y;
  918. result.z = this.z / otherVector.z;
  919. result.w = this.w / otherVector.w;
  920. return this;
  921. };
  922. Vector4.prototype.MinimizeInPlace = function (other) {
  923. if (other.x < this.x)
  924. this.x = other.x;
  925. if (other.y < this.y)
  926. this.y = other.y;
  927. if (other.z < this.z)
  928. this.z = other.z;
  929. if (other.w < this.w)
  930. this.w = other.w;
  931. return this;
  932. };
  933. Vector4.prototype.MaximizeInPlace = function (other) {
  934. if (other.x > this.x)
  935. this.x = other.x;
  936. if (other.y > this.y)
  937. this.y = other.y;
  938. if (other.z > this.z)
  939. this.z = other.z;
  940. if (other.w > this.w)
  941. this.w = other.w;
  942. return this;
  943. };
  944. // Properties
  945. Vector4.prototype.length = function () {
  946. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  947. };
  948. Vector4.prototype.lengthSquared = function () {
  949. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  950. };
  951. // Methods
  952. Vector4.prototype.normalize = function () {
  953. var len = this.length();
  954. if (len === 0)
  955. return this;
  956. var num = 1.0 / len;
  957. this.x *= num;
  958. this.y *= num;
  959. this.z *= num;
  960. this.w *= num;
  961. return this;
  962. };
  963. Vector4.prototype.clone = function () {
  964. return new Vector4(this.x, this.y, this.z, this.w);
  965. };
  966. Vector4.prototype.copyFrom = function (source) {
  967. this.x = source.x;
  968. this.y = source.y;
  969. this.z = source.z;
  970. this.w = source.w;
  971. return this;
  972. };
  973. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  974. this.x = x;
  975. this.y = y;
  976. this.z = z;
  977. this.w = w;
  978. return this;
  979. };
  980. // Statics
  981. Vector4.FromArray = function (array, offset) {
  982. if (!offset) {
  983. offset = 0;
  984. }
  985. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  986. };
  987. Vector4.FromArrayToRef = function (array, offset, result) {
  988. result.x = array[offset];
  989. result.y = array[offset + 1];
  990. result.z = array[offset + 2];
  991. result.w = array[offset + 3];
  992. };
  993. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  994. result.x = array[offset];
  995. result.y = array[offset + 1];
  996. result.z = array[offset + 2];
  997. result.w = array[offset + 3];
  998. };
  999. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1000. result.x = x;
  1001. result.y = y;
  1002. result.z = z;
  1003. result.w = w;
  1004. };
  1005. Vector4.Zero = function () {
  1006. return new Vector4(0, 0, 0, 0);
  1007. };
  1008. Vector4.Normalize = function (vector) {
  1009. var result = Vector4.Zero();
  1010. Vector4.NormalizeToRef(vector, result);
  1011. return result;
  1012. };
  1013. Vector4.NormalizeToRef = function (vector, result) {
  1014. result.copyFrom(vector);
  1015. result.normalize();
  1016. };
  1017. Vector4.Minimize = function (left, right) {
  1018. var min = left.clone();
  1019. min.MinimizeInPlace(right);
  1020. return min;
  1021. };
  1022. Vector4.Maximize = function (left, right) {
  1023. var max = left.clone();
  1024. max.MaximizeInPlace(right);
  1025. return max;
  1026. };
  1027. Vector4.Distance = function (value1, value2) {
  1028. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1029. };
  1030. Vector4.DistanceSquared = function (value1, value2) {
  1031. var x = value1.x - value2.x;
  1032. var y = value1.y - value2.y;
  1033. var z = value1.z - value2.z;
  1034. var w = value1.w - value2.w;
  1035. return (x * x) + (y * y) + (z * z) + (w * w);
  1036. };
  1037. Vector4.Center = function (value1, value2) {
  1038. var center = value1.add(value2);
  1039. center.scaleInPlace(0.5);
  1040. return center;
  1041. };
  1042. return Vector4;
  1043. })();
  1044. BABYLON.Vector4 = Vector4;
  1045. var Quaternion = (function () {
  1046. function Quaternion(x, y, z, w) {
  1047. if (x === void 0) { x = 0; }
  1048. if (y === void 0) { y = 0; }
  1049. if (z === void 0) { z = 0; }
  1050. if (w === void 0) { w = 1; }
  1051. this.x = x;
  1052. this.y = y;
  1053. this.z = z;
  1054. this.w = w;
  1055. }
  1056. Quaternion.prototype.toString = function () {
  1057. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1058. };
  1059. Quaternion.prototype.asArray = function () {
  1060. return [this.x, this.y, this.z, this.w];
  1061. };
  1062. Quaternion.prototype.equals = function (otherQuaternion) {
  1063. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1064. };
  1065. Quaternion.prototype.clone = function () {
  1066. return new Quaternion(this.x, this.y, this.z, this.w);
  1067. };
  1068. Quaternion.prototype.copyFrom = function (other) {
  1069. this.x = other.x;
  1070. this.y = other.y;
  1071. this.z = other.z;
  1072. this.w = other.w;
  1073. return this;
  1074. };
  1075. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1076. this.x = x;
  1077. this.y = y;
  1078. this.z = z;
  1079. this.w = w;
  1080. return this;
  1081. };
  1082. Quaternion.prototype.add = function (other) {
  1083. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1084. };
  1085. Quaternion.prototype.subtract = 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.scale = function (value) {
  1089. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1090. };
  1091. Quaternion.prototype.multiply = function (q1) {
  1092. var result = new Quaternion(0, 0, 0, 1.0);
  1093. this.multiplyToRef(q1, result);
  1094. return result;
  1095. };
  1096. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1097. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1098. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1099. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1100. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1101. return this;
  1102. };
  1103. Quaternion.prototype.length = function () {
  1104. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1105. };
  1106. Quaternion.prototype.normalize = function () {
  1107. var length = 1.0 / this.length();
  1108. this.x *= length;
  1109. this.y *= length;
  1110. this.z *= length;
  1111. this.w *= length;
  1112. return this;
  1113. };
  1114. Quaternion.prototype.toEulerAngles = function () {
  1115. var result = Vector3.Zero();
  1116. this.toEulerAnglesToRef(result);
  1117. return result;
  1118. };
  1119. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1120. //result is an EulerAngles in the in the z-x-z convention
  1121. var qx = this.x;
  1122. var qy = this.y;
  1123. var qz = this.z;
  1124. var qw = this.w;
  1125. var qxy = qx * qy;
  1126. var qxz = qx * qz;
  1127. var qwy = qw * qy;
  1128. var qwz = qw * qz;
  1129. var qwx = qw * qx;
  1130. var qyz = qy * qz;
  1131. var sqx = qx * qx;
  1132. var sqy = qy * qy;
  1133. var determinant = sqx + sqy;
  1134. if (determinant !== 0.000 && determinant !== 1.000) {
  1135. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1136. result.y = Math.acos(1 - 2 * determinant);
  1137. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1138. }
  1139. else {
  1140. if (determinant === 0.0) {
  1141. result.x = 0.0;
  1142. result.y = 0.0;
  1143. 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)
  1144. }
  1145. else {
  1146. 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)
  1147. result.y = Math.PI;
  1148. result.z = 0.0;
  1149. }
  1150. }
  1151. return this;
  1152. };
  1153. Quaternion.prototype.toRotationMatrix = function (result) {
  1154. var xx = this.x * this.x;
  1155. var yy = this.y * this.y;
  1156. var zz = this.z * this.z;
  1157. var xy = this.x * this.y;
  1158. var zw = this.z * this.w;
  1159. var zx = this.z * this.x;
  1160. var yw = this.y * this.w;
  1161. var yz = this.y * this.z;
  1162. var xw = this.x * this.w;
  1163. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1164. result.m[1] = 2.0 * (xy + zw);
  1165. result.m[2] = 2.0 * (zx - yw);
  1166. result.m[3] = 0;
  1167. result.m[4] = 2.0 * (xy - zw);
  1168. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1169. result.m[6] = 2.0 * (yz + xw);
  1170. result.m[7] = 0;
  1171. result.m[8] = 2.0 * (zx + yw);
  1172. result.m[9] = 2.0 * (yz - xw);
  1173. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1174. result.m[11] = 0;
  1175. result.m[12] = 0;
  1176. result.m[13] = 0;
  1177. result.m[14] = 0;
  1178. result.m[15] = 1.0;
  1179. return this;
  1180. };
  1181. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1182. Quaternion.FromRotationMatrixToRef(matrix, this);
  1183. return this;
  1184. };
  1185. // Statics
  1186. Quaternion.FromRotationMatrix = function (matrix) {
  1187. var result = new Quaternion();
  1188. Quaternion.FromRotationMatrixToRef(matrix, result);
  1189. return result;
  1190. };
  1191. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1192. var data = matrix.m;
  1193. var m11 = data[0], m12 = data[4], m13 = data[8];
  1194. var m21 = data[1], m22 = data[5], m23 = data[9];
  1195. var m31 = data[2], m32 = data[6], m33 = data[10];
  1196. var trace = m11 + m22 + m33;
  1197. var s;
  1198. if (trace > 0) {
  1199. s = 0.5 / Math.sqrt(trace + 1.0);
  1200. result.w = 0.25 / s;
  1201. result.x = (m32 - m23) * s;
  1202. result.y = (m13 - m31) * s;
  1203. result.z = (m21 - m12) * s;
  1204. }
  1205. else if (m11 > m22 && m11 > m33) {
  1206. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1207. result.w = (m32 - m23) / s;
  1208. result.x = 0.25 * s;
  1209. result.y = (m12 + m21) / s;
  1210. result.z = (m13 + m31) / s;
  1211. }
  1212. else if (m22 > m33) {
  1213. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1214. result.w = (m13 - m31) / s;
  1215. result.x = (m12 + m21) / s;
  1216. result.y = 0.25 * s;
  1217. result.z = (m23 + m32) / s;
  1218. }
  1219. else {
  1220. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1221. result.w = (m21 - m12) / s;
  1222. result.x = (m13 + m31) / s;
  1223. result.y = (m23 + m32) / s;
  1224. result.z = 0.25 * s;
  1225. }
  1226. };
  1227. Quaternion.Inverse = function (q) {
  1228. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1229. };
  1230. Quaternion.Identity = function () {
  1231. return new Quaternion(0, 0, 0, 1);
  1232. };
  1233. Quaternion.RotationAxis = function (axis, angle) {
  1234. var result = new Quaternion();
  1235. var sin = Math.sin(angle / 2);
  1236. result.w = Math.cos(angle / 2);
  1237. result.x = axis.x * sin;
  1238. result.y = axis.y * sin;
  1239. result.z = axis.z * sin;
  1240. return result;
  1241. };
  1242. Quaternion.FromArray = function (array, offset) {
  1243. if (!offset) {
  1244. offset = 0;
  1245. }
  1246. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1247. };
  1248. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1249. var result = new Quaternion();
  1250. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1251. return result;
  1252. };
  1253. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1254. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1255. var halfRoll = roll * 0.5;
  1256. var halfPitch = pitch * 0.5;
  1257. var halfYaw = yaw * 0.5;
  1258. var sinRoll = Math.sin(halfRoll);
  1259. var cosRoll = Math.cos(halfRoll);
  1260. var sinPitch = Math.sin(halfPitch);
  1261. var cosPitch = Math.cos(halfPitch);
  1262. var sinYaw = Math.sin(halfYaw);
  1263. var cosYaw = Math.cos(halfYaw);
  1264. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1265. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1266. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1267. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1268. };
  1269. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1270. var result = new Quaternion();
  1271. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1272. return result;
  1273. };
  1274. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1275. // Produces a quaternion from Euler angles in the z-x-z orientation
  1276. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1277. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1278. var halfBeta = beta * 0.5;
  1279. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1280. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1281. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1282. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1283. };
  1284. Quaternion.Slerp = function (left, right, amount) {
  1285. var num2;
  1286. var num3;
  1287. var num = amount;
  1288. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1289. var flag = false;
  1290. if (num4 < 0) {
  1291. flag = true;
  1292. num4 = -num4;
  1293. }
  1294. if (num4 > 0.999999) {
  1295. num3 = 1 - num;
  1296. num2 = flag ? -num : num;
  1297. }
  1298. else {
  1299. var num5 = Math.acos(num4);
  1300. var num6 = (1.0 / Math.sin(num5));
  1301. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1302. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1303. }
  1304. 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));
  1305. };
  1306. return Quaternion;
  1307. })();
  1308. BABYLON.Quaternion = Quaternion;
  1309. var Matrix = (function () {
  1310. function Matrix() {
  1311. this.m = new Float32Array(16);
  1312. }
  1313. // Properties
  1314. Matrix.prototype.isIdentity = function () {
  1315. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1316. return false;
  1317. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1318. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1319. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1320. 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) -
  1332. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1333. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1334. };
  1335. // Methods
  1336. Matrix.prototype.toArray = function () {
  1337. return this.m;
  1338. };
  1339. Matrix.prototype.asArray = function () {
  1340. return this.toArray();
  1341. };
  1342. Matrix.prototype.invert = function () {
  1343. this.invertToRef(this);
  1344. return this;
  1345. };
  1346. Matrix.prototype.invertToRef = function (other) {
  1347. var l1 = this.m[0];
  1348. var l2 = this.m[1];
  1349. var l3 = this.m[2];
  1350. var l4 = this.m[3];
  1351. var l5 = this.m[4];
  1352. var l6 = this.m[5];
  1353. var l7 = this.m[6];
  1354. var l8 = this.m[7];
  1355. var l9 = this.m[8];
  1356. var l10 = this.m[9];
  1357. var l11 = this.m[10];
  1358. var l12 = this.m[11];
  1359. var l13 = this.m[12];
  1360. var l14 = this.m[13];
  1361. var l15 = this.m[14];
  1362. var l16 = this.m[15];
  1363. var l17 = (l11 * l16) - (l12 * l15);
  1364. var l18 = (l10 * l16) - (l12 * l14);
  1365. var l19 = (l10 * l15) - (l11 * l14);
  1366. var l20 = (l9 * l16) - (l12 * l13);
  1367. var l21 = (l9 * l15) - (l11 * l13);
  1368. var l22 = (l9 * l14) - (l10 * l13);
  1369. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1370. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1371. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1372. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1373. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1374. var l28 = (l7 * l16) - (l8 * l15);
  1375. var l29 = (l6 * l16) - (l8 * l14);
  1376. var l30 = (l6 * l15) - (l7 * l14);
  1377. var l31 = (l5 * l16) - (l8 * l13);
  1378. var l32 = (l5 * l15) - (l7 * l13);
  1379. var l33 = (l5 * l14) - (l6 * l13);
  1380. var l34 = (l7 * l12) - (l8 * l11);
  1381. var l35 = (l6 * l12) - (l8 * l10);
  1382. var l36 = (l6 * l11) - (l7 * l10);
  1383. var l37 = (l5 * l12) - (l8 * l9);
  1384. var l38 = (l5 * l11) - (l7 * l9);
  1385. var l39 = (l5 * l10) - (l6 * l9);
  1386. other.m[0] = l23 * l27;
  1387. other.m[4] = l24 * l27;
  1388. other.m[8] = l25 * l27;
  1389. other.m[12] = l26 * l27;
  1390. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1391. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1392. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1393. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1394. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1395. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1396. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1397. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1398. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1399. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1400. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1401. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1402. return this;
  1403. };
  1404. Matrix.prototype.invertToRefSIMD = function (other) {
  1405. var src = this.m;
  1406. var dest = other.m;
  1407. var row0, row1, row2, row3;
  1408. var tmp1;
  1409. var minor0, minor1, minor2, minor3;
  1410. var det;
  1411. // Load the 4 rows
  1412. var src0 = SIMD.float32x4.load(src, 0);
  1413. var src1 = SIMD.float32x4.load(src, 4);
  1414. var src2 = SIMD.float32x4.load(src, 8);
  1415. var src3 = SIMD.float32x4.load(src, 12);
  1416. // Transpose the source matrix. Sort of. Not a true transpose operation
  1417. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1418. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1419. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1420. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1421. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1422. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1423. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1424. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1425. // This is a true transposition, but it will lead to an incorrect result
  1426. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1427. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1428. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1429. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1430. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1431. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1432. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1433. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1434. // ----
  1435. tmp1 = SIMD.float32x4.mul(row2, row3);
  1436. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1437. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1438. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1439. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1440. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1441. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1442. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1443. // ----
  1444. tmp1 = SIMD.float32x4.mul(row1, row2);
  1445. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1446. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1447. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1448. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1449. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1450. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1451. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1452. // ----
  1453. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1454. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1455. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1456. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1457. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1458. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1459. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1460. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1461. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1462. // ----
  1463. tmp1 = SIMD.float32x4.mul(row0, row1);
  1464. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1465. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1466. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1467. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1468. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1469. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1470. // ----
  1471. tmp1 = SIMD.float32x4.mul(row0, row3);
  1472. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1473. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1474. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1475. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1476. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1477. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1478. // ----
  1479. tmp1 = SIMD.float32x4.mul(row0, row2);
  1480. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1481. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1482. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1483. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1484. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1485. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1486. // Compute determinant
  1487. det = SIMD.float32x4.mul(row0, minor0);
  1488. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1489. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1490. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1491. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1492. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1493. // These shuffles aren't necessary if the faulty transposition is done
  1494. // up at the top of this function.
  1495. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1496. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1497. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1498. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1499. // Compute final values by multiplying with 1/det
  1500. minor0 = SIMD.float32x4.mul(det, minor0);
  1501. minor1 = SIMD.float32x4.mul(det, minor1);
  1502. minor2 = SIMD.float32x4.mul(det, minor2);
  1503. minor3 = SIMD.float32x4.mul(det, minor3);
  1504. SIMD.float32x4.store(dest, 0, minor0);
  1505. SIMD.float32x4.store(dest, 4, minor1);
  1506. SIMD.float32x4.store(dest, 8, minor2);
  1507. SIMD.float32x4.store(dest, 12, minor3);
  1508. return this;
  1509. };
  1510. Matrix.prototype.setTranslation = function (vector3) {
  1511. this.m[12] = vector3.x;
  1512. this.m[13] = vector3.y;
  1513. this.m[14] = vector3.z;
  1514. return this;
  1515. };
  1516. Matrix.prototype.multiply = function (other) {
  1517. var result = new Matrix();
  1518. this.multiplyToRef(other, result);
  1519. return result;
  1520. };
  1521. Matrix.prototype.copyFrom = function (other) {
  1522. for (var index = 0; index < 16; index++) {
  1523. this.m[index] = other.m[index];
  1524. }
  1525. return this;
  1526. };
  1527. Matrix.prototype.copyToArray = function (array, offset) {
  1528. if (offset === void 0) { offset = 0; }
  1529. for (var index = 0; index < 16; index++) {
  1530. array[offset + index] = this.m[index];
  1531. }
  1532. return this;
  1533. };
  1534. Matrix.prototype.multiplyToRef = function (other, result) {
  1535. this.multiplyToArray(other, result.m, 0);
  1536. return this;
  1537. };
  1538. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1539. var tm0 = this.m[0];
  1540. var tm1 = this.m[1];
  1541. var tm2 = this.m[2];
  1542. var tm3 = this.m[3];
  1543. var tm4 = this.m[4];
  1544. var tm5 = this.m[5];
  1545. var tm6 = this.m[6];
  1546. var tm7 = this.m[7];
  1547. var tm8 = this.m[8];
  1548. var tm9 = this.m[9];
  1549. var tm10 = this.m[10];
  1550. var tm11 = this.m[11];
  1551. var tm12 = this.m[12];
  1552. var tm13 = this.m[13];
  1553. var tm14 = this.m[14];
  1554. var tm15 = this.m[15];
  1555. var om0 = other.m[0];
  1556. var om1 = other.m[1];
  1557. var om2 = other.m[2];
  1558. var om3 = other.m[3];
  1559. var om4 = other.m[4];
  1560. var om5 = other.m[5];
  1561. var om6 = other.m[6];
  1562. var om7 = other.m[7];
  1563. var om8 = other.m[8];
  1564. var om9 = other.m[9];
  1565. var om10 = other.m[10];
  1566. var om11 = other.m[11];
  1567. var om12 = other.m[12];
  1568. var om13 = other.m[13];
  1569. var om14 = other.m[14];
  1570. var om15 = other.m[15];
  1571. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1572. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1573. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1574. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1575. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1576. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1577. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1578. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1579. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1580. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1581. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1582. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1583. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1584. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1585. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1586. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1587. return this;
  1588. };
  1589. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1590. if (offset === void 0) { offset = 0; }
  1591. var tm = this.m;
  1592. var om = other.m;
  1593. var om0 = SIMD.float32x4.load(om, 0);
  1594. var om1 = SIMD.float32x4.load(om, 4);
  1595. var om2 = SIMD.float32x4.load(om, 8);
  1596. var om3 = SIMD.float32x4.load(om, 12);
  1597. var tm0 = SIMD.float32x4.load(tm, 0);
  1598. 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)))));
  1599. var tm1 = SIMD.float32x4.load(tm, 4);
  1600. 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)))));
  1601. var tm2 = SIMD.float32x4.load(tm, 8);
  1602. 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)))));
  1603. var tm3 = SIMD.float32x4.load(tm, 12);
  1604. 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)))));
  1605. };
  1606. Matrix.prototype.equals = function (value) {
  1607. return value &&
  1608. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1609. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1610. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1611. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1612. };
  1613. Matrix.prototype.clone = function () {
  1614. 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]);
  1615. };
  1616. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1617. translation.x = this.m[12];
  1618. translation.y = this.m[13];
  1619. translation.z = this.m[14];
  1620. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1621. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1622. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1623. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1624. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1625. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1626. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1627. rotation.x = 0;
  1628. rotation.y = 0;
  1629. rotation.z = 0;
  1630. rotation.w = 1;
  1631. return false;
  1632. }
  1633. 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);
  1634. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1635. return true;
  1636. };
  1637. // Statics
  1638. Matrix.FromArray = function (array, offset) {
  1639. var result = new Matrix();
  1640. if (!offset) {
  1641. offset = 0;
  1642. }
  1643. Matrix.FromArrayToRef(array, offset, result);
  1644. return result;
  1645. };
  1646. Matrix.FromArrayToRef = function (array, offset, result) {
  1647. for (var index = 0; index < 16; index++) {
  1648. result.m[index] = array[index + offset];
  1649. }
  1650. };
  1651. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1652. result.m[0] = initialM11;
  1653. result.m[1] = initialM12;
  1654. result.m[2] = initialM13;
  1655. result.m[3] = initialM14;
  1656. result.m[4] = initialM21;
  1657. result.m[5] = initialM22;
  1658. result.m[6] = initialM23;
  1659. result.m[7] = initialM24;
  1660. result.m[8] = initialM31;
  1661. result.m[9] = initialM32;
  1662. result.m[10] = initialM33;
  1663. result.m[11] = initialM34;
  1664. result.m[12] = initialM41;
  1665. result.m[13] = initialM42;
  1666. result.m[14] = initialM43;
  1667. result.m[15] = initialM44;
  1668. };
  1669. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1670. var result = new Matrix();
  1671. result.m[0] = initialM11;
  1672. result.m[1] = initialM12;
  1673. result.m[2] = initialM13;
  1674. result.m[3] = initialM14;
  1675. result.m[4] = initialM21;
  1676. result.m[5] = initialM22;
  1677. result.m[6] = initialM23;
  1678. result.m[7] = initialM24;
  1679. result.m[8] = initialM31;
  1680. result.m[9] = initialM32;
  1681. result.m[10] = initialM33;
  1682. result.m[11] = initialM34;
  1683. result.m[12] = initialM41;
  1684. result.m[13] = initialM42;
  1685. result.m[14] = initialM43;
  1686. result.m[15] = initialM44;
  1687. return result;
  1688. };
  1689. Matrix.Compose = function (scale, rotation, translation) {
  1690. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1691. var rotationMatrix = Matrix.Identity();
  1692. rotation.toRotationMatrix(rotationMatrix);
  1693. result = result.multiply(rotationMatrix);
  1694. result.setTranslation(translation);
  1695. return result;
  1696. };
  1697. Matrix.Identity = function () {
  1698. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1699. };
  1700. Matrix.IdentityToRef = function (result) {
  1701. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1702. };
  1703. Matrix.Zero = function () {
  1704. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1705. };
  1706. Matrix.RotationX = function (angle) {
  1707. var result = new Matrix();
  1708. Matrix.RotationXToRef(angle, result);
  1709. return result;
  1710. };
  1711. Matrix.Invert = function (source) {
  1712. var result = new Matrix();
  1713. source.invertToRef(result);
  1714. return result;
  1715. };
  1716. Matrix.RotationXToRef = function (angle, result) {
  1717. var s = Math.sin(angle);
  1718. var c = Math.cos(angle);
  1719. result.m[0] = 1.0;
  1720. result.m[15] = 1.0;
  1721. result.m[5] = c;
  1722. result.m[10] = c;
  1723. result.m[9] = -s;
  1724. result.m[6] = s;
  1725. result.m[1] = 0;
  1726. result.m[2] = 0;
  1727. result.m[3] = 0;
  1728. result.m[4] = 0;
  1729. result.m[7] = 0;
  1730. result.m[8] = 0;
  1731. result.m[11] = 0;
  1732. result.m[12] = 0;
  1733. result.m[13] = 0;
  1734. result.m[14] = 0;
  1735. };
  1736. Matrix.RotationY = function (angle) {
  1737. var result = new Matrix();
  1738. Matrix.RotationYToRef(angle, result);
  1739. return result;
  1740. };
  1741. Matrix.RotationYToRef = function (angle, result) {
  1742. var s = Math.sin(angle);
  1743. var c = Math.cos(angle);
  1744. result.m[5] = 1.0;
  1745. result.m[15] = 1.0;
  1746. result.m[0] = c;
  1747. result.m[2] = -s;
  1748. result.m[8] = s;
  1749. result.m[10] = c;
  1750. result.m[1] = 0;
  1751. result.m[3] = 0;
  1752. result.m[4] = 0;
  1753. result.m[6] = 0;
  1754. result.m[7] = 0;
  1755. result.m[9] = 0;
  1756. result.m[11] = 0;
  1757. result.m[12] = 0;
  1758. result.m[13] = 0;
  1759. result.m[14] = 0;
  1760. };
  1761. Matrix.RotationZ = function (angle) {
  1762. var result = new Matrix();
  1763. Matrix.RotationZToRef(angle, result);
  1764. return result;
  1765. };
  1766. Matrix.RotationZToRef = function (angle, result) {
  1767. var s = Math.sin(angle);
  1768. var c = Math.cos(angle);
  1769. result.m[10] = 1.0;
  1770. result.m[15] = 1.0;
  1771. result.m[0] = c;
  1772. result.m[1] = s;
  1773. result.m[4] = -s;
  1774. result.m[5] = c;
  1775. result.m[2] = 0;
  1776. result.m[3] = 0;
  1777. result.m[6] = 0;
  1778. result.m[7] = 0;
  1779. result.m[8] = 0;
  1780. result.m[9] = 0;
  1781. result.m[11] = 0;
  1782. result.m[12] = 0;
  1783. result.m[13] = 0;
  1784. result.m[14] = 0;
  1785. };
  1786. Matrix.RotationAxis = function (axis, angle) {
  1787. var s = Math.sin(-angle);
  1788. var c = Math.cos(-angle);
  1789. var c1 = 1 - c;
  1790. axis.normalize();
  1791. var result = Matrix.Zero();
  1792. result.m[0] = (axis.x * axis.x) * c1 + c;
  1793. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1794. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1795. result.m[3] = 0.0;
  1796. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1797. result.m[5] = (axis.y * axis.y) * c1 + c;
  1798. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1799. result.m[7] = 0.0;
  1800. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1801. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1802. result.m[10] = (axis.z * axis.z) * c1 + c;
  1803. result.m[11] = 0.0;
  1804. result.m[15] = 1.0;
  1805. return result;
  1806. };
  1807. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1808. var result = new Matrix();
  1809. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1810. return result;
  1811. };
  1812. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1813. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1814. this._tempQuaternion.toRotationMatrix(result);
  1815. };
  1816. Matrix.Scaling = function (x, y, z) {
  1817. var result = Matrix.Zero();
  1818. Matrix.ScalingToRef(x, y, z, result);
  1819. return result;
  1820. };
  1821. Matrix.ScalingToRef = function (x, y, z, result) {
  1822. result.m[0] = x;
  1823. result.m[1] = 0;
  1824. result.m[2] = 0;
  1825. result.m[3] = 0;
  1826. result.m[4] = 0;
  1827. result.m[5] = y;
  1828. result.m[6] = 0;
  1829. result.m[7] = 0;
  1830. result.m[8] = 0;
  1831. result.m[9] = 0;
  1832. result.m[10] = z;
  1833. result.m[11] = 0;
  1834. result.m[12] = 0;
  1835. result.m[13] = 0;
  1836. result.m[14] = 0;
  1837. result.m[15] = 1.0;
  1838. };
  1839. Matrix.Translation = function (x, y, z) {
  1840. var result = Matrix.Identity();
  1841. Matrix.TranslationToRef(x, y, z, result);
  1842. return result;
  1843. };
  1844. Matrix.TranslationToRef = function (x, y, z, result) {
  1845. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1846. };
  1847. Matrix.LookAtLH = function (eye, target, up) {
  1848. var result = Matrix.Zero();
  1849. Matrix.LookAtLHToRef(eye, target, up, result);
  1850. return result;
  1851. };
  1852. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1853. // Z axis
  1854. target.subtractToRef(eye, this._zAxis);
  1855. this._zAxis.normalize();
  1856. // X axis
  1857. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1858. this._xAxis.normalize();
  1859. // Y axis
  1860. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1861. this._yAxis.normalize();
  1862. // Eye angles
  1863. var ex = -Vector3.Dot(this._xAxis, eye);
  1864. var ey = -Vector3.Dot(this._yAxis, eye);
  1865. var ez = -Vector3.Dot(this._zAxis, eye);
  1866. 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);
  1867. };
  1868. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1869. var out = result.m;
  1870. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1871. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1872. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1873. // cc.kmVec3Subtract(f, pCenter, pEye);
  1874. var f = SIMD.float32x4.sub(center, eye);
  1875. // cc.kmVec3Normalize(f, f);
  1876. var tmp = SIMD.float32x4.mul(f, f);
  1877. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1878. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1879. // cc.kmVec3Assign(up, pUp);
  1880. // cc.kmVec3Normalize(up, up);
  1881. tmp = SIMD.float32x4.mul(up, up);
  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. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1884. // cc.kmVec3Cross(s, f, up);
  1885. 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)));
  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. // cc.kmVec3Cross(u, s, f);
  1891. 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)));
  1892. // cc.kmVec3Normalize(s, s);
  1893. tmp = SIMD.float32x4.mul(s, s);
  1894. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1895. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1896. var zero = SIMD.float32x4.splat(0.0);
  1897. s = SIMD.float32x4.neg(s);
  1898. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1899. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1900. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1901. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1902. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1903. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1904. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1905. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1906. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1907. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1908. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1909. var b3 = SIMD.float32x4.neg(eye);
  1910. b3 = SIMD.float32x4.withW(b3, 1.0);
  1911. 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)))));
  1912. 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)))));
  1913. 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)))));
  1914. 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)))));
  1915. };
  1916. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1917. var matrix = Matrix.Zero();
  1918. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1919. return matrix;
  1920. };
  1921. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1922. var hw = 2.0 / width;
  1923. var hh = 2.0 / height;
  1924. var id = 1.0 / (zfar - znear);
  1925. var nid = znear / (znear - zfar);
  1926. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1927. };
  1928. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1929. var matrix = Matrix.Zero();
  1930. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1931. return matrix;
  1932. };
  1933. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1934. result.m[0] = 2.0 / (right - left);
  1935. result.m[1] = result.m[2] = result.m[3] = 0;
  1936. result.m[5] = 2.0 / (top - bottom);
  1937. result.m[4] = result.m[6] = result.m[7] = 0;
  1938. result.m[10] = -1.0 / (znear - zfar);
  1939. result.m[8] = result.m[9] = result.m[11] = 0;
  1940. result.m[12] = (left + right) / (left - right);
  1941. result.m[13] = (top + bottom) / (bottom - top);
  1942. result.m[14] = znear / (znear - zfar);
  1943. result.m[15] = 1.0;
  1944. };
  1945. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1946. var matrix = Matrix.Zero();
  1947. matrix.m[0] = (2.0 * znear) / width;
  1948. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1949. matrix.m[5] = (2.0 * znear) / height;
  1950. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1951. matrix.m[10] = -zfar / (znear - zfar);
  1952. matrix.m[8] = matrix.m[9] = 0.0;
  1953. matrix.m[11] = 1.0;
  1954. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1955. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1956. return matrix;
  1957. };
  1958. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1959. var matrix = Matrix.Zero();
  1960. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1961. return matrix;
  1962. };
  1963. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1964. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1965. var tan = 1.0 / (Math.tan(fov * 0.5));
  1966. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1967. if (v_fixed) {
  1968. result.m[0] = tan / aspect;
  1969. }
  1970. else {
  1971. result.m[0] = tan;
  1972. }
  1973. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1974. if (v_fixed) {
  1975. result.m[5] = tan;
  1976. }
  1977. else {
  1978. result.m[5] = tan * aspect;
  1979. }
  1980. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1981. result.m[8] = result.m[9] = 0.0;
  1982. result.m[10] = -zfar / (znear - zfar);
  1983. result.m[11] = 1.0;
  1984. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1985. result.m[14] = (znear * zfar) / (znear - zfar);
  1986. };
  1987. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1988. var cw = viewport.width;
  1989. var ch = viewport.height;
  1990. var cx = viewport.x;
  1991. var cy = viewport.y;
  1992. 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);
  1993. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1994. };
  1995. Matrix.Transpose = function (matrix) {
  1996. var result = new Matrix();
  1997. result.m[0] = matrix.m[0];
  1998. result.m[1] = matrix.m[4];
  1999. result.m[2] = matrix.m[8];
  2000. result.m[3] = matrix.m[12];
  2001. result.m[4] = matrix.m[1];
  2002. result.m[5] = matrix.m[5];
  2003. result.m[6] = matrix.m[9];
  2004. result.m[7] = matrix.m[13];
  2005. result.m[8] = matrix.m[2];
  2006. result.m[9] = matrix.m[6];
  2007. result.m[10] = matrix.m[10];
  2008. result.m[11] = matrix.m[14];
  2009. result.m[12] = matrix.m[3];
  2010. result.m[13] = matrix.m[7];
  2011. result.m[14] = matrix.m[11];
  2012. result.m[15] = matrix.m[15];
  2013. return result;
  2014. };
  2015. Matrix.Reflection = function (plane) {
  2016. var matrix = new Matrix();
  2017. Matrix.ReflectionToRef(plane, matrix);
  2018. return matrix;
  2019. };
  2020. Matrix.ReflectionToRef = function (plane, result) {
  2021. plane.normalize();
  2022. var x = plane.normal.x;
  2023. var y = plane.normal.y;
  2024. var z = plane.normal.z;
  2025. var temp = -2 * x;
  2026. var temp2 = -2 * y;
  2027. var temp3 = -2 * z;
  2028. result.m[0] = (temp * x) + 1;
  2029. result.m[1] = temp2 * x;
  2030. result.m[2] = temp3 * x;
  2031. result.m[3] = 0.0;
  2032. result.m[4] = temp * y;
  2033. result.m[5] = (temp2 * y) + 1;
  2034. result.m[6] = temp3 * y;
  2035. result.m[7] = 0.0;
  2036. result.m[8] = temp * z;
  2037. result.m[9] = temp2 * z;
  2038. result.m[10] = (temp3 * z) + 1;
  2039. result.m[11] = 0.0;
  2040. result.m[12] = temp * plane.d;
  2041. result.m[13] = temp2 * plane.d;
  2042. result.m[14] = temp3 * plane.d;
  2043. result.m[15] = 1.0;
  2044. };
  2045. Matrix._tempQuaternion = new Quaternion();
  2046. Matrix._xAxis = Vector3.Zero();
  2047. Matrix._yAxis = Vector3.Zero();
  2048. Matrix._zAxis = Vector3.Zero();
  2049. return Matrix;
  2050. })();
  2051. BABYLON.Matrix = Matrix;
  2052. var Plane = (function () {
  2053. function Plane(a, b, c, d) {
  2054. this.normal = new Vector3(a, b, c);
  2055. this.d = d;
  2056. }
  2057. Plane.prototype.asArray = function () {
  2058. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2059. };
  2060. // Methods
  2061. Plane.prototype.clone = function () {
  2062. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2063. };
  2064. Plane.prototype.normalize = function () {
  2065. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2066. var magnitude = 0;
  2067. if (norm !== 0) {
  2068. magnitude = 1.0 / norm;
  2069. }
  2070. this.normal.x *= magnitude;
  2071. this.normal.y *= magnitude;
  2072. this.normal.z *= magnitude;
  2073. this.d *= magnitude;
  2074. return this;
  2075. };
  2076. Plane.prototype.transform = function (transformation) {
  2077. var transposedMatrix = Matrix.Transpose(transformation);
  2078. var x = this.normal.x;
  2079. var y = this.normal.y;
  2080. var z = this.normal.z;
  2081. var d = this.d;
  2082. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2083. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2084. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2085. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2086. return new Plane(normalX, normalY, normalZ, finalD);
  2087. };
  2088. Plane.prototype.dotCoordinate = function (point) {
  2089. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2090. };
  2091. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2092. var x1 = point2.x - point1.x;
  2093. var y1 = point2.y - point1.y;
  2094. var z1 = point2.z - point1.z;
  2095. var x2 = point3.x - point1.x;
  2096. var y2 = point3.y - point1.y;
  2097. var z2 = point3.z - point1.z;
  2098. var yz = (y1 * z2) - (z1 * y2);
  2099. var xz = (z1 * x2) - (x1 * z2);
  2100. var xy = (x1 * y2) - (y1 * x2);
  2101. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2102. var invPyth;
  2103. if (pyth !== 0) {
  2104. invPyth = 1.0 / pyth;
  2105. }
  2106. else {
  2107. invPyth = 0;
  2108. }
  2109. this.normal.x = yz * invPyth;
  2110. this.normal.y = xz * invPyth;
  2111. this.normal.z = xy * invPyth;
  2112. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2113. return this;
  2114. };
  2115. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2116. var dot = Vector3.Dot(this.normal, direction);
  2117. return (dot <= epsilon);
  2118. };
  2119. Plane.prototype.signedDistanceTo = function (point) {
  2120. return Vector3.Dot(point, this.normal) + this.d;
  2121. };
  2122. // Statics
  2123. Plane.FromArray = function (array) {
  2124. return new Plane(array[0], array[1], array[2], array[3]);
  2125. };
  2126. Plane.FromPoints = function (point1, point2, point3) {
  2127. var result = new Plane(0, 0, 0, 0);
  2128. result.copyFromPoints(point1, point2, point3);
  2129. return result;
  2130. };
  2131. Plane.FromPositionAndNormal = function (origin, normal) {
  2132. var result = new Plane(0, 0, 0, 0);
  2133. normal.normalize();
  2134. result.normal = normal;
  2135. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2136. return result;
  2137. };
  2138. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2139. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2140. return Vector3.Dot(point, normal) + d;
  2141. };
  2142. return Plane;
  2143. })();
  2144. BABYLON.Plane = Plane;
  2145. var Viewport = (function () {
  2146. function Viewport(x, y, width, height) {
  2147. this.x = x;
  2148. this.y = y;
  2149. this.width = width;
  2150. this.height = height;
  2151. }
  2152. Viewport.prototype.toGlobal = function (engine) {
  2153. var width = engine.getRenderWidth();
  2154. var height = engine.getRenderHeight();
  2155. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2156. };
  2157. return Viewport;
  2158. })();
  2159. BABYLON.Viewport = Viewport;
  2160. var Frustum = (function () {
  2161. function Frustum() {
  2162. }
  2163. Frustum.GetPlanes = function (transform) {
  2164. var frustumPlanes = [];
  2165. for (var index = 0; index < 6; index++) {
  2166. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2167. }
  2168. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2169. return frustumPlanes;
  2170. };
  2171. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2172. // Near
  2173. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2174. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2175. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2176. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2177. frustumPlanes[0].normalize();
  2178. // Far
  2179. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2180. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2181. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2182. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2183. frustumPlanes[1].normalize();
  2184. // Left
  2185. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2186. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2187. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2188. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2189. frustumPlanes[2].normalize();
  2190. // Right
  2191. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2192. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2193. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2194. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2195. frustumPlanes[3].normalize();
  2196. // Top
  2197. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2198. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2199. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2200. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2201. frustumPlanes[4].normalize();
  2202. // Bottom
  2203. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2204. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2205. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2206. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2207. frustumPlanes[5].normalize();
  2208. };
  2209. return Frustum;
  2210. })();
  2211. BABYLON.Frustum = Frustum;
  2212. var Ray = (function () {
  2213. function Ray(origin, direction, length) {
  2214. if (length === void 0) { length = Number.MAX_VALUE; }
  2215. this.origin = origin;
  2216. this.direction = direction;
  2217. this.length = length;
  2218. }
  2219. // Methods
  2220. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2221. var d = 0.0;
  2222. var maxValue = Number.MAX_VALUE;
  2223. if (Math.abs(this.direction.x) < 0.0000001) {
  2224. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2225. return false;
  2226. }
  2227. }
  2228. else {
  2229. var inv = 1.0 / this.direction.x;
  2230. var min = (minimum.x - this.origin.x) * inv;
  2231. var max = (maximum.x - this.origin.x) * inv;
  2232. if (max === -Infinity) {
  2233. max = Infinity;
  2234. }
  2235. if (min > max) {
  2236. var temp = min;
  2237. min = max;
  2238. max = temp;
  2239. }
  2240. d = Math.max(min, d);
  2241. maxValue = Math.min(max, maxValue);
  2242. if (d > maxValue) {
  2243. return false;
  2244. }
  2245. }
  2246. if (Math.abs(this.direction.y) < 0.0000001) {
  2247. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2248. return false;
  2249. }
  2250. }
  2251. else {
  2252. inv = 1.0 / this.direction.y;
  2253. min = (minimum.y - this.origin.y) * inv;
  2254. max = (maximum.y - this.origin.y) * inv;
  2255. if (max === -Infinity) {
  2256. max = Infinity;
  2257. }
  2258. if (min > max) {
  2259. temp = min;
  2260. min = max;
  2261. max = temp;
  2262. }
  2263. d = Math.max(min, d);
  2264. maxValue = Math.min(max, maxValue);
  2265. if (d > maxValue) {
  2266. return false;
  2267. }
  2268. }
  2269. if (Math.abs(this.direction.z) < 0.0000001) {
  2270. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2271. return false;
  2272. }
  2273. }
  2274. else {
  2275. inv = 1.0 / this.direction.z;
  2276. min = (minimum.z - this.origin.z) * inv;
  2277. max = (maximum.z - this.origin.z) * inv;
  2278. if (max === -Infinity) {
  2279. max = Infinity;
  2280. }
  2281. if (min > max) {
  2282. temp = min;
  2283. min = max;
  2284. max = temp;
  2285. }
  2286. d = Math.max(min, d);
  2287. maxValue = Math.min(max, maxValue);
  2288. if (d > maxValue) {
  2289. return false;
  2290. }
  2291. }
  2292. return true;
  2293. };
  2294. Ray.prototype.intersectsBox = function (box) {
  2295. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2296. };
  2297. Ray.prototype.intersectsSphere = function (sphere) {
  2298. var x = sphere.center.x - this.origin.x;
  2299. var y = sphere.center.y - this.origin.y;
  2300. var z = sphere.center.z - this.origin.z;
  2301. var pyth = (x * x) + (y * y) + (z * z);
  2302. var rr = sphere.radius * sphere.radius;
  2303. if (pyth <= rr) {
  2304. return true;
  2305. }
  2306. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2307. if (dot < 0.0) {
  2308. return false;
  2309. }
  2310. var temp = pyth - (dot * dot);
  2311. return temp <= rr;
  2312. };
  2313. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2314. if (!this._edge1) {
  2315. this._edge1 = Vector3.Zero();
  2316. this._edge2 = Vector3.Zero();
  2317. this._pvec = Vector3.Zero();
  2318. this._tvec = Vector3.Zero();
  2319. this._qvec = Vector3.Zero();
  2320. }
  2321. vertex1.subtractToRef(vertex0, this._edge1);
  2322. vertex2.subtractToRef(vertex0, this._edge2);
  2323. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2324. var det = Vector3.Dot(this._edge1, this._pvec);
  2325. if (det === 0) {
  2326. return null;
  2327. }
  2328. var invdet = 1 / det;
  2329. this.origin.subtractToRef(vertex0, this._tvec);
  2330. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2331. if (bu < 0 || bu > 1.0) {
  2332. return null;
  2333. }
  2334. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2335. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2336. if (bv < 0 || bu + bv > 1.0) {
  2337. return null;
  2338. }
  2339. //check if the distance is longer than the predefined length.
  2340. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2341. if (distance > this.length) {
  2342. return null;
  2343. }
  2344. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2345. };
  2346. // Statics
  2347. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2348. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2349. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2350. var direction = end.subtract(start);
  2351. direction.normalize();
  2352. return new Ray(start, direction);
  2353. };
  2354. /**
  2355. * 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
  2356. * transformed to the given world matrix.
  2357. * @param origin The origin point
  2358. * @param end The end point
  2359. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2360. */
  2361. Ray.CreateNewFromTo = function (origin, end, world) {
  2362. if (world === void 0) { world = Matrix.Identity(); }
  2363. var direction = end.subtract(origin);
  2364. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2365. direction.normalize();
  2366. return Ray.Transform(new Ray(origin, direction, length), world);
  2367. };
  2368. Ray.Transform = function (ray, matrix) {
  2369. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2370. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2371. return new Ray(newOrigin, newDirection, ray.length);
  2372. };
  2373. return Ray;
  2374. })();
  2375. BABYLON.Ray = Ray;
  2376. (function (Space) {
  2377. Space[Space["LOCAL"] = 0] = "LOCAL";
  2378. Space[Space["WORLD"] = 1] = "WORLD";
  2379. })(BABYLON.Space || (BABYLON.Space = {}));
  2380. var Space = BABYLON.Space;
  2381. var Axis = (function () {
  2382. function Axis() {
  2383. }
  2384. Axis.X = new Vector3(1, 0, 0);
  2385. Axis.Y = new Vector3(0, 1, 0);
  2386. Axis.Z = new Vector3(0, 0, 1);
  2387. return Axis;
  2388. })();
  2389. BABYLON.Axis = Axis;
  2390. ;
  2391. var BezierCurve = (function () {
  2392. function BezierCurve() {
  2393. }
  2394. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2395. // Extract X (which is equal to time here)
  2396. var f0 = 1 - 3 * x2 + 3 * x1;
  2397. var f1 = 3 * x2 - 6 * x1;
  2398. var f2 = 3 * x1;
  2399. var refinedT = t;
  2400. for (var i = 0; i < 5; i++) {
  2401. var refinedT2 = refinedT * refinedT;
  2402. var refinedT3 = refinedT2 * refinedT;
  2403. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2404. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2405. refinedT -= (x - t) * slope;
  2406. refinedT = Math.min(1, Math.max(0, refinedT));
  2407. }
  2408. // Resolve cubic bezier for the given x
  2409. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2410. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2411. Math.pow(refinedT, 3);
  2412. };
  2413. return BezierCurve;
  2414. })();
  2415. BABYLON.BezierCurve = BezierCurve;
  2416. (function (Orientation) {
  2417. Orientation[Orientation["CW"] = 0] = "CW";
  2418. Orientation[Orientation["CCW"] = 1] = "CCW";
  2419. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2420. var Orientation = BABYLON.Orientation;
  2421. var Angle = (function () {
  2422. function Angle(radians) {
  2423. var _this = this;
  2424. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2425. this.radians = function () { return _this._radians; };
  2426. this._radians = radians;
  2427. if (this._radians < 0)
  2428. this._radians += (2 * Math.PI);
  2429. }
  2430. Angle.BetweenTwoPoints = function (a, b) {
  2431. var delta = b.subtract(a);
  2432. var theta = Math.atan2(delta.y, delta.x);
  2433. return new Angle(theta);
  2434. };
  2435. Angle.FromRadians = function (radians) {
  2436. return new Angle(radians);
  2437. };
  2438. Angle.FromDegrees = function (degrees) {
  2439. return new Angle(degrees * Math.PI / 180);
  2440. };
  2441. return Angle;
  2442. })();
  2443. BABYLON.Angle = Angle;
  2444. var Arc2 = (function () {
  2445. function Arc2(startPoint, midPoint, endPoint) {
  2446. this.startPoint = startPoint;
  2447. this.midPoint = midPoint;
  2448. this.endPoint = endPoint;
  2449. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2450. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2451. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2452. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2453. 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);
  2454. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2455. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2456. var a1 = this.startAngle.degrees();
  2457. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2458. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2459. // angles correction
  2460. if (a2 - a1 > +180.0)
  2461. a2 -= 360.0;
  2462. if (a2 - a1 < -180.0)
  2463. a2 += 360.0;
  2464. if (a3 - a2 > +180.0)
  2465. a3 -= 360.0;
  2466. if (a3 - a2 < -180.0)
  2467. a3 += 360.0;
  2468. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2469. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2470. }
  2471. return Arc2;
  2472. })();
  2473. BABYLON.Arc2 = Arc2;
  2474. var PathCursor = (function () {
  2475. function PathCursor(path) {
  2476. this.path = path;
  2477. this._onchange = new Array();
  2478. this.value = 0;
  2479. this.animations = new Array();
  2480. }
  2481. PathCursor.prototype.getPoint = function () {
  2482. var point = this.path.getPointAtLengthPosition(this.value);
  2483. return new Vector3(point.x, 0, point.y);
  2484. };
  2485. PathCursor.prototype.moveAhead = function (step) {
  2486. if (step === void 0) { step = 0.002; }
  2487. this.move(step);
  2488. return this;
  2489. };
  2490. PathCursor.prototype.moveBack = function (step) {
  2491. if (step === void 0) { step = 0.002; }
  2492. this.move(-step);
  2493. return this;
  2494. };
  2495. PathCursor.prototype.move = function (step) {
  2496. if (Math.abs(step) > 1) {
  2497. throw "step size should be less than 1.";
  2498. }
  2499. this.value += step;
  2500. this.ensureLimits();
  2501. this.raiseOnChange();
  2502. return this;
  2503. };
  2504. PathCursor.prototype.ensureLimits = function () {
  2505. while (this.value > 1) {
  2506. this.value -= 1;
  2507. }
  2508. while (this.value < 0) {
  2509. this.value += 1;
  2510. }
  2511. return this;
  2512. };
  2513. // used by animation engine
  2514. PathCursor.prototype.markAsDirty = function (propertyName) {
  2515. this.ensureLimits();
  2516. this.raiseOnChange();
  2517. return this;
  2518. };
  2519. PathCursor.prototype.raiseOnChange = function () {
  2520. var _this = this;
  2521. this._onchange.forEach(function (f) { return f(_this); });
  2522. return this;
  2523. };
  2524. PathCursor.prototype.onchange = function (f) {
  2525. this._onchange.push(f);
  2526. return this;
  2527. };
  2528. return PathCursor;
  2529. })();
  2530. BABYLON.PathCursor = PathCursor;
  2531. var Path2 = (function () {
  2532. function Path2(x, y) {
  2533. this._points = new Array();
  2534. this._length = 0;
  2535. this.closed = false;
  2536. this._points.push(new Vector2(x, y));
  2537. }
  2538. Path2.prototype.addLineTo = function (x, y) {
  2539. if (closed) {
  2540. BABYLON.Tools.Error("cannot add lines to closed paths");
  2541. return this;
  2542. }
  2543. var newPoint = new Vector2(x, y);
  2544. var previousPoint = this._points[this._points.length - 1];
  2545. this._points.push(newPoint);
  2546. this._length += newPoint.subtract(previousPoint).length();
  2547. return this;
  2548. };
  2549. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2550. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2551. if (closed) {
  2552. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2553. return this;
  2554. }
  2555. var startPoint = this._points[this._points.length - 1];
  2556. var midPoint = new Vector2(midX, midY);
  2557. var endPoint = new Vector2(endX, endY);
  2558. var arc = new Arc2(startPoint, midPoint, endPoint);
  2559. var increment = arc.angle.radians() / numberOfSegments;
  2560. if (arc.orientation === Orientation.CW)
  2561. increment *= -1;
  2562. var currentAngle = arc.startAngle.radians() + increment;
  2563. for (var i = 0; i < numberOfSegments; i++) {
  2564. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2565. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2566. this.addLineTo(x, y);
  2567. currentAngle += increment;
  2568. }
  2569. return this;
  2570. };
  2571. Path2.prototype.close = function () {
  2572. this.closed = true;
  2573. return this;
  2574. };
  2575. Path2.prototype.length = function () {
  2576. var result = this._length;
  2577. if (!this.closed) {
  2578. var lastPoint = this._points[this._points.length - 1];
  2579. var firstPoint = this._points[0];
  2580. result += (firstPoint.subtract(lastPoint).length());
  2581. }
  2582. return result;
  2583. };
  2584. Path2.prototype.getPoints = function () {
  2585. return this._points;
  2586. };
  2587. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2588. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2589. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2590. return Vector2.Zero();
  2591. }
  2592. var lengthPosition = normalizedLengthPosition * this.length();
  2593. var previousOffset = 0;
  2594. for (var i = 0; i < this._points.length; i++) {
  2595. var j = (i + 1) % this._points.length;
  2596. var a = this._points[i];
  2597. var b = this._points[j];
  2598. var bToA = b.subtract(a);
  2599. var nextOffset = (bToA.length() + previousOffset);
  2600. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2601. var dir = bToA.normalize();
  2602. var localOffset = lengthPosition - previousOffset;
  2603. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2604. }
  2605. previousOffset = nextOffset;
  2606. }
  2607. BABYLON.Tools.Error("internal error");
  2608. return Vector2.Zero();
  2609. };
  2610. Path2.StartingAt = function (x, y) {
  2611. return new Path2(x, y);
  2612. };
  2613. return Path2;
  2614. })();
  2615. BABYLON.Path2 = Path2;
  2616. var Path3D = (function () {
  2617. function Path3D(path, firstNormal) {
  2618. this.path = path;
  2619. this._curve = new Array();
  2620. this._distances = new Array();
  2621. this._tangents = new Array();
  2622. this._normals = new Array();
  2623. this._binormals = new Array();
  2624. for (var p = 0; p < path.length; p++) {
  2625. this._curve[p] = path[p].clone(); // hard copy
  2626. }
  2627. this._compute(firstNormal);
  2628. }
  2629. Path3D.prototype.getCurve = function () {
  2630. return this._curve;
  2631. };
  2632. Path3D.prototype.getTangents = function () {
  2633. return this._tangents;
  2634. };
  2635. Path3D.prototype.getNormals = function () {
  2636. return this._normals;
  2637. };
  2638. Path3D.prototype.getBinormals = function () {
  2639. return this._binormals;
  2640. };
  2641. Path3D.prototype.getDistances = function () {
  2642. return this._distances;
  2643. };
  2644. Path3D.prototype.update = function (path, firstNormal) {
  2645. for (var p = 0; p < path.length; p++) {
  2646. this._curve[p].x = path[p].x;
  2647. this._curve[p].y = path[p].y;
  2648. this._curve[p].z = path[p].z;
  2649. }
  2650. this._compute(firstNormal);
  2651. return this;
  2652. };
  2653. // private function compute() : computes tangents, normals and binormals
  2654. Path3D.prototype._compute = function (firstNormal) {
  2655. var l = this._curve.length;
  2656. // first and last tangents
  2657. this._tangents[0] = this._getFirstNonNullVector(0);
  2658. this._tangents[0].normalize();
  2659. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2660. this._tangents[l - 1].normalize();
  2661. // normals and binormals at first point : arbitrary vector with _normalVector()
  2662. var tg0 = this._tangents[0];
  2663. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2664. this._normals[0] = pp0;
  2665. this._normals[0].normalize();
  2666. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2667. this._binormals[0].normalize();
  2668. this._distances[0] = 0;
  2669. // normals and binormals : next points
  2670. var prev; // previous vector (segment)
  2671. var cur; // current vector (segment)
  2672. var curTang; // current tangent
  2673. var prevNorm; // previous normal
  2674. var prevBinor; // previous binormal
  2675. for (var i = 1; i < l; i++) {
  2676. // tangents
  2677. prev = this._getLastNonNullVector(i);
  2678. if (i < l - 1) {
  2679. cur = this._getFirstNonNullVector(i);
  2680. this._tangents[i] = prev.add(cur);
  2681. this._tangents[i].normalize();
  2682. }
  2683. this._distances[i] = this._distances[i - 1] + prev.length();
  2684. // normals and binormals
  2685. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2686. curTang = this._tangents[i];
  2687. prevNorm = this._normals[i - 1];
  2688. prevBinor = this._binormals[i - 1];
  2689. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2690. this._normals[i].normalize();
  2691. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2692. this._binormals[i].normalize();
  2693. }
  2694. };
  2695. // private function getFirstNonNullVector(index)
  2696. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2697. Path3D.prototype._getFirstNonNullVector = function (index) {
  2698. var i = 1;
  2699. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2700. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2701. i++;
  2702. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2703. }
  2704. return nNVector;
  2705. };
  2706. // private function getLastNonNullVector(index)
  2707. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2708. Path3D.prototype._getLastNonNullVector = function (index) {
  2709. var i = 1;
  2710. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2711. while (nLVector.length() == 0 && index > i + 1) {
  2712. i++;
  2713. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2714. }
  2715. return nLVector;
  2716. };
  2717. // private function normalVector(v0, vt, va) :
  2718. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2719. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2720. Path3D.prototype._normalVector = function (v0, vt, va) {
  2721. var normal0;
  2722. if (va === undefined || va === null) {
  2723. var point;
  2724. if (vt.y !== 1) {
  2725. point = new Vector3(0, -1, 0);
  2726. }
  2727. else if (vt.x !== 1) {
  2728. point = new Vector3(1, 0, 0);
  2729. }
  2730. else if (vt.z !== 1) {
  2731. point = new Vector3(0, 0, 1);
  2732. }
  2733. normal0 = Vector3.Cross(vt, point);
  2734. }
  2735. else {
  2736. normal0 = Vector3.Cross(vt, va);
  2737. Vector3.CrossToRef(normal0, vt, normal0);
  2738. }
  2739. normal0.normalize();
  2740. return normal0;
  2741. };
  2742. return Path3D;
  2743. })();
  2744. BABYLON.Path3D = Path3D;
  2745. var Curve3 = (function () {
  2746. function Curve3(points) {
  2747. this._length = 0;
  2748. this._points = points;
  2749. this._length = this._computeLength(points);
  2750. }
  2751. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2752. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2753. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2754. var bez = new Array();
  2755. var equation = function (t, val0, val1, val2) {
  2756. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2757. return res;
  2758. };
  2759. for (var i = 0; i <= nbPoints; i++) {
  2760. 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)));
  2761. }
  2762. return new Curve3(bez);
  2763. };
  2764. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2765. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2766. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2767. var bez = new Array();
  2768. var equation = function (t, val0, val1, val2, val3) {
  2769. 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;
  2770. return res;
  2771. };
  2772. for (var i = 0; i <= nbPoints; i++) {
  2773. 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)));
  2774. }
  2775. return new Curve3(bez);
  2776. };
  2777. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2778. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2779. var hermite = new Array();
  2780. var step = 1 / nbPoints;
  2781. for (var i = 0; i <= nbPoints; i++) {
  2782. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2783. }
  2784. return new Curve3(hermite);
  2785. };
  2786. Curve3.prototype.getPoints = function () {
  2787. return this._points;
  2788. };
  2789. Curve3.prototype.length = function () {
  2790. return this._length;
  2791. };
  2792. Curve3.prototype.continue = function (curve) {
  2793. var lastPoint = this._points[this._points.length - 1];
  2794. var continuedPoints = this._points.slice();
  2795. var curvePoints = curve.getPoints();
  2796. for (var i = 1; i < curvePoints.length; i++) {
  2797. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2798. }
  2799. var continuedCurve = new Curve3(continuedPoints);
  2800. return continuedCurve;
  2801. };
  2802. Curve3.prototype._computeLength = function (path) {
  2803. var l = 0;
  2804. for (var i = 1; i < path.length; i++) {
  2805. l += (path[i].subtract(path[i - 1])).length();
  2806. }
  2807. return l;
  2808. };
  2809. return Curve3;
  2810. })();
  2811. BABYLON.Curve3 = Curve3;
  2812. // Vertex formats
  2813. var PositionNormalVertex = (function () {
  2814. function PositionNormalVertex(position, normal) {
  2815. if (position === void 0) { position = Vector3.Zero(); }
  2816. if (normal === void 0) { normal = Vector3.Up(); }
  2817. this.position = position;
  2818. this.normal = normal;
  2819. }
  2820. PositionNormalVertex.prototype.clone = function () {
  2821. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2822. };
  2823. return PositionNormalVertex;
  2824. })();
  2825. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2826. var PositionNormalTextureVertex = (function () {
  2827. function PositionNormalTextureVertex(position, normal, uv) {
  2828. if (position === void 0) { position = Vector3.Zero(); }
  2829. if (normal === void 0) { normal = Vector3.Up(); }
  2830. if (uv === void 0) { uv = Vector2.Zero(); }
  2831. this.position = position;
  2832. this.normal = normal;
  2833. this.uv = uv;
  2834. }
  2835. PositionNormalTextureVertex.prototype.clone = function () {
  2836. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2837. };
  2838. return PositionNormalTextureVertex;
  2839. })();
  2840. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2841. // SIMD
  2842. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2843. var previousInvertToRef = Matrix.prototype.invertToRef;
  2844. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2845. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2846. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2847. var SIMDHelper = (function () {
  2848. function SIMDHelper() {
  2849. }
  2850. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2851. get: function () {
  2852. return SIMDHelper._isEnabled;
  2853. },
  2854. enumerable: true,
  2855. configurable: true
  2856. });
  2857. SIMDHelper.DisableSIMD = function () {
  2858. // Replace functions
  2859. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2860. Matrix.prototype.invertToRef = previousInvertToRef;
  2861. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2862. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2863. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2864. SIMDHelper._isEnabled = false;
  2865. };
  2866. SIMDHelper.EnableSIMD = function () {
  2867. if (window.SIMD === undefined) {
  2868. return;
  2869. }
  2870. // Replace functions
  2871. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2872. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2873. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2874. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2875. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2876. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2877. get: function () { return this._data[0]; },
  2878. set: function (value) {
  2879. if (!this._data) {
  2880. this._data = new Float32Array(3);
  2881. }
  2882. this._data[0] = value;
  2883. }
  2884. });
  2885. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2886. get: function () { return this._data[1]; },
  2887. set: function (value) {
  2888. this._data[1] = value;
  2889. }
  2890. });
  2891. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2892. get: function () { return this._data[2]; },
  2893. set: function (value) {
  2894. this._data[2] = value;
  2895. }
  2896. });
  2897. SIMDHelper._isEnabled = true;
  2898. };
  2899. SIMDHelper._isEnabled = false;
  2900. return SIMDHelper;
  2901. })();
  2902. BABYLON.SIMDHelper = SIMDHelper;
  2903. if (window.SIMD !== undefined && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  2904. SIMDHelper.EnableSIMD();
  2905. }
  2906. })(BABYLON || (BABYLON = {}));
  2907. //# sourceMappingURL=babylon.math.js.map
  2908. var BABYLON;
  2909. (function (BABYLON) {
  2910. var Database = (function () {
  2911. function Database(urlToScene, callbackManifestChecked) {
  2912. // Handling various flavors of prefixed version of IndexedDB
  2913. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2914. this.callbackManifestChecked = callbackManifestChecked;
  2915. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  2916. this.db = null;
  2917. this.enableSceneOffline = false;
  2918. this.enableTexturesOffline = false;
  2919. this.manifestVersionFound = 0;
  2920. this.mustUpdateRessources = false;
  2921. this.hasReachedQuota = false;
  2922. this.checkManifestFile();
  2923. }
  2924. Database.prototype.checkManifestFile = function () {
  2925. var _this = this;
  2926. function noManifestFile() {
  2927. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  2928. that.enableSceneOffline = false;
  2929. that.enableTexturesOffline = false;
  2930. that.callbackManifestChecked(false);
  2931. }
  2932. var that = this;
  2933. var manifestURL = this.currentSceneUrl + ".manifest";
  2934. var xhr = new XMLHttpRequest();
  2935. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2936. xhr.open("GET", manifestURLTimeStamped, true);
  2937. xhr.addEventListener("load", function () {
  2938. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2939. try {
  2940. var manifestFile = JSON.parse(xhr.response);
  2941. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2942. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2943. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2944. _this.manifestVersionFound = manifestFile.version;
  2945. }
  2946. if (_this.callbackManifestChecked) {
  2947. _this.callbackManifestChecked(true);
  2948. }
  2949. }
  2950. catch (ex) {
  2951. noManifestFile();
  2952. }
  2953. }
  2954. else {
  2955. noManifestFile();
  2956. }
  2957. }, false);
  2958. xhr.addEventListener("error", function (event) {
  2959. noManifestFile();
  2960. }, false);
  2961. try {
  2962. xhr.send();
  2963. }
  2964. catch (ex) {
  2965. BABYLON.Tools.Error("Error on XHR send request.");
  2966. that.callbackManifestChecked(false);
  2967. }
  2968. };
  2969. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2970. var _this = this;
  2971. function handleError() {
  2972. that.isSupported = false;
  2973. if (errorCallback)
  2974. errorCallback();
  2975. }
  2976. var that = this;
  2977. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2978. // Your browser doesn't support IndexedDB
  2979. this.isSupported = false;
  2980. if (errorCallback)
  2981. errorCallback();
  2982. }
  2983. else {
  2984. // If the DB hasn't been opened or created yet
  2985. if (!this.db) {
  2986. this.hasReachedQuota = false;
  2987. this.isSupported = true;
  2988. var request = this.idbFactory.open("babylonjs", 1);
  2989. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  2990. request.onerror = function (event) {
  2991. handleError();
  2992. };
  2993. // executes when a version change transaction cannot complete due to other active transactions
  2994. request.onblocked = function (event) {
  2995. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  2996. handleError();
  2997. };
  2998. // DB has been opened successfully
  2999. request.onsuccess = function (event) {
  3000. _this.db = request.result;
  3001. successCallback();
  3002. };
  3003. // Initialization of the DB. Creating Scenes & Textures stores
  3004. request.onupgradeneeded = function (event) {
  3005. _this.db = (event.target).result;
  3006. try {
  3007. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3008. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3009. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3010. }
  3011. catch (ex) {
  3012. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3013. handleError();
  3014. }
  3015. };
  3016. }
  3017. else {
  3018. if (successCallback)
  3019. successCallback();
  3020. }
  3021. }
  3022. };
  3023. Database.prototype.loadImageFromDB = function (url, image) {
  3024. var _this = this;
  3025. var completeURL = Database.ReturnFullUrlLocation(url);
  3026. var saveAndLoadImage = function () {
  3027. if (!_this.hasReachedQuota && _this.db !== null) {
  3028. // the texture is not yet in the DB, let's try to save it
  3029. _this._saveImageIntoDBAsync(completeURL, image);
  3030. }
  3031. else {
  3032. image.src = url;
  3033. }
  3034. };
  3035. if (!this.mustUpdateRessources) {
  3036. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3037. }
  3038. else {
  3039. saveAndLoadImage();
  3040. }
  3041. };
  3042. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3043. if (this.isSupported && this.db !== null) {
  3044. var texture;
  3045. var transaction = this.db.transaction(["textures"]);
  3046. transaction.onabort = function (event) {
  3047. image.src = url;
  3048. };
  3049. transaction.oncomplete = function (event) {
  3050. var blobTextureURL;
  3051. if (texture) {
  3052. var URL = window.URL || window.webkitURL;
  3053. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3054. image.onerror = function () {
  3055. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3056. image.src = url;
  3057. };
  3058. image.src = blobTextureURL;
  3059. }
  3060. else {
  3061. notInDBCallback();
  3062. }
  3063. };
  3064. var getRequest = transaction.objectStore("textures").get(url);
  3065. getRequest.onsuccess = function (event) {
  3066. texture = (event.target).result;
  3067. };
  3068. getRequest.onerror = function (event) {
  3069. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3070. image.src = url;
  3071. };
  3072. }
  3073. else {
  3074. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3075. image.src = url;
  3076. }
  3077. };
  3078. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3079. var _this = this;
  3080. if (this.isSupported) {
  3081. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3082. var generateBlobUrl = function () {
  3083. var blobTextureURL;
  3084. if (blob) {
  3085. var URL = window.URL || window.webkitURL;
  3086. try {
  3087. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3088. }
  3089. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3090. catch (ex) {
  3091. blobTextureURL = URL.createObjectURL(blob);
  3092. }
  3093. }
  3094. image.src = blobTextureURL;
  3095. };
  3096. if (Database.isUASupportingBlobStorage) {
  3097. var xhr = new XMLHttpRequest(), blob;
  3098. xhr.open("GET", url, true);
  3099. xhr.responseType = "blob";
  3100. xhr.addEventListener("load", function () {
  3101. if (xhr.status === 200) {
  3102. // Blob as response (XHR2)
  3103. blob = xhr.response;
  3104. var transaction = _this.db.transaction(["textures"], "readwrite");
  3105. // the transaction could abort because of a QuotaExceededError error
  3106. transaction.onabort = function (event) {
  3107. try {
  3108. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3109. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3110. this.hasReachedQuota = true;
  3111. }
  3112. }
  3113. catch (ex) { }
  3114. generateBlobUrl();
  3115. };
  3116. transaction.oncomplete = function (event) {
  3117. generateBlobUrl();
  3118. };
  3119. var newTexture = { textureUrl: url, data: blob };
  3120. try {
  3121. // Put the blob into the dabase
  3122. var addRequest = transaction.objectStore("textures").put(newTexture);
  3123. addRequest.onsuccess = function (event) {
  3124. };
  3125. addRequest.onerror = function (event) {
  3126. generateBlobUrl();
  3127. };
  3128. }
  3129. catch (ex) {
  3130. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3131. if (ex.code === 25) {
  3132. Database.isUASupportingBlobStorage = false;
  3133. }
  3134. image.src = url;
  3135. }
  3136. }
  3137. else {
  3138. image.src = url;
  3139. }
  3140. }, false);
  3141. xhr.addEventListener("error", function (event) {
  3142. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3143. image.src = url;
  3144. }, false);
  3145. xhr.send();
  3146. }
  3147. else {
  3148. image.src = url;
  3149. }
  3150. }
  3151. else {
  3152. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3153. image.src = url;
  3154. }
  3155. };
  3156. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3157. var _this = this;
  3158. var updateVersion = function (event) {
  3159. // the version is not yet in the DB or we need to update it
  3160. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3161. };
  3162. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3163. };
  3164. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3165. var _this = this;
  3166. if (this.isSupported) {
  3167. var version;
  3168. try {
  3169. var transaction = this.db.transaction(["versions"]);
  3170. transaction.oncomplete = function (event) {
  3171. if (version) {
  3172. // If the version in the JSON file is > than the version in DB
  3173. if (_this.manifestVersionFound > version.data) {
  3174. _this.mustUpdateRessources = true;
  3175. updateInDBCallback();
  3176. }
  3177. else {
  3178. callback(version.data);
  3179. }
  3180. }
  3181. else {
  3182. _this.mustUpdateRessources = true;
  3183. updateInDBCallback();
  3184. }
  3185. };
  3186. transaction.onabort = function (event) {
  3187. callback(-1);
  3188. };
  3189. var getRequest = transaction.objectStore("versions").get(url);
  3190. getRequest.onsuccess = function (event) {
  3191. version = (event.target).result;
  3192. };
  3193. getRequest.onerror = function (event) {
  3194. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3195. callback(-1);
  3196. };
  3197. }
  3198. catch (ex) {
  3199. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3200. callback(-1);
  3201. }
  3202. }
  3203. else {
  3204. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3205. callback(-1);
  3206. }
  3207. };
  3208. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3209. var _this = this;
  3210. if (this.isSupported && !this.hasReachedQuota) {
  3211. try {
  3212. // Open a transaction to the database
  3213. var transaction = this.db.transaction(["versions"], "readwrite");
  3214. // the transaction could abort because of a QuotaExceededError error
  3215. transaction.onabort = function (event) {
  3216. try {
  3217. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3218. _this.hasReachedQuota = true;
  3219. }
  3220. }
  3221. catch (ex) { }
  3222. callback(-1);
  3223. };
  3224. transaction.oncomplete = function (event) {
  3225. callback(_this.manifestVersionFound);
  3226. };
  3227. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3228. // Put the scene into the database
  3229. var addRequest = transaction.objectStore("versions").put(newVersion);
  3230. addRequest.onsuccess = function (event) {
  3231. };
  3232. addRequest.onerror = function (event) {
  3233. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3234. };
  3235. }
  3236. catch (ex) {
  3237. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3238. callback(-1);
  3239. }
  3240. }
  3241. else {
  3242. callback(-1);
  3243. }
  3244. };
  3245. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3246. var _this = this;
  3247. var completeUrl = Database.ReturnFullUrlLocation(url);
  3248. var saveAndLoadFile = function (event) {
  3249. // the scene is not yet in the DB, let's try to save it
  3250. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3251. };
  3252. this._checkVersionFromDB(completeUrl, function (version) {
  3253. if (version !== -1) {
  3254. if (!_this.mustUpdateRessources) {
  3255. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3256. }
  3257. else {
  3258. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3259. }
  3260. }
  3261. else {
  3262. errorCallback();
  3263. }
  3264. });
  3265. };
  3266. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3267. if (this.isSupported) {
  3268. var targetStore;
  3269. if (url.indexOf(".babylon") !== -1) {
  3270. targetStore = "scenes";
  3271. }
  3272. else {
  3273. targetStore = "textures";
  3274. }
  3275. var file;
  3276. var transaction = this.db.transaction([targetStore]);
  3277. transaction.oncomplete = function (event) {
  3278. if (file) {
  3279. callback(file.data);
  3280. }
  3281. else {
  3282. notInDBCallback();
  3283. }
  3284. };
  3285. transaction.onabort = function (event) {
  3286. notInDBCallback();
  3287. };
  3288. var getRequest = transaction.objectStore(targetStore).get(url);
  3289. getRequest.onsuccess = function (event) {
  3290. file = (event.target).result;
  3291. };
  3292. getRequest.onerror = function (event) {
  3293. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3294. notInDBCallback();
  3295. };
  3296. }
  3297. else {
  3298. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3299. callback();
  3300. }
  3301. };
  3302. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3303. var _this = this;
  3304. if (this.isSupported) {
  3305. var targetStore;
  3306. if (url.indexOf(".babylon") !== -1) {
  3307. targetStore = "scenes";
  3308. }
  3309. else {
  3310. targetStore = "textures";
  3311. }
  3312. // Create XHR
  3313. var xhr = new XMLHttpRequest(), fileData;
  3314. xhr.open("GET", url, true);
  3315. if (useArrayBuffer) {
  3316. xhr.responseType = "arraybuffer";
  3317. }
  3318. xhr.onprogress = progressCallback;
  3319. xhr.addEventListener("load", function () {
  3320. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3321. // Blob as response (XHR2)
  3322. //fileData = xhr.responseText;
  3323. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3324. if (!_this.hasReachedQuota) {
  3325. // Open a transaction to the database
  3326. var transaction = _this.db.transaction([targetStore], "readwrite");
  3327. // the transaction could abort because of a QuotaExceededError error
  3328. transaction.onabort = function (event) {
  3329. try {
  3330. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3331. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3332. this.hasReachedQuota = true;
  3333. }
  3334. }
  3335. catch (ex) { }
  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. // Get some informations.
  3455. switch (header.image_type) {
  3456. case TGATools._TYPE_RLE_INDEXED:
  3457. use_rle = true;
  3458. case TGATools._TYPE_INDEXED:
  3459. use_pal = true;
  3460. break;
  3461. case TGATools._TYPE_RLE_RGB:
  3462. use_rle = true;
  3463. case TGATools._TYPE_RGB:
  3464. use_rgb = true;
  3465. break;
  3466. case TGATools._TYPE_RLE_GREY:
  3467. use_rle = true;
  3468. case TGATools._TYPE_GREY:
  3469. use_grey = true;
  3470. break;
  3471. }
  3472. var pixel_data;
  3473. var numAlphaBits = header.flags & 0xf;
  3474. var pixel_size = header.pixel_size >> 3;
  3475. var pixel_total = header.width * header.height * pixel_size;
  3476. // Read palettes
  3477. var palettes;
  3478. if (use_pal) {
  3479. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3480. }
  3481. // Read LRE
  3482. if (use_rle) {
  3483. pixel_data = new Uint8Array(pixel_total);
  3484. var c, count, i;
  3485. var localOffset = 0;
  3486. var pixels = new Uint8Array(pixel_size);
  3487. while (offset < pixel_total && localOffset < pixel_total) {
  3488. c = data[offset++];
  3489. count = (c & 0x7f) + 1;
  3490. // RLE pixels
  3491. if (c & 0x80) {
  3492. // Bind pixel tmp array
  3493. for (i = 0; i < pixel_size; ++i) {
  3494. pixels[i] = data[offset++];
  3495. }
  3496. // Copy pixel array
  3497. for (i = 0; i < count; ++i) {
  3498. pixel_data.set(pixels, localOffset + i * pixel_size);
  3499. }
  3500. localOffset += pixel_size * count;
  3501. }
  3502. else {
  3503. count *= pixel_size;
  3504. for (i = 0; i < count; ++i) {
  3505. pixel_data[localOffset + i] = data[offset++];
  3506. }
  3507. localOffset += count;
  3508. }
  3509. }
  3510. }
  3511. else {
  3512. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3513. }
  3514. // Load to texture
  3515. var x_start, y_start, x_step, y_step, y_end, x_end;
  3516. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3517. default:
  3518. case TGATools._ORIGIN_UL:
  3519. x_start = 0;
  3520. x_step = 1;
  3521. x_end = header.width;
  3522. y_start = 0;
  3523. y_step = 1;
  3524. y_end = header.height;
  3525. break;
  3526. case TGATools._ORIGIN_BL:
  3527. x_start = 0;
  3528. x_step = 1;
  3529. x_end = header.width;
  3530. y_start = header.height - 1;
  3531. y_step = -1;
  3532. y_end = -1;
  3533. break;
  3534. case TGATools._ORIGIN_UR:
  3535. x_start = header.width - 1;
  3536. x_step = -1;
  3537. x_end = -1;
  3538. y_start = 0;
  3539. y_step = 1;
  3540. y_end = header.height;
  3541. break;
  3542. case TGATools._ORIGIN_BR:
  3543. x_start = header.width - 1;
  3544. x_step = -1;
  3545. x_end = -1;
  3546. y_start = header.height - 1;
  3547. y_step = -1;
  3548. y_end = -1;
  3549. break;
  3550. }
  3551. // Load the specify method
  3552. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3553. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3554. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3555. };
  3556. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3557. var image = pixel_data, colormap = palettes;
  3558. var width = header.width, height = header.height;
  3559. var color, i = 0, x, y;
  3560. var imageData = new Uint8Array(width * height * 4);
  3561. for (y = y_start; y !== y_end; y += y_step) {
  3562. for (x = x_start; x !== x_end; x += x_step, i++) {
  3563. color = image[i];
  3564. imageData[(x + width * y) * 4 + 3] = 255;
  3565. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3566. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3567. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3568. }
  3569. }
  3570. return imageData;
  3571. };
  3572. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3573. var image = pixel_data;
  3574. var width = header.width, height = header.height;
  3575. var color, i = 0, x, y;
  3576. var imageData = new Uint8Array(width * height * 4);
  3577. for (y = y_start; y !== y_end; y += y_step) {
  3578. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3579. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3580. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3581. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3582. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3583. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3584. }
  3585. }
  3586. return imageData;
  3587. };
  3588. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3589. var image = pixel_data;
  3590. var width = header.width, height = header.height;
  3591. var i = 0, x, y;
  3592. var imageData = new Uint8Array(width * height * 4);
  3593. for (y = y_start; y !== y_end; y += y_step) {
  3594. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3595. imageData[(x + width * y) * 4 + 3] = 255;
  3596. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3597. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3598. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3599. }
  3600. }
  3601. return imageData;
  3602. };
  3603. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3604. var image = pixel_data;
  3605. var width = header.width, height = header.height;
  3606. var i = 0, x, y;
  3607. var imageData = new Uint8Array(width * height * 4);
  3608. for (y = y_start; y !== y_end; y += y_step) {
  3609. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3610. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3611. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3612. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3613. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3614. }
  3615. }
  3616. return imageData;
  3617. };
  3618. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3619. var image = pixel_data;
  3620. var width = header.width, height = header.height;
  3621. var color, i = 0, x, y;
  3622. var imageData = new Uint8Array(width * height * 4);
  3623. for (y = y_start; y !== y_end; y += y_step) {
  3624. for (x = x_start; x !== x_end; x += x_step, i++) {
  3625. color = image[i];
  3626. imageData[(x + width * y) * 4 + 0] = color;
  3627. imageData[(x + width * y) * 4 + 1] = color;
  3628. imageData[(x + width * y) * 4 + 2] = color;
  3629. imageData[(x + width * y) * 4 + 3] = 255;
  3630. }
  3631. }
  3632. return imageData;
  3633. };
  3634. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3635. var image = pixel_data;
  3636. var width = header.width, height = header.height;
  3637. var i = 0, x, y;
  3638. var imageData = new Uint8Array(width * height * 4);
  3639. for (y = y_start; y !== y_end; y += y_step) {
  3640. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3641. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3642. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3643. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3644. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3645. }
  3646. }
  3647. return imageData;
  3648. };
  3649. TGATools._TYPE_NO_DATA = 0;
  3650. TGATools._TYPE_INDEXED = 1;
  3651. TGATools._TYPE_RGB = 2;
  3652. TGATools._TYPE_GREY = 3;
  3653. TGATools._TYPE_RLE_INDEXED = 9;
  3654. TGATools._TYPE_RLE_RGB = 10;
  3655. TGATools._TYPE_RLE_GREY = 11;
  3656. TGATools._ORIGIN_MASK = 0x30;
  3657. TGATools._ORIGIN_SHIFT = 0x04;
  3658. TGATools._ORIGIN_BL = 0x00;
  3659. TGATools._ORIGIN_BR = 0x01;
  3660. TGATools._ORIGIN_UL = 0x02;
  3661. TGATools._ORIGIN_UR = 0x03;
  3662. return TGATools;
  3663. })();
  3664. Internals.TGATools = TGATools;
  3665. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3666. })(BABYLON || (BABYLON = {}));
  3667. //# sourceMappingURL=babylon.tools.tga.js.map
  3668. var BABYLON;
  3669. (function (BABYLON) {
  3670. var Internals;
  3671. (function (Internals) {
  3672. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3673. // All values and structures referenced from:
  3674. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3675. var DDS_MAGIC = 0x20534444;
  3676. 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;
  3677. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3678. 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;
  3679. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3680. function FourCCToInt32(value) {
  3681. return value.charCodeAt(0) +
  3682. (value.charCodeAt(1) << 8) +
  3683. (value.charCodeAt(2) << 16) +
  3684. (value.charCodeAt(3) << 24);
  3685. }
  3686. function Int32ToFourCC(value) {
  3687. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3688. }
  3689. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3690. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3691. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3692. var headerLengthInt = 31; // The header length in 32 bit ints
  3693. // Offsets into the header array
  3694. var off_magic = 0;
  3695. var off_size = 1;
  3696. var off_flags = 2;
  3697. var off_height = 3;
  3698. var off_width = 4;
  3699. var off_mipmapCount = 7;
  3700. var off_pfFlags = 20;
  3701. var off_pfFourCC = 21;
  3702. var off_RGBbpp = 22;
  3703. var off_RMask = 23;
  3704. var off_GMask = 24;
  3705. var off_BMask = 25;
  3706. var off_AMask = 26;
  3707. var off_caps1 = 27;
  3708. var off_caps2 = 28;
  3709. ;
  3710. var DDSTools = (function () {
  3711. function DDSTools() {
  3712. }
  3713. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3714. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3715. var mipmapCount = 1;
  3716. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3717. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3718. }
  3719. return {
  3720. width: header[off_width],
  3721. height: header[off_height],
  3722. mipmapCount: mipmapCount,
  3723. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3724. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3725. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3726. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3727. };
  3728. };
  3729. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3730. var byteArray = new Uint8Array(dataLength);
  3731. var srcData = new Uint8Array(arrayBuffer);
  3732. var index = 0;
  3733. for (var y = height - 1; y >= 0; y--) {
  3734. for (var x = 0; x < width; x++) {
  3735. var srcPos = dataOffset + (x + y * width) * 4;
  3736. byteArray[index + 2] = srcData[srcPos];
  3737. byteArray[index + 1] = srcData[srcPos + 1];
  3738. byteArray[index] = srcData[srcPos + 2];
  3739. byteArray[index + 3] = srcData[srcPos + 3];
  3740. index += 4;
  3741. }
  3742. }
  3743. return byteArray;
  3744. };
  3745. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3746. var byteArray = new Uint8Array(dataLength);
  3747. var srcData = new Uint8Array(arrayBuffer);
  3748. var index = 0;
  3749. for (var y = height - 1; y >= 0; y--) {
  3750. for (var x = 0; x < width; x++) {
  3751. var srcPos = dataOffset + (x + y * width) * 3;
  3752. byteArray[index + 2] = srcData[srcPos];
  3753. byteArray[index + 1] = srcData[srcPos + 1];
  3754. byteArray[index] = srcData[srcPos + 2];
  3755. index += 3;
  3756. }
  3757. }
  3758. return byteArray;
  3759. };
  3760. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3761. var byteArray = new Uint8Array(dataLength);
  3762. var srcData = new Uint8Array(arrayBuffer);
  3763. var index = 0;
  3764. for (var y = height - 1; y >= 0; y--) {
  3765. for (var x = 0; x < width; x++) {
  3766. var srcPos = dataOffset + (x + y * width);
  3767. byteArray[index] = srcData[srcPos];
  3768. index++;
  3769. }
  3770. }
  3771. return byteArray;
  3772. };
  3773. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3774. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3775. if (header[off_magic] != DDS_MAGIC) {
  3776. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3777. return;
  3778. }
  3779. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3780. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3781. return;
  3782. }
  3783. if (info.isFourCC) {
  3784. fourCC = header[off_pfFourCC];
  3785. switch (fourCC) {
  3786. case FOURCC_DXT1:
  3787. blockBytes = 8;
  3788. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3789. break;
  3790. case FOURCC_DXT3:
  3791. blockBytes = 16;
  3792. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3793. break;
  3794. case FOURCC_DXT5:
  3795. blockBytes = 16;
  3796. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3797. break;
  3798. default:
  3799. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3800. return;
  3801. }
  3802. }
  3803. mipmapCount = 1;
  3804. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3805. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3806. }
  3807. var bpp = header[off_RGBbpp];
  3808. for (var face = 0; face < faces; face++) {
  3809. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3810. width = header[off_width];
  3811. height = header[off_height];
  3812. dataOffset = header[off_size] + 4;
  3813. for (i = 0; i < mipmapCount; ++i) {
  3814. if (info.isRGB) {
  3815. if (bpp == 24) {
  3816. dataLength = width * height * 3;
  3817. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3818. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3819. }
  3820. else {
  3821. dataLength = width * height * 4;
  3822. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3823. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3824. }
  3825. }
  3826. else if (info.isLuminance) {
  3827. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3828. var unpaddedRowSize = width;
  3829. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3830. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3831. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3832. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3833. }
  3834. else {
  3835. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3836. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3837. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3838. }
  3839. dataOffset += dataLength;
  3840. width *= 0.5;
  3841. height *= 0.5;
  3842. width = Math.max(1.0, width);
  3843. height = Math.max(1.0, height);
  3844. }
  3845. }
  3846. };
  3847. return DDSTools;
  3848. })();
  3849. Internals.DDSTools = DDSTools;
  3850. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3851. })(BABYLON || (BABYLON = {}));
  3852. //# sourceMappingURL=babylon.tools.dds.js.map
  3853. var BABYLON;
  3854. (function (BABYLON) {
  3855. var SmartArray = (function () {
  3856. function SmartArray(capacity) {
  3857. this.length = 0;
  3858. this._duplicateId = 0;
  3859. this.data = new Array(capacity);
  3860. this._id = SmartArray._GlobalId++;
  3861. }
  3862. SmartArray.prototype.push = function (value) {
  3863. this.data[this.length++] = value;
  3864. if (this.length > this.data.length) {
  3865. this.data.length *= 2;
  3866. }
  3867. if (!value.__smartArrayFlags) {
  3868. value.__smartArrayFlags = {};
  3869. }
  3870. value.__smartArrayFlags[this._id] = this._duplicateId;
  3871. };
  3872. SmartArray.prototype.pushNoDuplicate = function (value) {
  3873. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3874. return;
  3875. }
  3876. this.push(value);
  3877. };
  3878. SmartArray.prototype.sort = function (compareFn) {
  3879. this.data.sort(compareFn);
  3880. };
  3881. SmartArray.prototype.reset = function () {
  3882. this.length = 0;
  3883. this._duplicateId++;
  3884. };
  3885. SmartArray.prototype.concat = function (array) {
  3886. if (array.length === 0) {
  3887. return;
  3888. }
  3889. if (this.length + array.length > this.data.length) {
  3890. this.data.length = (this.length + array.length) * 2;
  3891. }
  3892. for (var index = 0; index < array.length; index++) {
  3893. this.data[this.length++] = (array.data || array)[index];
  3894. }
  3895. };
  3896. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3897. if (array.length === 0) {
  3898. return;
  3899. }
  3900. if (this.length + array.length > this.data.length) {
  3901. this.data.length = (this.length + array.length) * 2;
  3902. }
  3903. for (var index = 0; index < array.length; index++) {
  3904. var item = (array.data || array)[index];
  3905. this.pushNoDuplicate(item);
  3906. }
  3907. };
  3908. SmartArray.prototype.indexOf = function (value) {
  3909. var position = this.data.indexOf(value);
  3910. if (position >= this.length) {
  3911. return -1;
  3912. }
  3913. return position;
  3914. };
  3915. // Statics
  3916. SmartArray._GlobalId = 0;
  3917. return SmartArray;
  3918. })();
  3919. BABYLON.SmartArray = SmartArray;
  3920. })(BABYLON || (BABYLON = {}));
  3921. //# sourceMappingURL=babylon.smartArray.js.map
  3922. var BABYLON;
  3923. (function (BABYLON) {
  3924. var SmartCollection = (function () {
  3925. function SmartCollection(capacity) {
  3926. if (capacity === void 0) { capacity = 10; }
  3927. this.count = 0;
  3928. this._initialCapacity = capacity;
  3929. this.items = {};
  3930. this._keys = new Array(this._initialCapacity);
  3931. }
  3932. SmartCollection.prototype.add = function (key, item) {
  3933. if (this.items[key] != undefined) {
  3934. return -1;
  3935. }
  3936. this.items[key] = item;
  3937. //literal keys are always strings, but we keep source type of key in _keys array
  3938. this._keys[this.count++] = key;
  3939. if (this.count > this._keys.length) {
  3940. this._keys.length *= 2;
  3941. }
  3942. return this.count;
  3943. };
  3944. SmartCollection.prototype.remove = function (key) {
  3945. if (this.items[key] == undefined) {
  3946. return -1;
  3947. }
  3948. return this.removeItemOfIndex(this.indexOf(key));
  3949. };
  3950. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3951. if (index < this.count && index > -1) {
  3952. delete this.items[this._keys[index]];
  3953. //here, shifting by hand is better optimised than .splice
  3954. while (index < this.count) {
  3955. this._keys[index] = this._keys[index + 1];
  3956. index++;
  3957. }
  3958. }
  3959. else {
  3960. return -1;
  3961. }
  3962. return --this.count;
  3963. };
  3964. SmartCollection.prototype.indexOf = function (key) {
  3965. for (var i = 0; i !== this.count; i++) {
  3966. if (this._keys[i] === key) {
  3967. return i;
  3968. }
  3969. }
  3970. return -1;
  3971. };
  3972. SmartCollection.prototype.item = function (key) {
  3973. return this.items[key];
  3974. };
  3975. SmartCollection.prototype.getAllKeys = function () {
  3976. if (this.count > 0) {
  3977. var keys = new Array(this.count);
  3978. for (var i = 0; i < this.count; i++) {
  3979. keys[i] = this._keys[i];
  3980. }
  3981. return keys;
  3982. }
  3983. else {
  3984. return undefined;
  3985. }
  3986. };
  3987. SmartCollection.prototype.getKeyByIndex = function (index) {
  3988. if (index < this.count && index > -1) {
  3989. return this._keys[index];
  3990. }
  3991. else {
  3992. return undefined;
  3993. }
  3994. };
  3995. SmartCollection.prototype.getItemByIndex = function (index) {
  3996. if (index < this.count && index > -1) {
  3997. return this.items[this._keys[index]];
  3998. }
  3999. else {
  4000. return undefined;
  4001. }
  4002. };
  4003. SmartCollection.prototype.empty = function () {
  4004. if (this.count > 0) {
  4005. this.count = 0;
  4006. this.items = {};
  4007. this._keys = new Array(this._initialCapacity);
  4008. }
  4009. };
  4010. SmartCollection.prototype.forEach = function (block) {
  4011. var key;
  4012. for (key in this.items) {
  4013. if (this.items.hasOwnProperty(key)) {
  4014. block(this.items[key]);
  4015. }
  4016. }
  4017. };
  4018. return SmartCollection;
  4019. })();
  4020. BABYLON.SmartCollection = SmartCollection;
  4021. })(BABYLON || (BABYLON = {}));
  4022. //# sourceMappingURL=babylon.smartCollection.js.map
  4023. var BABYLON;
  4024. (function (BABYLON) {
  4025. // Screenshots
  4026. var screenshotCanvas;
  4027. var cloneValue = function (source, destinationObject) {
  4028. if (!source)
  4029. return null;
  4030. if (source instanceof BABYLON.Mesh) {
  4031. return null;
  4032. }
  4033. if (source instanceof BABYLON.SubMesh) {
  4034. return source.clone(destinationObject);
  4035. }
  4036. else if (source.clone) {
  4037. return source.clone();
  4038. }
  4039. return null;
  4040. };
  4041. var Tools = (function () {
  4042. function Tools() {
  4043. }
  4044. Tools.SetImmediate = function (action) {
  4045. if (window.setImmediate) {
  4046. window.setImmediate(action);
  4047. }
  4048. else {
  4049. setTimeout(action, 1);
  4050. }
  4051. };
  4052. Tools.GetFilename = function (path) {
  4053. var index = path.lastIndexOf("/");
  4054. if (index < 0)
  4055. return path;
  4056. return path.substring(index + 1);
  4057. };
  4058. Tools.GetDOMTextContent = function (element) {
  4059. var result = "";
  4060. var child = element.firstChild;
  4061. while (child) {
  4062. if (child.nodeType === 3) {
  4063. result += child.textContent;
  4064. }
  4065. child = child.nextSibling;
  4066. }
  4067. return result;
  4068. };
  4069. Tools.ToDegrees = function (angle) {
  4070. return angle * 180 / Math.PI;
  4071. };
  4072. Tools.ToRadians = function (angle) {
  4073. return angle * Math.PI / 180;
  4074. };
  4075. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4076. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4077. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4078. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4079. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4080. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4081. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4082. }
  4083. return {
  4084. minimum: minimum,
  4085. maximum: maximum
  4086. };
  4087. };
  4088. Tools.ExtractMinAndMax = function (positions, start, count) {
  4089. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4090. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4091. for (var index = start; index < start + count; index++) {
  4092. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4093. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4094. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4095. }
  4096. return {
  4097. minimum: minimum,
  4098. maximum: maximum
  4099. };
  4100. };
  4101. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4102. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4103. return undefined;
  4104. return Array.isArray(obj) ? obj : [obj];
  4105. };
  4106. // Misc.
  4107. Tools.GetPointerPrefix = function () {
  4108. var eventPrefix = "pointer";
  4109. // Check if hand.js is referenced or if the browser natively supports pointer events
  4110. if (!navigator.pointerEnabled) {
  4111. eventPrefix = "mouse";
  4112. }
  4113. return eventPrefix;
  4114. };
  4115. Tools.QueueNewFrame = function (func) {
  4116. if (window.requestAnimationFrame)
  4117. window.requestAnimationFrame(func);
  4118. else if (window.msRequestAnimationFrame)
  4119. window.msRequestAnimationFrame(func);
  4120. else if (window.webkitRequestAnimationFrame)
  4121. window.webkitRequestAnimationFrame(func);
  4122. else if (window.mozRequestAnimationFrame)
  4123. window.mozRequestAnimationFrame(func);
  4124. else if (window.oRequestAnimationFrame)
  4125. window.oRequestAnimationFrame(func);
  4126. else {
  4127. window.setTimeout(func, 16);
  4128. }
  4129. };
  4130. Tools.RequestFullscreen = function (element) {
  4131. if (element.requestFullscreen)
  4132. element.requestFullscreen();
  4133. else if (element.msRequestFullscreen)
  4134. element.msRequestFullscreen();
  4135. else if (element.webkitRequestFullscreen)
  4136. element.webkitRequestFullscreen();
  4137. else if (element.mozRequestFullScreen)
  4138. element.mozRequestFullScreen();
  4139. };
  4140. Tools.ExitFullscreen = function () {
  4141. if (document.exitFullscreen) {
  4142. document.exitFullscreen();
  4143. }
  4144. else if (document.mozCancelFullScreen) {
  4145. document.mozCancelFullScreen();
  4146. }
  4147. else if (document.webkitCancelFullScreen) {
  4148. document.webkitCancelFullScreen();
  4149. }
  4150. else if (document.msCancelFullScreen) {
  4151. document.msCancelFullScreen();
  4152. }
  4153. };
  4154. // External files
  4155. Tools.CleanUrl = function (url) {
  4156. url = url.replace(/#/mg, "%23");
  4157. return url;
  4158. };
  4159. Tools.LoadImage = function (url, onload, onerror, database) {
  4160. url = Tools.CleanUrl(url);
  4161. var img = new Image();
  4162. if (url.substr(0, 5) !== "data:")
  4163. img.crossOrigin = 'anonymous';
  4164. img.onload = function () {
  4165. onload(img);
  4166. };
  4167. img.onerror = function (err) {
  4168. onerror(img, err);
  4169. };
  4170. var noIndexedDB = function () {
  4171. img.src = url;
  4172. };
  4173. var loadFromIndexedDB = function () {
  4174. database.loadImageFromDB(url, img);
  4175. };
  4176. //ANY database to do!
  4177. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4178. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4179. }
  4180. else {
  4181. if (url.indexOf("file:") === -1) {
  4182. noIndexedDB();
  4183. }
  4184. else {
  4185. try {
  4186. var textureName = url.substring(5);
  4187. var blobURL;
  4188. try {
  4189. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4190. }
  4191. catch (ex) {
  4192. // Chrome doesn't support oneTimeOnly parameter
  4193. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4194. }
  4195. img.src = blobURL;
  4196. }
  4197. catch (e) {
  4198. Tools.Log("Error while trying to load texture: " + textureName);
  4199. img.src = null;
  4200. }
  4201. }
  4202. }
  4203. return img;
  4204. };
  4205. //ANY
  4206. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4207. url = Tools.CleanUrl(url);
  4208. var noIndexedDB = function () {
  4209. var request = new XMLHttpRequest();
  4210. var loadUrl = Tools.BaseUrl + url;
  4211. request.open('GET', loadUrl, true);
  4212. if (useArrayBuffer) {
  4213. request.responseType = "arraybuffer";
  4214. }
  4215. request.onprogress = progressCallBack;
  4216. request.onreadystatechange = function () {
  4217. if (request.readyState === 4) {
  4218. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4219. callback(!useArrayBuffer ? request.responseText : request.response);
  4220. }
  4221. else {
  4222. if (onError) {
  4223. onError();
  4224. }
  4225. else {
  4226. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4227. }
  4228. }
  4229. }
  4230. };
  4231. request.send(null);
  4232. };
  4233. var loadFromIndexedDB = function () {
  4234. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4235. };
  4236. if (url.indexOf("file:") !== -1) {
  4237. var fileName = url.substring(5);
  4238. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4239. }
  4240. else {
  4241. // Caching all files
  4242. if (database && database.enableSceneOffline) {
  4243. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4244. }
  4245. else {
  4246. noIndexedDB();
  4247. }
  4248. }
  4249. };
  4250. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4251. var reader = new FileReader();
  4252. reader.onload = function (e) {
  4253. //target doesn't have result from ts 1.3
  4254. callback(e.target['result']);
  4255. };
  4256. reader.onprogress = progressCallback;
  4257. reader.readAsDataURL(fileToLoad);
  4258. };
  4259. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4260. var reader = new FileReader();
  4261. reader.onerror = function (e) {
  4262. Tools.Log("Error while reading file: " + fileToLoad.name);
  4263. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4264. };
  4265. reader.onload = function (e) {
  4266. //target doesn't have result from ts 1.3
  4267. callback(e.target['result']);
  4268. };
  4269. reader.onprogress = progressCallBack;
  4270. if (!useArrayBuffer) {
  4271. // Asynchronous read
  4272. reader.readAsText(fileToLoad);
  4273. }
  4274. else {
  4275. reader.readAsArrayBuffer(fileToLoad);
  4276. }
  4277. };
  4278. // Misc.
  4279. Tools.Clamp = function (value, min, max) {
  4280. if (min === void 0) { min = 0; }
  4281. if (max === void 0) { max = 1; }
  4282. return Math.min(max, Math.max(min, value));
  4283. };
  4284. // Returns -1 when value is a negative number and
  4285. // +1 when value is a positive number.
  4286. Tools.Sign = function (value) {
  4287. value = +value; // convert to a number
  4288. if (value === 0 || isNaN(value))
  4289. return value;
  4290. return value > 0 ? 1 : -1;
  4291. };
  4292. Tools.Format = function (value, decimals) {
  4293. if (decimals === void 0) { decimals = 2; }
  4294. return value.toFixed(decimals);
  4295. };
  4296. Tools.CheckExtends = function (v, min, max) {
  4297. if (v.x < min.x)
  4298. min.x = v.x;
  4299. if (v.y < min.y)
  4300. min.y = v.y;
  4301. if (v.z < min.z)
  4302. min.z = v.z;
  4303. if (v.x > max.x)
  4304. max.x = v.x;
  4305. if (v.y > max.y)
  4306. max.y = v.y;
  4307. if (v.z > max.z)
  4308. max.z = v.z;
  4309. };
  4310. Tools.WithinEpsilon = function (a, b, epsilon) {
  4311. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4312. var num = a - b;
  4313. return -epsilon <= num && num <= epsilon;
  4314. };
  4315. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4316. for (var prop in source) {
  4317. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4318. continue;
  4319. }
  4320. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4321. continue;
  4322. }
  4323. var sourceValue = source[prop];
  4324. var typeOfSourceValue = typeof sourceValue;
  4325. if (typeOfSourceValue === "function") {
  4326. continue;
  4327. }
  4328. if (typeOfSourceValue === "object") {
  4329. if (sourceValue instanceof Array) {
  4330. destination[prop] = [];
  4331. if (sourceValue.length > 0) {
  4332. if (typeof sourceValue[0] == "object") {
  4333. for (var index = 0; index < sourceValue.length; index++) {
  4334. var clonedValue = cloneValue(sourceValue[index], destination);
  4335. if (destination[prop].indexOf(clonedValue) === -1) {
  4336. destination[prop].push(clonedValue);
  4337. }
  4338. }
  4339. }
  4340. else {
  4341. destination[prop] = sourceValue.slice(0);
  4342. }
  4343. }
  4344. }
  4345. else {
  4346. destination[prop] = cloneValue(sourceValue, destination);
  4347. }
  4348. }
  4349. else {
  4350. destination[prop] = sourceValue;
  4351. }
  4352. }
  4353. };
  4354. Tools.IsEmpty = function (obj) {
  4355. for (var i in obj) {
  4356. return false;
  4357. }
  4358. return true;
  4359. };
  4360. Tools.RegisterTopRootEvents = function (events) {
  4361. for (var index = 0; index < events.length; index++) {
  4362. var event = events[index];
  4363. window.addEventListener(event.name, event.handler, false);
  4364. try {
  4365. if (window.parent) {
  4366. window.parent.addEventListener(event.name, event.handler, false);
  4367. }
  4368. }
  4369. catch (e) {
  4370. }
  4371. }
  4372. };
  4373. Tools.UnregisterTopRootEvents = function (events) {
  4374. for (var index = 0; index < events.length; index++) {
  4375. var event = events[index];
  4376. window.removeEventListener(event.name, event.handler);
  4377. try {
  4378. if (window.parent) {
  4379. window.parent.removeEventListener(event.name, event.handler);
  4380. }
  4381. }
  4382. catch (e) {
  4383. }
  4384. }
  4385. };
  4386. Tools.DumpFramebuffer = function (width, height, engine) {
  4387. // Read the contents of the framebuffer
  4388. var numberOfChannelsByLine = width * 4;
  4389. var halfHeight = height / 2;
  4390. //Reading datas from WebGL
  4391. var data = engine.readPixels(0, 0, width, height);
  4392. //To flip image on Y axis.
  4393. for (var i = 0; i < halfHeight; i++) {
  4394. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4395. var currentCell = j + i * numberOfChannelsByLine;
  4396. var targetLine = height - i - 1;
  4397. var targetCell = j + targetLine * numberOfChannelsByLine;
  4398. var temp = data[currentCell];
  4399. data[currentCell] = data[targetCell];
  4400. data[targetCell] = temp;
  4401. }
  4402. }
  4403. // Create a 2D canvas to store the result
  4404. if (!screenshotCanvas) {
  4405. screenshotCanvas = document.createElement('canvas');
  4406. }
  4407. screenshotCanvas.width = width;
  4408. screenshotCanvas.height = height;
  4409. var context = screenshotCanvas.getContext('2d');
  4410. // Copy the pixels to a 2D canvas
  4411. var imageData = context.createImageData(width, height);
  4412. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4413. var castData = imageData.data;
  4414. castData.set(data);
  4415. context.putImageData(imageData, 0, 0);
  4416. var base64Image = screenshotCanvas.toDataURL();
  4417. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4418. if (("download" in document.createElement("a"))) {
  4419. var a = window.document.createElement("a");
  4420. a.href = base64Image;
  4421. var date = new Date();
  4422. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4423. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4424. window.document.body.appendChild(a);
  4425. a.addEventListener("click", function () {
  4426. a.parentElement.removeChild(a);
  4427. });
  4428. a.click();
  4429. }
  4430. else {
  4431. var newWindow = window.open("");
  4432. var img = newWindow.document.createElement("img");
  4433. img.src = base64Image;
  4434. newWindow.document.body.appendChild(img);
  4435. }
  4436. };
  4437. Tools.CreateScreenshot = function (engine, camera, size) {
  4438. var width;
  4439. var height;
  4440. var scene = camera.getScene();
  4441. var previousCamera = null;
  4442. if (scene.activeCamera !== camera) {
  4443. previousCamera = scene.activeCamera;
  4444. scene.activeCamera = camera;
  4445. }
  4446. //If a precision value is specified
  4447. if (size.precision) {
  4448. width = Math.round(engine.getRenderWidth() * size.precision);
  4449. height = Math.round(width / engine.getAspectRatio(camera));
  4450. size = { width: width, height: height };
  4451. }
  4452. else if (size.width && size.height) {
  4453. width = size.width;
  4454. height = size.height;
  4455. }
  4456. else if (size.width && !size.height) {
  4457. width = size.width;
  4458. height = Math.round(width / engine.getAspectRatio(camera));
  4459. size = { width: width, height: height };
  4460. }
  4461. else if (size.height && !size.width) {
  4462. height = size.height;
  4463. width = Math.round(height * engine.getAspectRatio(camera));
  4464. size = { width: width, height: height };
  4465. }
  4466. else if (!isNaN(size)) {
  4467. height = size;
  4468. width = size;
  4469. }
  4470. else {
  4471. Tools.Error("Invalid 'size' parameter !");
  4472. return;
  4473. }
  4474. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4475. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4476. texture.renderList = scene.meshes;
  4477. texture.onAfterRender = function () {
  4478. Tools.DumpFramebuffer(width, height, engine);
  4479. };
  4480. scene.incrementRenderId();
  4481. texture.render(true);
  4482. texture.dispose();
  4483. if (previousCamera) {
  4484. scene.activeCamera = previousCamera;
  4485. }
  4486. };
  4487. // XHR response validator for local file scenario
  4488. Tools.ValidateXHRData = function (xhr, dataType) {
  4489. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4490. if (dataType === void 0) { dataType = 7; }
  4491. try {
  4492. if (dataType & 1) {
  4493. if (xhr.responseText && xhr.responseText.length > 0) {
  4494. return true;
  4495. }
  4496. else if (dataType === 1) {
  4497. return false;
  4498. }
  4499. }
  4500. if (dataType & 2) {
  4501. // Check header width and height since there is no "TGA" magic number
  4502. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4503. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4504. return true;
  4505. }
  4506. else if (dataType === 2) {
  4507. return false;
  4508. }
  4509. }
  4510. if (dataType & 4) {
  4511. // Check for the "DDS" magic number
  4512. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4513. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4514. return true;
  4515. }
  4516. else {
  4517. return false;
  4518. }
  4519. }
  4520. }
  4521. catch (e) {
  4522. }
  4523. return false;
  4524. };
  4525. Object.defineProperty(Tools, "NoneLogLevel", {
  4526. get: function () {
  4527. return Tools._NoneLogLevel;
  4528. },
  4529. enumerable: true,
  4530. configurable: true
  4531. });
  4532. Object.defineProperty(Tools, "MessageLogLevel", {
  4533. get: function () {
  4534. return Tools._MessageLogLevel;
  4535. },
  4536. enumerable: true,
  4537. configurable: true
  4538. });
  4539. Object.defineProperty(Tools, "WarningLogLevel", {
  4540. get: function () {
  4541. return Tools._WarningLogLevel;
  4542. },
  4543. enumerable: true,
  4544. configurable: true
  4545. });
  4546. Object.defineProperty(Tools, "ErrorLogLevel", {
  4547. get: function () {
  4548. return Tools._ErrorLogLevel;
  4549. },
  4550. enumerable: true,
  4551. configurable: true
  4552. });
  4553. Object.defineProperty(Tools, "AllLogLevel", {
  4554. get: function () {
  4555. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4556. },
  4557. enumerable: true,
  4558. configurable: true
  4559. });
  4560. Tools._AddLogEntry = function (entry) {
  4561. Tools._LogCache = entry + Tools._LogCache;
  4562. if (Tools.OnNewCacheEntry) {
  4563. Tools.OnNewCacheEntry(entry);
  4564. }
  4565. };
  4566. Tools._FormatMessage = function (message) {
  4567. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4568. var date = new Date();
  4569. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4570. };
  4571. Tools._LogDisabled = function (message) {
  4572. // nothing to do
  4573. };
  4574. Tools._LogEnabled = function (message) {
  4575. var formattedMessage = Tools._FormatMessage(message);
  4576. console.log("BJS - " + formattedMessage);
  4577. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4578. Tools._AddLogEntry(entry);
  4579. };
  4580. Tools._WarnDisabled = function (message) {
  4581. // nothing to do
  4582. };
  4583. Tools._WarnEnabled = function (message) {
  4584. var formattedMessage = Tools._FormatMessage(message);
  4585. console.warn("BJS - " + formattedMessage);
  4586. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4587. Tools._AddLogEntry(entry);
  4588. };
  4589. Tools._ErrorDisabled = function (message) {
  4590. // nothing to do
  4591. };
  4592. Tools._ErrorEnabled = function (message) {
  4593. var formattedMessage = Tools._FormatMessage(message);
  4594. console.error("BJS - " + formattedMessage);
  4595. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4596. Tools._AddLogEntry(entry);
  4597. };
  4598. Object.defineProperty(Tools, "LogCache", {
  4599. get: function () {
  4600. return Tools._LogCache;
  4601. },
  4602. enumerable: true,
  4603. configurable: true
  4604. });
  4605. Object.defineProperty(Tools, "LogLevels", {
  4606. set: function (level) {
  4607. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4608. Tools.Log = Tools._LogEnabled;
  4609. }
  4610. else {
  4611. Tools.Log = Tools._LogDisabled;
  4612. }
  4613. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4614. Tools.Warn = Tools._WarnEnabled;
  4615. }
  4616. else {
  4617. Tools.Warn = Tools._WarnDisabled;
  4618. }
  4619. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4620. Tools.Error = Tools._ErrorEnabled;
  4621. }
  4622. else {
  4623. Tools.Error = Tools._ErrorDisabled;
  4624. }
  4625. },
  4626. enumerable: true,
  4627. configurable: true
  4628. });
  4629. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4630. get: function () {
  4631. return Tools._PerformanceNoneLogLevel;
  4632. },
  4633. enumerable: true,
  4634. configurable: true
  4635. });
  4636. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4637. get: function () {
  4638. return Tools._PerformanceUserMarkLogLevel;
  4639. },
  4640. enumerable: true,
  4641. configurable: true
  4642. });
  4643. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4644. get: function () {
  4645. return Tools._PerformanceConsoleLogLevel;
  4646. },
  4647. enumerable: true,
  4648. configurable: true
  4649. });
  4650. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4651. set: function (level) {
  4652. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4653. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4654. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4655. return;
  4656. }
  4657. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4658. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4659. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4660. return;
  4661. }
  4662. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4663. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4664. },
  4665. enumerable: true,
  4666. configurable: true
  4667. });
  4668. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4669. };
  4670. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4671. };
  4672. Tools._StartUserMark = function (counterName, condition) {
  4673. if (condition === void 0) { condition = true; }
  4674. if (!condition || !Tools._performance.mark) {
  4675. return;
  4676. }
  4677. Tools._performance.mark(counterName + "-Begin");
  4678. };
  4679. Tools._EndUserMark = function (counterName, condition) {
  4680. if (condition === void 0) { condition = true; }
  4681. if (!condition || !Tools._performance.mark) {
  4682. return;
  4683. }
  4684. Tools._performance.mark(counterName + "-End");
  4685. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4686. };
  4687. Tools._StartPerformanceConsole = function (counterName, condition) {
  4688. if (condition === void 0) { condition = true; }
  4689. if (!condition) {
  4690. return;
  4691. }
  4692. Tools._StartUserMark(counterName, condition);
  4693. if (console.time) {
  4694. console.time(counterName);
  4695. }
  4696. };
  4697. Tools._EndPerformanceConsole = function (counterName, condition) {
  4698. if (condition === void 0) { condition = true; }
  4699. if (!condition) {
  4700. return;
  4701. }
  4702. Tools._EndUserMark(counterName, condition);
  4703. if (console.time) {
  4704. console.timeEnd(counterName);
  4705. }
  4706. };
  4707. Object.defineProperty(Tools, "Now", {
  4708. get: function () {
  4709. if (window.performance && window.performance.now) {
  4710. return window.performance.now();
  4711. }
  4712. return new Date().getTime();
  4713. },
  4714. enumerable: true,
  4715. configurable: true
  4716. });
  4717. // Deprecated
  4718. Tools.GetFps = function () {
  4719. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4720. return 0;
  4721. };
  4722. Tools.BaseUrl = "";
  4723. Tools.GetExponantOfTwo = function (value, max) {
  4724. var count = 1;
  4725. do {
  4726. count *= 2;
  4727. } while (count < value);
  4728. if (count > max)
  4729. count = max;
  4730. return count;
  4731. };
  4732. // Logs
  4733. Tools._NoneLogLevel = 0;
  4734. Tools._MessageLogLevel = 1;
  4735. Tools._WarningLogLevel = 2;
  4736. Tools._ErrorLogLevel = 4;
  4737. Tools._LogCache = "";
  4738. Tools.Log = Tools._LogEnabled;
  4739. Tools.Warn = Tools._WarnEnabled;
  4740. Tools.Error = Tools._ErrorEnabled;
  4741. // Performances
  4742. Tools._PerformanceNoneLogLevel = 0;
  4743. Tools._PerformanceUserMarkLogLevel = 1;
  4744. Tools._PerformanceConsoleLogLevel = 2;
  4745. Tools._performance = window.performance;
  4746. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4747. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4748. return Tools;
  4749. })();
  4750. BABYLON.Tools = Tools;
  4751. /**
  4752. * An implementation of a loop for asynchronous functions.
  4753. */
  4754. var AsyncLoop = (function () {
  4755. /**
  4756. * Constroctor.
  4757. * @param iterations the number of iterations.
  4758. * @param _fn the function to run each iteration
  4759. * @param _successCallback the callback that will be called upon succesful execution
  4760. * @param offset starting offset.
  4761. */
  4762. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4763. if (offset === void 0) { offset = 0; }
  4764. this.iterations = iterations;
  4765. this._fn = _fn;
  4766. this._successCallback = _successCallback;
  4767. this.index = offset - 1;
  4768. this._done = false;
  4769. }
  4770. /**
  4771. * Execute the next iteration. Must be called after the last iteration was finished.
  4772. */
  4773. AsyncLoop.prototype.executeNext = function () {
  4774. if (!this._done) {
  4775. if (this.index + 1 < this.iterations) {
  4776. ++this.index;
  4777. this._fn(this);
  4778. }
  4779. else {
  4780. this.breakLoop();
  4781. }
  4782. }
  4783. };
  4784. /**
  4785. * Break the loop and run the success callback.
  4786. */
  4787. AsyncLoop.prototype.breakLoop = function () {
  4788. this._done = true;
  4789. this._successCallback();
  4790. };
  4791. /**
  4792. * Helper function
  4793. */
  4794. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4795. if (offset === void 0) { offset = 0; }
  4796. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4797. loop.executeNext();
  4798. return loop;
  4799. };
  4800. /**
  4801. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4802. * @param iterations total number of iterations
  4803. * @param syncedIterations number of synchronous iterations in each async iteration.
  4804. * @param fn the function to call each iteration.
  4805. * @param callback a success call back that will be called when iterating stops.
  4806. * @param breakFunction a break condition (optional)
  4807. * @param timeout timeout settings for the setTimeout function. default - 0.
  4808. * @constructor
  4809. */
  4810. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4811. if (timeout === void 0) { timeout = 0; }
  4812. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4813. if (breakFunction && breakFunction())
  4814. loop.breakLoop();
  4815. else {
  4816. setTimeout(function () {
  4817. for (var i = 0; i < syncedIterations; ++i) {
  4818. var iteration = (loop.index * syncedIterations) + i;
  4819. if (iteration >= iterations)
  4820. break;
  4821. fn(iteration);
  4822. if (breakFunction && breakFunction()) {
  4823. loop.breakLoop();
  4824. break;
  4825. }
  4826. }
  4827. loop.executeNext();
  4828. }, timeout);
  4829. }
  4830. }, callback);
  4831. };
  4832. return AsyncLoop;
  4833. })();
  4834. BABYLON.AsyncLoop = AsyncLoop;
  4835. })(BABYLON || (BABYLON = {}));
  4836. //# sourceMappingURL=babylon.tools.js.map
  4837. var BABYLON;
  4838. (function (BABYLON) {
  4839. var _DepthCullingState = (function () {
  4840. function _DepthCullingState() {
  4841. this._isDepthTestDirty = false;
  4842. this._isDepthMaskDirty = false;
  4843. this._isDepthFuncDirty = false;
  4844. this._isCullFaceDirty = false;
  4845. this._isCullDirty = false;
  4846. this._isZOffsetDirty = false;
  4847. }
  4848. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4849. get: function () {
  4850. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4851. },
  4852. enumerable: true,
  4853. configurable: true
  4854. });
  4855. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4856. get: function () {
  4857. return this._zOffset;
  4858. },
  4859. set: function (value) {
  4860. if (this._zOffset === value) {
  4861. return;
  4862. }
  4863. this._zOffset = value;
  4864. this._isZOffsetDirty = true;
  4865. },
  4866. enumerable: true,
  4867. configurable: true
  4868. });
  4869. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4870. get: function () {
  4871. return this._cullFace;
  4872. },
  4873. set: function (value) {
  4874. if (this._cullFace === value) {
  4875. return;
  4876. }
  4877. this._cullFace = value;
  4878. this._isCullFaceDirty = true;
  4879. },
  4880. enumerable: true,
  4881. configurable: true
  4882. });
  4883. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4884. get: function () {
  4885. return this._cull;
  4886. },
  4887. set: function (value) {
  4888. if (this._cull === value) {
  4889. return;
  4890. }
  4891. this._cull = value;
  4892. this._isCullDirty = true;
  4893. },
  4894. enumerable: true,
  4895. configurable: true
  4896. });
  4897. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4898. get: function () {
  4899. return this._depthFunc;
  4900. },
  4901. set: function (value) {
  4902. if (this._depthFunc === value) {
  4903. return;
  4904. }
  4905. this._depthFunc = value;
  4906. this._isDepthFuncDirty = true;
  4907. },
  4908. enumerable: true,
  4909. configurable: true
  4910. });
  4911. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4912. get: function () {
  4913. return this._depthMask;
  4914. },
  4915. set: function (value) {
  4916. if (this._depthMask === value) {
  4917. return;
  4918. }
  4919. this._depthMask = value;
  4920. this._isDepthMaskDirty = true;
  4921. },
  4922. enumerable: true,
  4923. configurable: true
  4924. });
  4925. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4926. get: function () {
  4927. return this._depthTest;
  4928. },
  4929. set: function (value) {
  4930. if (this._depthTest === value) {
  4931. return;
  4932. }
  4933. this._depthTest = value;
  4934. this._isDepthTestDirty = true;
  4935. },
  4936. enumerable: true,
  4937. configurable: true
  4938. });
  4939. _DepthCullingState.prototype.reset = function () {
  4940. this._depthMask = true;
  4941. this._depthTest = true;
  4942. this._depthFunc = null;
  4943. this._cull = null;
  4944. this._cullFace = null;
  4945. this._zOffset = 0;
  4946. this._isDepthTestDirty = true;
  4947. this._isDepthMaskDirty = true;
  4948. this._isDepthFuncDirty = false;
  4949. this._isCullFaceDirty = false;
  4950. this._isCullDirty = false;
  4951. this._isZOffsetDirty = false;
  4952. };
  4953. _DepthCullingState.prototype.apply = function (gl) {
  4954. if (!this.isDirty) {
  4955. return;
  4956. }
  4957. // Cull
  4958. if (this._isCullDirty) {
  4959. if (this.cull) {
  4960. gl.enable(gl.CULL_FACE);
  4961. }
  4962. else {
  4963. gl.disable(gl.CULL_FACE);
  4964. }
  4965. this._isCullDirty = false;
  4966. }
  4967. // Cull face
  4968. if (this._isCullFaceDirty) {
  4969. gl.cullFace(this.cullFace);
  4970. this._isCullFaceDirty = false;
  4971. }
  4972. // Depth mask
  4973. if (this._isDepthMaskDirty) {
  4974. gl.depthMask(this.depthMask);
  4975. this._isDepthMaskDirty = false;
  4976. }
  4977. // Depth test
  4978. if (this._isDepthTestDirty) {
  4979. if (this.depthTest) {
  4980. gl.enable(gl.DEPTH_TEST);
  4981. }
  4982. else {
  4983. gl.disable(gl.DEPTH_TEST);
  4984. }
  4985. this._isDepthTestDirty = false;
  4986. }
  4987. // Depth func
  4988. if (this._isDepthFuncDirty) {
  4989. gl.depthFunc(this.depthFunc);
  4990. this._isDepthFuncDirty = false;
  4991. }
  4992. // zOffset
  4993. if (this._isZOffsetDirty) {
  4994. if (this.zOffset) {
  4995. gl.enable(gl.POLYGON_OFFSET_FILL);
  4996. gl.polygonOffset(this.zOffset, 0);
  4997. }
  4998. else {
  4999. gl.disable(gl.POLYGON_OFFSET_FILL);
  5000. }
  5001. this._isZOffsetDirty = false;
  5002. }
  5003. };
  5004. return _DepthCullingState;
  5005. })();
  5006. BABYLON._DepthCullingState = _DepthCullingState;
  5007. var _AlphaState = (function () {
  5008. function _AlphaState() {
  5009. this._isAlphaBlendDirty = false;
  5010. this._isBlendFunctionParametersDirty = false;
  5011. this._alphaBlend = false;
  5012. this._blendFunctionParameters = new Array(4);
  5013. }
  5014. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5015. get: function () {
  5016. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5017. },
  5018. enumerable: true,
  5019. configurable: true
  5020. });
  5021. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5022. get: function () {
  5023. return this._alphaBlend;
  5024. },
  5025. set: function (value) {
  5026. if (this._alphaBlend === value) {
  5027. return;
  5028. }
  5029. this._alphaBlend = value;
  5030. this._isAlphaBlendDirty = true;
  5031. },
  5032. enumerable: true,
  5033. configurable: true
  5034. });
  5035. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5036. if (this._blendFunctionParameters[0] === value0 &&
  5037. this._blendFunctionParameters[1] === value1 &&
  5038. this._blendFunctionParameters[2] === value2 &&
  5039. this._blendFunctionParameters[3] === value3) {
  5040. return;
  5041. }
  5042. this._blendFunctionParameters[0] = value0;
  5043. this._blendFunctionParameters[1] = value1;
  5044. this._blendFunctionParameters[2] = value2;
  5045. this._blendFunctionParameters[3] = value3;
  5046. this._isBlendFunctionParametersDirty = true;
  5047. };
  5048. _AlphaState.prototype.reset = function () {
  5049. this._alphaBlend = false;
  5050. this._blendFunctionParameters[0] = null;
  5051. this._blendFunctionParameters[1] = null;
  5052. this._blendFunctionParameters[2] = null;
  5053. this._blendFunctionParameters[3] = null;
  5054. this._isAlphaBlendDirty = true;
  5055. this._isBlendFunctionParametersDirty = false;
  5056. };
  5057. _AlphaState.prototype.apply = function (gl) {
  5058. if (!this.isDirty) {
  5059. return;
  5060. }
  5061. // Alpha blend
  5062. if (this._isAlphaBlendDirty) {
  5063. if (this._alphaBlend) {
  5064. gl.enable(gl.BLEND);
  5065. }
  5066. else {
  5067. gl.disable(gl.BLEND);
  5068. }
  5069. this._isAlphaBlendDirty = false;
  5070. }
  5071. // Alpha function
  5072. if (this._isBlendFunctionParametersDirty) {
  5073. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5074. this._isBlendFunctionParametersDirty = false;
  5075. }
  5076. };
  5077. return _AlphaState;
  5078. })();
  5079. BABYLON._AlphaState = _AlphaState;
  5080. var compileShader = function (gl, source, type, defines) {
  5081. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5082. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5083. gl.compileShader(shader);
  5084. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5085. throw new Error(gl.getShaderInfoLog(shader));
  5086. }
  5087. return shader;
  5088. };
  5089. var getWebGLTextureType = function (gl, type) {
  5090. var textureType = gl.UNSIGNED_BYTE;
  5091. if (type === Engine.TEXTURETYPE_FLOAT)
  5092. textureType = gl.FLOAT;
  5093. return textureType;
  5094. };
  5095. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5096. var magFilter = gl.NEAREST;
  5097. var minFilter = gl.NEAREST;
  5098. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5099. magFilter = gl.LINEAR;
  5100. if (generateMipMaps) {
  5101. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5102. }
  5103. else {
  5104. minFilter = gl.LINEAR;
  5105. }
  5106. }
  5107. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5108. magFilter = gl.LINEAR;
  5109. if (generateMipMaps) {
  5110. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5111. }
  5112. else {
  5113. minFilter = gl.LINEAR;
  5114. }
  5115. }
  5116. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5117. magFilter = gl.NEAREST;
  5118. if (generateMipMaps) {
  5119. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5120. }
  5121. else {
  5122. minFilter = gl.NEAREST;
  5123. }
  5124. }
  5125. return {
  5126. min: minFilter,
  5127. mag: magFilter
  5128. };
  5129. };
  5130. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5132. var engine = scene.getEngine();
  5133. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5134. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5135. gl.bindTexture(gl.TEXTURE_2D, texture);
  5136. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5137. texture._baseWidth = width;
  5138. texture._baseHeight = height;
  5139. texture._width = potWidth;
  5140. texture._height = potHeight;
  5141. texture.isReady = true;
  5142. processFunction(potWidth, potHeight);
  5143. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5145. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5146. if (!noMipmap && !isCompressed) {
  5147. gl.generateMipmap(gl.TEXTURE_2D);
  5148. }
  5149. gl.bindTexture(gl.TEXTURE_2D, null);
  5150. engine._activeTexturesCache = [];
  5151. scene._removePendingData(texture);
  5152. };
  5153. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5154. var onload = function () {
  5155. loadedImages[index] = img;
  5156. loadedImages._internalCount++;
  5157. scene._removePendingData(img);
  5158. if (loadedImages._internalCount === 6) {
  5159. onfinish(loadedImages);
  5160. }
  5161. };
  5162. var onerror = function () {
  5163. scene._removePendingData(img);
  5164. };
  5165. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5166. scene._addPendingData(img);
  5167. };
  5168. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5169. var loadedImages = [];
  5170. loadedImages._internalCount = 0;
  5171. for (var index = 0; index < 6; index++) {
  5172. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5173. }
  5174. };
  5175. var EngineCapabilities = (function () {
  5176. function EngineCapabilities() {
  5177. }
  5178. return EngineCapabilities;
  5179. })();
  5180. BABYLON.EngineCapabilities = EngineCapabilities;
  5181. /**
  5182. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5183. */
  5184. var Engine = (function () {
  5185. /**
  5186. * @constructor
  5187. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5188. * @param {boolean} [antialias] - enable antialias
  5189. * @param options - further options to be sent to the getContext function
  5190. */
  5191. function Engine(canvas, antialias, options) {
  5192. var _this = this;
  5193. // Public members
  5194. this.isFullscreen = false;
  5195. this.isPointerLock = false;
  5196. this.cullBackFaces = true;
  5197. this.renderEvenInBackground = true;
  5198. this.scenes = new Array();
  5199. this._windowIsBackground = false;
  5200. this._loadingDivBackgroundColor = "black";
  5201. this._drawCalls = 0;
  5202. this._renderingQueueLaunched = false;
  5203. this._activeRenderLoops = [];
  5204. // FPS
  5205. this.fpsRange = 60;
  5206. this.previousFramesDuration = [];
  5207. this.fps = 60;
  5208. this.deltaTime = 0;
  5209. // States
  5210. this._depthCullingState = new _DepthCullingState();
  5211. this._alphaState = new _AlphaState();
  5212. this._alphaMode = Engine.ALPHA_DISABLE;
  5213. // Cache
  5214. this._loadedTexturesCache = new Array();
  5215. this._activeTexturesCache = new Array();
  5216. this._compiledEffects = {};
  5217. this._uintIndicesCurrentlySet = false;
  5218. this._renderingCanvas = canvas;
  5219. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5220. options = options || {};
  5221. options.antialias = antialias;
  5222. // GL
  5223. try {
  5224. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5225. }
  5226. catch (e) {
  5227. throw new Error("WebGL not supported");
  5228. }
  5229. if (!this._gl) {
  5230. throw new Error("WebGL not supported");
  5231. }
  5232. this._onBlur = function () {
  5233. _this._windowIsBackground = true;
  5234. };
  5235. this._onFocus = function () {
  5236. _this._windowIsBackground = false;
  5237. };
  5238. window.addEventListener("blur", this._onBlur);
  5239. window.addEventListener("focus", this._onFocus);
  5240. // Viewport
  5241. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5242. this.resize();
  5243. // Caps
  5244. this._caps = new EngineCapabilities();
  5245. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5246. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5247. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5248. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5249. // Infos
  5250. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5251. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5252. if (rendererInfo != null) {
  5253. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5254. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5255. }
  5256. if (!this._glVendor) {
  5257. this._glVendor = "Unknown vendor";
  5258. }
  5259. if (!this._glRenderer) {
  5260. this._glRenderer = "Unknown renderer";
  5261. }
  5262. // Extensions
  5263. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5264. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5265. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5266. 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');
  5267. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5268. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5269. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5270. this._caps.highPrecisionShaderSupported = true;
  5271. if (this._gl.getShaderPrecisionFormat) {
  5272. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5273. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5274. }
  5275. // Depth buffer
  5276. this.setDepthBuffer(true);
  5277. this.setDepthFunctionToLessOrEqual();
  5278. this.setDepthWrite(true);
  5279. // Fullscreen
  5280. this._onFullscreenChange = function () {
  5281. if (document.fullscreen !== undefined) {
  5282. _this.isFullscreen = document.fullscreen;
  5283. }
  5284. else if (document.mozFullScreen !== undefined) {
  5285. _this.isFullscreen = document.mozFullScreen;
  5286. }
  5287. else if (document.webkitIsFullScreen !== undefined) {
  5288. _this.isFullscreen = document.webkitIsFullScreen;
  5289. }
  5290. else if (document.msIsFullScreen !== undefined) {
  5291. _this.isFullscreen = document.msIsFullScreen;
  5292. }
  5293. // Pointer lock
  5294. if (_this.isFullscreen && _this._pointerLockRequested) {
  5295. canvas.requestPointerLock = canvas.requestPointerLock ||
  5296. canvas.msRequestPointerLock ||
  5297. canvas.mozRequestPointerLock ||
  5298. canvas.webkitRequestPointerLock;
  5299. if (canvas.requestPointerLock) {
  5300. canvas.requestPointerLock();
  5301. }
  5302. }
  5303. };
  5304. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5305. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5306. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5307. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5308. // Pointer lock
  5309. this._onPointerLockChange = function () {
  5310. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5311. document.webkitPointerLockElement === canvas ||
  5312. document.msPointerLockElement === canvas ||
  5313. document.pointerLockElement === canvas);
  5314. };
  5315. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5316. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5317. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5318. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5319. if (!Engine.audioEngine) {
  5320. Engine.audioEngine = new BABYLON.AudioEngine();
  5321. }
  5322. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5323. }
  5324. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5325. get: function () {
  5326. return Engine._ALPHA_DISABLE;
  5327. },
  5328. enumerable: true,
  5329. configurable: true
  5330. });
  5331. Object.defineProperty(Engine, "ALPHA_ADD", {
  5332. get: function () {
  5333. return Engine._ALPHA_ADD;
  5334. },
  5335. enumerable: true,
  5336. configurable: true
  5337. });
  5338. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5339. get: function () {
  5340. return Engine._ALPHA_COMBINE;
  5341. },
  5342. enumerable: true,
  5343. configurable: true
  5344. });
  5345. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5346. get: function () {
  5347. return Engine._DELAYLOADSTATE_NONE;
  5348. },
  5349. enumerable: true,
  5350. configurable: true
  5351. });
  5352. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5353. get: function () {
  5354. return Engine._DELAYLOADSTATE_LOADED;
  5355. },
  5356. enumerable: true,
  5357. configurable: true
  5358. });
  5359. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5360. get: function () {
  5361. return Engine._DELAYLOADSTATE_LOADING;
  5362. },
  5363. enumerable: true,
  5364. configurable: true
  5365. });
  5366. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5367. get: function () {
  5368. return Engine._DELAYLOADSTATE_NOTLOADED;
  5369. },
  5370. enumerable: true,
  5371. configurable: true
  5372. });
  5373. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5374. get: function () {
  5375. return Engine._TEXTUREFORMAT_ALPHA;
  5376. },
  5377. enumerable: true,
  5378. configurable: true
  5379. });
  5380. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5381. get: function () {
  5382. return Engine._TEXTUREFORMAT_LUMINANCE;
  5383. },
  5384. enumerable: true,
  5385. configurable: true
  5386. });
  5387. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5388. get: function () {
  5389. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5390. },
  5391. enumerable: true,
  5392. configurable: true
  5393. });
  5394. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5395. get: function () {
  5396. return Engine._TEXTUREFORMAT_RGB;
  5397. },
  5398. enumerable: true,
  5399. configurable: true
  5400. });
  5401. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5402. get: function () {
  5403. return Engine._TEXTUREFORMAT_RGBA;
  5404. },
  5405. enumerable: true,
  5406. configurable: true
  5407. });
  5408. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5409. get: function () {
  5410. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5411. },
  5412. enumerable: true,
  5413. configurable: true
  5414. });
  5415. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5416. get: function () {
  5417. return Engine._TEXTURETYPE_FLOAT;
  5418. },
  5419. enumerable: true,
  5420. configurable: true
  5421. });
  5422. Object.defineProperty(Engine, "Version", {
  5423. get: function () {
  5424. return "2.1.0 beta";
  5425. },
  5426. enumerable: true,
  5427. configurable: true
  5428. });
  5429. Engine.prototype._prepareWorkingCanvas = function () {
  5430. if (this._workingCanvas) {
  5431. return;
  5432. }
  5433. this._workingCanvas = document.createElement("canvas");
  5434. this._workingContext = this._workingCanvas.getContext("2d");
  5435. };
  5436. Engine.prototype.getGlInfo = function () {
  5437. return {
  5438. vendor: this._glVendor,
  5439. renderer: this._glRenderer,
  5440. version: this._glVersion
  5441. };
  5442. };
  5443. Engine.prototype.getAspectRatio = function (camera) {
  5444. var viewport = camera.viewport;
  5445. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5446. };
  5447. Engine.prototype.getRenderWidth = function () {
  5448. if (this._currentRenderTarget) {
  5449. return this._currentRenderTarget._width;
  5450. }
  5451. return this._renderingCanvas.width;
  5452. };
  5453. Engine.prototype.getRenderHeight = function () {
  5454. if (this._currentRenderTarget) {
  5455. return this._currentRenderTarget._height;
  5456. }
  5457. return this._renderingCanvas.height;
  5458. };
  5459. Engine.prototype.getRenderingCanvas = function () {
  5460. return this._renderingCanvas;
  5461. };
  5462. Engine.prototype.getRenderingCanvasClientRect = function () {
  5463. return this._renderingCanvas.getBoundingClientRect();
  5464. };
  5465. Engine.prototype.setHardwareScalingLevel = function (level) {
  5466. this._hardwareScalingLevel = level;
  5467. this.resize();
  5468. };
  5469. Engine.prototype.getHardwareScalingLevel = function () {
  5470. return this._hardwareScalingLevel;
  5471. };
  5472. Engine.prototype.getLoadedTexturesCache = function () {
  5473. return this._loadedTexturesCache;
  5474. };
  5475. Engine.prototype.getCaps = function () {
  5476. return this._caps;
  5477. };
  5478. Object.defineProperty(Engine.prototype, "drawCalls", {
  5479. get: function () {
  5480. return this._drawCalls;
  5481. },
  5482. enumerable: true,
  5483. configurable: true
  5484. });
  5485. // Methods
  5486. Engine.prototype.resetDrawCalls = function () {
  5487. this._drawCalls = 0;
  5488. };
  5489. Engine.prototype.setDepthFunctionToGreater = function () {
  5490. this._depthCullingState.depthFunc = this._gl.GREATER;
  5491. };
  5492. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5493. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5494. };
  5495. Engine.prototype.setDepthFunctionToLess = function () {
  5496. this._depthCullingState.depthFunc = this._gl.LESS;
  5497. };
  5498. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5499. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5500. };
  5501. /**
  5502. * stop executing a render loop function and remove it from the execution array
  5503. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5504. */
  5505. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5506. if (!renderFunction) {
  5507. this._activeRenderLoops = [];
  5508. return;
  5509. }
  5510. var index = this._activeRenderLoops.indexOf(renderFunction);
  5511. if (index >= 0) {
  5512. this._activeRenderLoops.splice(index, 1);
  5513. }
  5514. };
  5515. Engine.prototype._renderLoop = function () {
  5516. var _this = this;
  5517. var shouldRender = true;
  5518. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5519. shouldRender = false;
  5520. }
  5521. if (shouldRender) {
  5522. // Start new frame
  5523. this.beginFrame();
  5524. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5525. var renderFunction = this._activeRenderLoops[index];
  5526. renderFunction();
  5527. }
  5528. // Present
  5529. this.endFrame();
  5530. }
  5531. if (this._activeRenderLoops.length > 0) {
  5532. // Register new frame
  5533. BABYLON.Tools.QueueNewFrame(function () {
  5534. _this._renderLoop();
  5535. });
  5536. }
  5537. else {
  5538. this._renderingQueueLaunched = false;
  5539. }
  5540. };
  5541. /**
  5542. * Register and execute a render loop. The engine can have more than one render function.
  5543. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5544. * @example
  5545. * engine.runRenderLoop(function () {
  5546. * scene.render()
  5547. * })
  5548. */
  5549. Engine.prototype.runRenderLoop = function (renderFunction) {
  5550. var _this = this;
  5551. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5552. return;
  5553. }
  5554. this._activeRenderLoops.push(renderFunction);
  5555. if (!this._renderingQueueLaunched) {
  5556. this._renderingQueueLaunched = true;
  5557. BABYLON.Tools.QueueNewFrame(function () {
  5558. _this._renderLoop();
  5559. });
  5560. }
  5561. };
  5562. /**
  5563. * Toggle full screen mode.
  5564. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5565. */
  5566. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5567. if (this.isFullscreen) {
  5568. BABYLON.Tools.ExitFullscreen();
  5569. }
  5570. else {
  5571. this._pointerLockRequested = requestPointerLock;
  5572. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5573. }
  5574. };
  5575. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5576. this.applyStates();
  5577. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5578. if (this._depthCullingState.depthMask) {
  5579. this._gl.clearDepth(1.0);
  5580. }
  5581. var mode = 0;
  5582. if (backBuffer)
  5583. mode |= this._gl.COLOR_BUFFER_BIT;
  5584. if (depthStencil && this._depthCullingState.depthMask)
  5585. mode |= this._gl.DEPTH_BUFFER_BIT;
  5586. this._gl.clear(mode);
  5587. };
  5588. /**
  5589. * Set the WebGL's viewport
  5590. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5591. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5592. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5593. */
  5594. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5595. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5596. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5597. var x = viewport.x || 0;
  5598. var y = viewport.y || 0;
  5599. this._cachedViewport = viewport;
  5600. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5601. };
  5602. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5603. this._cachedViewport = null;
  5604. this._gl.viewport(x, y, width, height);
  5605. };
  5606. Engine.prototype.beginFrame = function () {
  5607. this._measureFps();
  5608. };
  5609. Engine.prototype.endFrame = function () {
  5610. //this.flushFramebuffer();
  5611. };
  5612. /**
  5613. * resize the view according to the canvas' size.
  5614. * @example
  5615. * window.addEventListener("resize", function () {
  5616. * engine.resize();
  5617. * });
  5618. */
  5619. Engine.prototype.resize = function () {
  5620. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5621. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5622. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5623. };
  5624. /**
  5625. * force a specific size of the canvas
  5626. * @param {number} width - the new canvas' width
  5627. * @param {number} height - the new canvas' height
  5628. */
  5629. Engine.prototype.setSize = function (width, height) {
  5630. this._renderingCanvas.width = width;
  5631. this._renderingCanvas.height = height;
  5632. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5633. for (var index = 0; index < this.scenes.length; index++) {
  5634. var scene = this.scenes[index];
  5635. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5636. var cam = scene.cameras[camIndex];
  5637. cam._currentRenderId = 0;
  5638. }
  5639. }
  5640. };
  5641. Engine.prototype.bindFramebuffer = function (texture) {
  5642. this._currentRenderTarget = texture;
  5643. var gl = this._gl;
  5644. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5645. this._gl.viewport(0, 0, texture._width, texture._height);
  5646. this.wipeCaches();
  5647. };
  5648. Engine.prototype.unBindFramebuffer = function (texture) {
  5649. this._currentRenderTarget = null;
  5650. if (texture.generateMipMaps) {
  5651. var gl = this._gl;
  5652. gl.bindTexture(gl.TEXTURE_2D, texture);
  5653. gl.generateMipmap(gl.TEXTURE_2D);
  5654. gl.bindTexture(gl.TEXTURE_2D, null);
  5655. }
  5656. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5657. };
  5658. Engine.prototype.flushFramebuffer = function () {
  5659. this._gl.flush();
  5660. };
  5661. Engine.prototype.restoreDefaultFramebuffer = function () {
  5662. this._currentRenderTarget = null;
  5663. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5664. this.setViewport(this._cachedViewport);
  5665. this.wipeCaches();
  5666. };
  5667. // VBOs
  5668. Engine.prototype._resetVertexBufferBinding = function () {
  5669. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5670. this._cachedVertexBuffers = null;
  5671. };
  5672. Engine.prototype.createVertexBuffer = function (vertices) {
  5673. var vbo = this._gl.createBuffer();
  5674. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5675. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5676. this._resetVertexBufferBinding();
  5677. vbo.references = 1;
  5678. return vbo;
  5679. };
  5680. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5681. var vbo = this._gl.createBuffer();
  5682. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5683. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5684. this._resetVertexBufferBinding();
  5685. vbo.references = 1;
  5686. return vbo;
  5687. };
  5688. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5689. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5690. if (offset === undefined) {
  5691. offset = 0;
  5692. }
  5693. if (vertices instanceof Float32Array) {
  5694. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5695. }
  5696. else {
  5697. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5698. }
  5699. this._resetVertexBufferBinding();
  5700. };
  5701. Engine.prototype._resetIndexBufferBinding = function () {
  5702. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5703. this._cachedIndexBuffer = null;
  5704. };
  5705. Engine.prototype.createIndexBuffer = function (indices) {
  5706. var vbo = this._gl.createBuffer();
  5707. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5708. // Check for 32 bits indices
  5709. var arrayBuffer;
  5710. var need32Bits = false;
  5711. if (this._caps.uintIndices) {
  5712. for (var index = 0; index < indices.length; index++) {
  5713. if (indices[index] > 65535) {
  5714. need32Bits = true;
  5715. break;
  5716. }
  5717. }
  5718. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5719. }
  5720. else {
  5721. arrayBuffer = new Uint16Array(indices);
  5722. }
  5723. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5724. this._resetIndexBufferBinding();
  5725. vbo.references = 1;
  5726. vbo.is32Bits = need32Bits;
  5727. return vbo;
  5728. };
  5729. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5730. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5731. this._cachedVertexBuffers = vertexBuffer;
  5732. this._cachedEffectForVertexBuffers = effect;
  5733. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5734. var offset = 0;
  5735. for (var index = 0; index < vertexDeclaration.length; index++) {
  5736. var order = effect.getAttributeLocation(index);
  5737. if (order >= 0) {
  5738. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5739. }
  5740. offset += vertexDeclaration[index] * 4;
  5741. }
  5742. }
  5743. if (this._cachedIndexBuffer !== indexBuffer) {
  5744. this._cachedIndexBuffer = indexBuffer;
  5745. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5746. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5747. }
  5748. };
  5749. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5750. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5751. this._cachedVertexBuffers = vertexBuffers;
  5752. this._cachedEffectForVertexBuffers = effect;
  5753. var attributes = effect.getAttributesNames();
  5754. for (var index = 0; index < attributes.length; index++) {
  5755. var order = effect.getAttributeLocation(index);
  5756. if (order >= 0) {
  5757. var vertexBuffer = vertexBuffers[attributes[index]];
  5758. if (!vertexBuffer) {
  5759. continue;
  5760. }
  5761. var stride = vertexBuffer.getStrideSize();
  5762. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5763. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5764. }
  5765. }
  5766. }
  5767. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5768. this._cachedIndexBuffer = indexBuffer;
  5769. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5770. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5771. }
  5772. };
  5773. Engine.prototype._releaseBuffer = function (buffer) {
  5774. buffer.references--;
  5775. if (buffer.references === 0) {
  5776. this._gl.deleteBuffer(buffer);
  5777. return true;
  5778. }
  5779. return false;
  5780. };
  5781. Engine.prototype.createInstancesBuffer = function (capacity) {
  5782. var buffer = this._gl.createBuffer();
  5783. buffer.capacity = capacity;
  5784. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5785. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5786. return buffer;
  5787. };
  5788. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5789. this._gl.deleteBuffer(buffer);
  5790. };
  5791. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5792. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5793. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5794. for (var index = 0; index < 4; index++) {
  5795. var offsetLocation = offsetLocations[index];
  5796. this._gl.enableVertexAttribArray(offsetLocation);
  5797. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5798. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5799. }
  5800. };
  5801. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5802. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5803. for (var index = 0; index < 4; index++) {
  5804. var offsetLocation = offsetLocations[index];
  5805. this._gl.disableVertexAttribArray(offsetLocation);
  5806. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5807. }
  5808. };
  5809. Engine.prototype.applyStates = function () {
  5810. this._depthCullingState.apply(this._gl);
  5811. this._alphaState.apply(this._gl);
  5812. };
  5813. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5814. // Apply states
  5815. this.applyStates();
  5816. this._drawCalls++;
  5817. // Render
  5818. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5819. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5820. if (instancesCount) {
  5821. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5822. return;
  5823. }
  5824. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5825. };
  5826. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5827. // Apply states
  5828. this.applyStates();
  5829. this._drawCalls++;
  5830. if (instancesCount) {
  5831. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5832. return;
  5833. }
  5834. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5835. };
  5836. // Shaders
  5837. Engine.prototype._releaseEffect = function (effect) {
  5838. if (this._compiledEffects[effect._key]) {
  5839. delete this._compiledEffects[effect._key];
  5840. if (effect.getProgram()) {
  5841. this._gl.deleteProgram(effect.getProgram());
  5842. }
  5843. }
  5844. };
  5845. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5846. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5847. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5848. var name = vertex + "+" + fragment + "@" + defines;
  5849. if (this._compiledEffects[name]) {
  5850. return this._compiledEffects[name];
  5851. }
  5852. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5853. effect._key = name;
  5854. this._compiledEffects[name] = effect;
  5855. return effect;
  5856. };
  5857. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5858. if (uniformsNames === void 0) { uniformsNames = []; }
  5859. if (samplers === void 0) { samplers = []; }
  5860. if (defines === void 0) { defines = ""; }
  5861. return this.createEffect({
  5862. vertex: "particles",
  5863. fragmentElement: fragmentName
  5864. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5865. };
  5866. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5867. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5868. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5869. var shaderProgram = this._gl.createProgram();
  5870. this._gl.attachShader(shaderProgram, vertexShader);
  5871. this._gl.attachShader(shaderProgram, fragmentShader);
  5872. this._gl.linkProgram(shaderProgram);
  5873. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5874. if (!linked) {
  5875. var error = this._gl.getProgramInfoLog(shaderProgram);
  5876. if (error) {
  5877. throw new Error(error);
  5878. }
  5879. }
  5880. this._gl.deleteShader(vertexShader);
  5881. this._gl.deleteShader(fragmentShader);
  5882. return shaderProgram;
  5883. };
  5884. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5885. var results = [];
  5886. for (var index = 0; index < uniformsNames.length; index++) {
  5887. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5888. }
  5889. return results;
  5890. };
  5891. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5892. var results = [];
  5893. for (var index = 0; index < attributesNames.length; index++) {
  5894. try {
  5895. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5896. }
  5897. catch (e) {
  5898. results.push(-1);
  5899. }
  5900. }
  5901. return results;
  5902. };
  5903. Engine.prototype.enableEffect = function (effect) {
  5904. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5905. if (effect && effect.onBind) {
  5906. effect.onBind(effect);
  5907. }
  5908. return;
  5909. }
  5910. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5911. // Use program
  5912. this._gl.useProgram(effect.getProgram());
  5913. for (var i in this._vertexAttribArrays) {
  5914. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5915. continue;
  5916. }
  5917. this._vertexAttribArrays[i] = false;
  5918. this._gl.disableVertexAttribArray(i);
  5919. }
  5920. var attributesCount = effect.getAttributesCount();
  5921. for (var index = 0; index < attributesCount; index++) {
  5922. // Attributes
  5923. var order = effect.getAttributeLocation(index);
  5924. if (order >= 0) {
  5925. this._vertexAttribArrays[order] = true;
  5926. this._gl.enableVertexAttribArray(order);
  5927. }
  5928. }
  5929. this._currentEffect = effect;
  5930. if (effect.onBind) {
  5931. effect.onBind(effect);
  5932. }
  5933. };
  5934. Engine.prototype.setArray = function (uniform, array) {
  5935. if (!uniform)
  5936. return;
  5937. this._gl.uniform1fv(uniform, array);
  5938. };
  5939. Engine.prototype.setArray2 = function (uniform, array) {
  5940. if (!uniform || array.length % 2 !== 0)
  5941. return;
  5942. this._gl.uniform2fv(uniform, array);
  5943. };
  5944. Engine.prototype.setArray3 = function (uniform, array) {
  5945. if (!uniform || array.length % 3 !== 0)
  5946. return;
  5947. this._gl.uniform3fv(uniform, array);
  5948. };
  5949. Engine.prototype.setArray4 = function (uniform, array) {
  5950. if (!uniform || array.length % 4 !== 0)
  5951. return;
  5952. this._gl.uniform4fv(uniform, array);
  5953. };
  5954. Engine.prototype.setMatrices = function (uniform, matrices) {
  5955. if (!uniform)
  5956. return;
  5957. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5958. };
  5959. Engine.prototype.setMatrix = function (uniform, matrix) {
  5960. if (!uniform)
  5961. return;
  5962. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5963. };
  5964. Engine.prototype.setFloat = function (uniform, value) {
  5965. if (!uniform)
  5966. return;
  5967. this._gl.uniform1f(uniform, value);
  5968. };
  5969. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5970. if (!uniform)
  5971. return;
  5972. this._gl.uniform2f(uniform, x, y);
  5973. };
  5974. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5975. if (!uniform)
  5976. return;
  5977. this._gl.uniform3f(uniform, x, y, z);
  5978. };
  5979. Engine.prototype.setBool = function (uniform, bool) {
  5980. if (!uniform)
  5981. return;
  5982. this._gl.uniform1i(uniform, bool);
  5983. };
  5984. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5985. if (!uniform)
  5986. return;
  5987. this._gl.uniform4f(uniform, x, y, z, w);
  5988. };
  5989. Engine.prototype.setColor3 = function (uniform, color3) {
  5990. if (!uniform)
  5991. return;
  5992. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5993. };
  5994. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5995. if (!uniform)
  5996. return;
  5997. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5998. };
  5999. // States
  6000. Engine.prototype.setState = function (culling, zOffset, force) {
  6001. if (zOffset === void 0) { zOffset = 0; }
  6002. // Culling
  6003. if (this._depthCullingState.cull !== culling || force) {
  6004. if (culling) {
  6005. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6006. this._depthCullingState.cull = true;
  6007. }
  6008. else {
  6009. this._depthCullingState.cull = false;
  6010. }
  6011. }
  6012. // Z offset
  6013. this._depthCullingState.zOffset = zOffset;
  6014. };
  6015. Engine.prototype.setDepthBuffer = function (enable) {
  6016. this._depthCullingState.depthTest = enable;
  6017. };
  6018. Engine.prototype.getDepthWrite = function () {
  6019. return this._depthCullingState.depthMask;
  6020. };
  6021. Engine.prototype.setDepthWrite = function (enable) {
  6022. this._depthCullingState.depthMask = enable;
  6023. };
  6024. Engine.prototype.setColorWrite = function (enable) {
  6025. this._gl.colorMask(enable, enable, enable, enable);
  6026. };
  6027. Engine.prototype.setAlphaMode = function (mode) {
  6028. switch (mode) {
  6029. case Engine.ALPHA_DISABLE:
  6030. this.setDepthWrite(true);
  6031. this._alphaState.alphaBlend = false;
  6032. break;
  6033. case Engine.ALPHA_COMBINE:
  6034. this.setDepthWrite(false);
  6035. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6036. this._alphaState.alphaBlend = true;
  6037. break;
  6038. case Engine.ALPHA_ADD:
  6039. this.setDepthWrite(false);
  6040. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6041. this._alphaState.alphaBlend = true;
  6042. break;
  6043. }
  6044. this._alphaMode = mode;
  6045. };
  6046. Engine.prototype.getAlphaMode = function () {
  6047. return this._alphaMode;
  6048. };
  6049. Engine.prototype.setAlphaTesting = function (enable) {
  6050. this._alphaTest = enable;
  6051. };
  6052. Engine.prototype.getAlphaTesting = function () {
  6053. return this._alphaTest;
  6054. };
  6055. // Textures
  6056. Engine.prototype.wipeCaches = function () {
  6057. this._activeTexturesCache = [];
  6058. this._currentEffect = null;
  6059. this._depthCullingState.reset();
  6060. this._alphaState.reset();
  6061. this._cachedVertexBuffers = null;
  6062. this._cachedIndexBuffer = null;
  6063. this._cachedEffectForVertexBuffers = null;
  6064. };
  6065. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6066. var gl = this._gl;
  6067. gl.bindTexture(gl.TEXTURE_2D, texture);
  6068. var magFilter = gl.NEAREST;
  6069. var minFilter = gl.NEAREST;
  6070. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6071. magFilter = gl.LINEAR;
  6072. minFilter = gl.LINEAR;
  6073. }
  6074. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6075. magFilter = gl.LINEAR;
  6076. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6077. }
  6078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6080. gl.bindTexture(gl.TEXTURE_2D, null);
  6081. texture.samplingMode = samplingMode;
  6082. };
  6083. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6084. var _this = this;
  6085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6086. if (onLoad === void 0) { onLoad = null; }
  6087. if (onError === void 0) { onError = null; }
  6088. if (buffer === void 0) { buffer = null; }
  6089. var texture = this._gl.createTexture();
  6090. var extension;
  6091. var fromData = false;
  6092. if (url.substr(0, 5) === "data:") {
  6093. fromData = true;
  6094. }
  6095. if (!fromData)
  6096. extension = url.substr(url.length - 4, 4).toLowerCase();
  6097. else {
  6098. var oldUrl = url;
  6099. fromData = oldUrl.split(':');
  6100. url = oldUrl;
  6101. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6102. }
  6103. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6104. var isTGA = (extension === ".tga");
  6105. scene._addPendingData(texture);
  6106. texture.url = url;
  6107. texture.noMipmap = noMipmap;
  6108. texture.references = 1;
  6109. texture.samplingMode = samplingMode;
  6110. this._loadedTexturesCache.push(texture);
  6111. var onerror = function () {
  6112. scene._removePendingData(texture);
  6113. if (onError) {
  6114. onError();
  6115. }
  6116. };
  6117. if (isTGA) {
  6118. var callback = function (arrayBuffer) {
  6119. var data = new Uint8Array(arrayBuffer);
  6120. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6121. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6122. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6123. if (onLoad) {
  6124. onLoad();
  6125. }
  6126. }, samplingMode);
  6127. };
  6128. if (!(fromData instanceof Array))
  6129. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6130. callback(arrayBuffer);
  6131. }, onerror, scene.database, true);
  6132. else
  6133. callback(buffer);
  6134. }
  6135. else if (isDDS) {
  6136. callback = function (data) {
  6137. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6138. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6139. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6140. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6141. if (onLoad) {
  6142. onLoad();
  6143. }
  6144. }, samplingMode);
  6145. };
  6146. if (!(fromData instanceof Array))
  6147. BABYLON.Tools.LoadFile(url, function (data) {
  6148. callback(data);
  6149. }, onerror, scene.database, true);
  6150. else
  6151. callback(buffer);
  6152. }
  6153. else {
  6154. var onload = function (img) {
  6155. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6156. var isPot = (img.width === potWidth && img.height === potHeight);
  6157. if (!isPot) {
  6158. _this._prepareWorkingCanvas();
  6159. _this._workingCanvas.width = potWidth;
  6160. _this._workingCanvas.height = potHeight;
  6161. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6162. _this._workingContext.imageSmoothingEnabled = false;
  6163. _this._workingContext.mozImageSmoothingEnabled = false;
  6164. _this._workingContext.oImageSmoothingEnabled = false;
  6165. _this._workingContext.webkitImageSmoothingEnabled = false;
  6166. _this._workingContext.msImageSmoothingEnabled = false;
  6167. }
  6168. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6169. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6170. _this._workingContext.imageSmoothingEnabled = true;
  6171. _this._workingContext.mozImageSmoothingEnabled = true;
  6172. _this._workingContext.oImageSmoothingEnabled = true;
  6173. _this._workingContext.webkitImageSmoothingEnabled = true;
  6174. _this._workingContext.msImageSmoothingEnabled = true;
  6175. }
  6176. }
  6177. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6178. if (onLoad) {
  6179. onLoad();
  6180. }
  6181. }, samplingMode);
  6182. };
  6183. if (!(fromData instanceof Array))
  6184. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6185. else
  6186. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6187. }
  6188. return texture;
  6189. };
  6190. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6191. var texture = this._gl.createTexture();
  6192. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6193. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6194. // Format
  6195. var internalFormat = this._gl.RGBA;
  6196. switch (format) {
  6197. case Engine.TEXTUREFORMAT_ALPHA:
  6198. internalFormat = this._gl.ALPHA;
  6199. break;
  6200. case Engine.TEXTUREFORMAT_LUMINANCE:
  6201. internalFormat = this._gl.LUMINANCE;
  6202. break;
  6203. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6204. internalFormat = this._gl.LUMINANCE_ALPHA;
  6205. break;
  6206. case Engine.TEXTUREFORMAT_RGB:
  6207. internalFormat = this._gl.RGB;
  6208. break;
  6209. case Engine.TEXTUREFORMAT_RGBA:
  6210. internalFormat = this._gl.RGBA;
  6211. break;
  6212. }
  6213. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6214. if (generateMipMaps) {
  6215. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6216. }
  6217. // Filters
  6218. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6219. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6220. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6221. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6222. this._activeTexturesCache = [];
  6223. texture._baseWidth = width;
  6224. texture._baseHeight = height;
  6225. texture._width = width;
  6226. texture._height = height;
  6227. texture.isReady = true;
  6228. texture.references = 1;
  6229. texture.samplingMode = samplingMode;
  6230. this._loadedTexturesCache.push(texture);
  6231. return texture;
  6232. };
  6233. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  6234. var texture = this._gl.createTexture();
  6235. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6236. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6237. this._activeTexturesCache = [];
  6238. texture._baseWidth = width;
  6239. texture._baseHeight = height;
  6240. texture._width = width;
  6241. texture._height = height;
  6242. texture.isReady = false;
  6243. texture.generateMipMaps = generateMipMaps;
  6244. texture.references = 1;
  6245. texture.samplingMode = samplingMode;
  6246. this.updateTextureSamplingMode(samplingMode, texture);
  6247. this._loadedTexturesCache.push(texture);
  6248. return texture;
  6249. };
  6250. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6251. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6252. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6253. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6254. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6255. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6256. };
  6257. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6258. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6259. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6260. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6261. if (texture.generateMipMaps) {
  6262. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6263. }
  6264. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6265. this._activeTexturesCache = [];
  6266. texture.isReady = true;
  6267. };
  6268. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6269. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6270. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6271. // Scale the video if it is a NPOT using the current working canvas
  6272. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  6273. if (!texture._workingCanvas) {
  6274. texture._workingCanvas = document.createElement("canvas");
  6275. texture._workingContext = texture._workingCanvas.getContext("2d");
  6276. texture._workingCanvas.width = texture._width;
  6277. texture._workingCanvas.height = texture._height;
  6278. }
  6279. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6280. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6281. }
  6282. else {
  6283. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6284. }
  6285. if (texture.generateMipMaps) {
  6286. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6287. }
  6288. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6289. this._activeTexturesCache = [];
  6290. texture.isReady = true;
  6291. };
  6292. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6293. // old version had a "generateMipMaps" arg instead of options.
  6294. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6295. // in the same way, generateDepthBuffer is defaulted to true
  6296. var generateMipMaps = false;
  6297. var generateDepthBuffer = true;
  6298. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6299. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6300. if (options !== undefined) {
  6301. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6302. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6303. type = options.type === undefined ? type : options.type;
  6304. if (options.samplingMode !== undefined) {
  6305. samplingMode = options.samplingMode;
  6306. }
  6307. if (type === Engine.TEXTURETYPE_FLOAT) {
  6308. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6309. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6310. }
  6311. }
  6312. var gl = this._gl;
  6313. var texture = gl.createTexture();
  6314. gl.bindTexture(gl.TEXTURE_2D, texture);
  6315. var width = size.width || size;
  6316. var height = size.height || size;
  6317. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6318. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6319. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6320. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6321. }
  6322. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6323. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6324. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6325. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6326. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6327. var depthBuffer;
  6328. // Create the depth buffer
  6329. if (generateDepthBuffer) {
  6330. depthBuffer = gl.createRenderbuffer();
  6331. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6332. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6333. }
  6334. // Create the framebuffer
  6335. var framebuffer = gl.createFramebuffer();
  6336. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6337. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6338. if (generateDepthBuffer) {
  6339. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6340. }
  6341. // Unbind
  6342. gl.bindTexture(gl.TEXTURE_2D, null);
  6343. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6344. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6345. texture._framebuffer = framebuffer;
  6346. if (generateDepthBuffer) {
  6347. texture._depthBuffer = depthBuffer;
  6348. }
  6349. texture._width = width;
  6350. texture._height = height;
  6351. texture.isReady = true;
  6352. texture.generateMipMaps = generateMipMaps;
  6353. texture.references = 1;
  6354. texture.samplingMode = samplingMode;
  6355. this._activeTexturesCache = [];
  6356. this._loadedTexturesCache.push(texture);
  6357. return texture;
  6358. };
  6359. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6360. var _this = this;
  6361. var gl = this._gl;
  6362. var texture = gl.createTexture();
  6363. texture.isCube = true;
  6364. texture.url = rootUrl;
  6365. texture.references = 1;
  6366. this._loadedTexturesCache.push(texture);
  6367. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6368. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6369. if (isDDS) {
  6370. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6371. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6372. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6373. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6374. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6375. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6376. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6377. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6378. }
  6379. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6383. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6384. _this._activeTexturesCache = [];
  6385. texture._width = info.width;
  6386. texture._height = info.height;
  6387. texture.isReady = true;
  6388. }, null, null, true);
  6389. }
  6390. else {
  6391. cascadeLoad(rootUrl, scene, function (imgs) {
  6392. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6393. var height = width;
  6394. _this._prepareWorkingCanvas();
  6395. _this._workingCanvas.width = width;
  6396. _this._workingCanvas.height = height;
  6397. var faces = [
  6398. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6399. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6400. ];
  6401. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6402. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6403. for (var index = 0; index < faces.length; index++) {
  6404. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6405. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6406. }
  6407. if (!noMipmap) {
  6408. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6409. }
  6410. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6411. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6412. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6414. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6415. _this._activeTexturesCache = [];
  6416. texture._width = width;
  6417. texture._height = height;
  6418. texture.isReady = true;
  6419. }, extensions);
  6420. }
  6421. return texture;
  6422. };
  6423. Engine.prototype._releaseTexture = function (texture) {
  6424. var gl = this._gl;
  6425. if (texture._framebuffer) {
  6426. gl.deleteFramebuffer(texture._framebuffer);
  6427. }
  6428. if (texture._depthBuffer) {
  6429. gl.deleteRenderbuffer(texture._depthBuffer);
  6430. }
  6431. gl.deleteTexture(texture);
  6432. // Unbind channels
  6433. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6434. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6435. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6436. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6437. this._activeTexturesCache[channel] = null;
  6438. }
  6439. var index = this._loadedTexturesCache.indexOf(texture);
  6440. if (index !== -1) {
  6441. this._loadedTexturesCache.splice(index, 1);
  6442. }
  6443. };
  6444. Engine.prototype.bindSamplers = function (effect) {
  6445. this._gl.useProgram(effect.getProgram());
  6446. var samplers = effect.getSamplers();
  6447. for (var index = 0; index < samplers.length; index++) {
  6448. var uniform = effect.getUniform(samplers[index]);
  6449. this._gl.uniform1i(uniform, index);
  6450. }
  6451. this._currentEffect = null;
  6452. };
  6453. Engine.prototype._bindTexture = function (channel, texture) {
  6454. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6455. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6456. this._activeTexturesCache[channel] = null;
  6457. };
  6458. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6459. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6460. };
  6461. Engine.prototype.setTexture = function (channel, texture) {
  6462. if (channel < 0) {
  6463. return;
  6464. }
  6465. // Not ready?
  6466. if (!texture || !texture.isReady()) {
  6467. if (this._activeTexturesCache[channel] != null) {
  6468. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6469. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6470. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6471. this._activeTexturesCache[channel] = null;
  6472. }
  6473. return;
  6474. }
  6475. // Video
  6476. if (texture instanceof BABYLON.VideoTexture) {
  6477. if (texture.update()) {
  6478. this._activeTexturesCache[channel] = null;
  6479. }
  6480. }
  6481. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6482. texture.delayLoad();
  6483. return;
  6484. }
  6485. if (this._activeTexturesCache[channel] === texture) {
  6486. return;
  6487. }
  6488. this._activeTexturesCache[channel] = texture;
  6489. var internalTexture = texture.getInternalTexture();
  6490. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6491. if (internalTexture.isCube) {
  6492. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6493. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6494. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6495. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6496. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6497. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6498. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6499. }
  6500. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6501. }
  6502. else {
  6503. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6504. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6505. internalTexture._cachedWrapU = texture.wrapU;
  6506. switch (texture.wrapU) {
  6507. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6508. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6509. break;
  6510. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6511. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6512. break;
  6513. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6514. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6515. break;
  6516. }
  6517. }
  6518. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6519. internalTexture._cachedWrapV = texture.wrapV;
  6520. switch (texture.wrapV) {
  6521. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6522. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6523. break;
  6524. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6525. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6526. break;
  6527. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6528. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6529. break;
  6530. }
  6531. }
  6532. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6533. }
  6534. };
  6535. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6536. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6537. var value = texture.anisotropicFilteringLevel;
  6538. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6539. value = 1;
  6540. }
  6541. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6542. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6543. texture._cachedAnisotropicFilteringLevel = value;
  6544. }
  6545. };
  6546. Engine.prototype.readPixels = function (x, y, width, height) {
  6547. var data = new Uint8Array(height * width * 4);
  6548. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6549. return data;
  6550. };
  6551. // Dispose
  6552. Engine.prototype.dispose = function () {
  6553. this.hideLoadingUI();
  6554. this.stopRenderLoop();
  6555. // Release scenes
  6556. while (this.scenes.length) {
  6557. this.scenes[0].dispose();
  6558. }
  6559. // Release audio engine
  6560. Engine.audioEngine.dispose();
  6561. // Release effects
  6562. for (var name in this._compiledEffects) {
  6563. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6564. }
  6565. // Unbind
  6566. for (var i in this._vertexAttribArrays) {
  6567. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6568. continue;
  6569. }
  6570. this._gl.disableVertexAttribArray(i);
  6571. }
  6572. // Events
  6573. window.removeEventListener("blur", this._onBlur);
  6574. window.removeEventListener("focus", this._onFocus);
  6575. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6576. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6577. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6578. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6579. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6580. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6581. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6582. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6583. };
  6584. // Loading screen
  6585. Engine.prototype.displayLoadingUI = function () {
  6586. var _this = this;
  6587. this._loadingDiv = document.createElement("div");
  6588. this._loadingDiv.style.opacity = "0";
  6589. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6590. // Loading text
  6591. this._loadingTextDiv = document.createElement("div");
  6592. this._loadingTextDiv.style.position = "absolute";
  6593. this._loadingTextDiv.style.left = "0";
  6594. this._loadingTextDiv.style.top = "50%";
  6595. this._loadingTextDiv.style.marginTop = "80px";
  6596. this._loadingTextDiv.style.width = "100%";
  6597. this._loadingTextDiv.style.height = "20px";
  6598. this._loadingTextDiv.style.fontFamily = "Arial";
  6599. this._loadingTextDiv.style.fontSize = "14px";
  6600. this._loadingTextDiv.style.color = "white";
  6601. this._loadingTextDiv.style.textAlign = "center";
  6602. this._loadingTextDiv.innerHTML = "Loading";
  6603. this._loadingDiv.appendChild(this._loadingTextDiv);
  6604. // Loading img
  6605. var imgBack = new Image();
  6606. 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==";
  6607. imgBack.style.position = "absolute";
  6608. imgBack.style.left = "50%";
  6609. imgBack.style.top = "50%";
  6610. imgBack.style.marginLeft = "-50px";
  6611. imgBack.style.marginTop = "-50px";
  6612. imgBack.style.transition = "transform 1.0s ease";
  6613. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6614. var deg = 360;
  6615. var onTransitionEnd = function () {
  6616. deg += 360;
  6617. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6618. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6619. };
  6620. imgBack.addEventListener("transitionend", onTransitionEnd);
  6621. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6622. this._loadingDiv.appendChild(imgBack);
  6623. // front image
  6624. var imgFront = new Image();
  6625. 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=";
  6626. imgFront.style.position = "absolute";
  6627. imgFront.style.left = "50%";
  6628. imgFront.style.top = "50%";
  6629. imgFront.style.marginLeft = "-50px";
  6630. imgFront.style.marginTop = "-50px";
  6631. this._loadingDiv.appendChild(imgFront);
  6632. // Resize
  6633. this._resizeLoadingUI = function () {
  6634. var canvasRect = _this.getRenderingCanvasClientRect();
  6635. _this._loadingDiv.style.position = "absolute";
  6636. _this._loadingDiv.style.left = canvasRect.left + "px";
  6637. _this._loadingDiv.style.top = canvasRect.top + "px";
  6638. _this._loadingDiv.style.width = canvasRect.width + "px";
  6639. _this._loadingDiv.style.height = canvasRect.height + "px";
  6640. };
  6641. this._resizeLoadingUI();
  6642. window.addEventListener("resize", this._resizeLoadingUI);
  6643. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6644. document.body.appendChild(this._loadingDiv);
  6645. setTimeout(function () {
  6646. _this._loadingDiv.style.opacity = "1";
  6647. imgBack.style.transform = "rotateZ(360deg)";
  6648. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6649. }, 0);
  6650. };
  6651. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6652. set: function (text) {
  6653. if (!this._loadingDiv) {
  6654. return;
  6655. }
  6656. this._loadingTextDiv.innerHTML = text;
  6657. },
  6658. enumerable: true,
  6659. configurable: true
  6660. });
  6661. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6662. get: function () {
  6663. return this._loadingDivBackgroundColor;
  6664. },
  6665. set: function (color) {
  6666. this._loadingDivBackgroundColor = color;
  6667. if (!this._loadingDiv) {
  6668. return;
  6669. }
  6670. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Engine.prototype.hideLoadingUI = function () {
  6676. var _this = this;
  6677. if (!this._loadingDiv) {
  6678. return;
  6679. }
  6680. var onTransitionEnd = function () {
  6681. if (!_this._loadingDiv) {
  6682. return;
  6683. }
  6684. document.body.removeChild(_this._loadingDiv);
  6685. window.removeEventListener("resize", _this._resizeLoadingUI);
  6686. _this._loadingDiv = null;
  6687. };
  6688. this._loadingDiv.style.opacity = "0";
  6689. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6690. };
  6691. // FPS
  6692. Engine.prototype.getFps = function () {
  6693. return this.fps;
  6694. };
  6695. Engine.prototype.getDeltaTime = function () {
  6696. return this.deltaTime;
  6697. };
  6698. Engine.prototype._measureFps = function () {
  6699. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6700. var length = this.previousFramesDuration.length;
  6701. if (length >= 2) {
  6702. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6703. }
  6704. if (length >= this.fpsRange) {
  6705. if (length > this.fpsRange) {
  6706. this.previousFramesDuration.splice(0, 1);
  6707. length = this.previousFramesDuration.length;
  6708. }
  6709. var sum = 0;
  6710. for (var id = 0; id < length - 1; id++) {
  6711. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6712. }
  6713. this.fps = 1000.0 / (sum / (length - 1));
  6714. }
  6715. };
  6716. // Statics
  6717. Engine.isSupported = function () {
  6718. try {
  6719. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6720. if (navigator.isCocoonJS) {
  6721. return true;
  6722. }
  6723. var tempcanvas = document.createElement("canvas");
  6724. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6725. return gl != null && !!window.WebGLRenderingContext;
  6726. }
  6727. catch (e) {
  6728. return false;
  6729. }
  6730. };
  6731. // Const statics
  6732. Engine._ALPHA_DISABLE = 0;
  6733. Engine._ALPHA_ADD = 1;
  6734. Engine._ALPHA_COMBINE = 2;
  6735. Engine._DELAYLOADSTATE_NONE = 0;
  6736. Engine._DELAYLOADSTATE_LOADED = 1;
  6737. Engine._DELAYLOADSTATE_LOADING = 2;
  6738. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6739. Engine._TEXTUREFORMAT_ALPHA = 0;
  6740. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6741. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6742. Engine._TEXTUREFORMAT_RGB = 4;
  6743. Engine._TEXTUREFORMAT_RGBA = 4;
  6744. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6745. Engine._TEXTURETYPE_FLOAT = 1;
  6746. // Updatable statics so stick with vars here
  6747. Engine.Epsilon = 0.001;
  6748. Engine.CollisionsEpsilon = 0.001;
  6749. Engine.CodeRepository = "Babylon/";
  6750. Engine.ShadersRepository = "Babylon/Shaders/";
  6751. return Engine;
  6752. })();
  6753. BABYLON.Engine = Engine;
  6754. })(BABYLON || (BABYLON = {}));
  6755. //# sourceMappingURL=babylon.engine.js.map
  6756. var BABYLON;
  6757. (function (BABYLON) {
  6758. /**
  6759. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6760. */
  6761. var Node = (function () {
  6762. /**
  6763. * @constructor
  6764. * @param {string} name - the name and id to be given to this node
  6765. * @param {BABYLON.Scene} the scene this node will be added to
  6766. */
  6767. function Node(name, scene) {
  6768. this.state = "";
  6769. this.animations = new Array();
  6770. this._childrenFlag = -1;
  6771. this._isEnabled = true;
  6772. this._isReady = true;
  6773. this._currentRenderId = -1;
  6774. this._parentRenderId = -1;
  6775. this.name = name;
  6776. this.id = name;
  6777. this._scene = scene;
  6778. this._initCache();
  6779. }
  6780. Node.prototype.getScene = function () {
  6781. return this._scene;
  6782. };
  6783. Node.prototype.getEngine = function () {
  6784. return this._scene.getEngine();
  6785. };
  6786. // override it in derived class
  6787. Node.prototype.getWorldMatrix = function () {
  6788. return BABYLON.Matrix.Identity();
  6789. };
  6790. // override it in derived class if you add new variables to the cache
  6791. // and call the parent class method
  6792. Node.prototype._initCache = function () {
  6793. this._cache = {};
  6794. this._cache.parent = undefined;
  6795. };
  6796. Node.prototype.updateCache = function (force) {
  6797. if (!force && this.isSynchronized())
  6798. return;
  6799. this._cache.parent = this.parent;
  6800. this._updateCache();
  6801. };
  6802. // override it in derived class if you add new variables to the cache
  6803. // and call the parent class method if !ignoreParentClass
  6804. Node.prototype._updateCache = function (ignoreParentClass) {
  6805. };
  6806. // override it in derived class if you add new variables to the cache
  6807. Node.prototype._isSynchronized = function () {
  6808. return true;
  6809. };
  6810. Node.prototype._markSyncedWithParent = function () {
  6811. this._parentRenderId = this.parent._currentRenderId;
  6812. };
  6813. Node.prototype.isSynchronizedWithParent = function () {
  6814. if (!this.parent) {
  6815. return true;
  6816. }
  6817. if (this._parentRenderId !== this.parent._currentRenderId) {
  6818. return false;
  6819. }
  6820. return this.parent.isSynchronized();
  6821. };
  6822. Node.prototype.isSynchronized = function (updateCache) {
  6823. var check = this.hasNewParent();
  6824. check = check || !this.isSynchronizedWithParent();
  6825. check = check || !this._isSynchronized();
  6826. if (updateCache)
  6827. this.updateCache(true);
  6828. return !check;
  6829. };
  6830. Node.prototype.hasNewParent = function (update) {
  6831. if (this._cache.parent === this.parent)
  6832. return false;
  6833. if (update)
  6834. this._cache.parent = this.parent;
  6835. return true;
  6836. };
  6837. /**
  6838. * Is this node ready to be used/rendered
  6839. * @return {boolean} is it ready
  6840. */
  6841. Node.prototype.isReady = function () {
  6842. return this._isReady;
  6843. };
  6844. /**
  6845. * Is this node enabled.
  6846. * If the node has a parent and is enabled, the parent will be inspected as well.
  6847. * @return {boolean} whether this node (and its parent) is enabled.
  6848. * @see setEnabled
  6849. */
  6850. Node.prototype.isEnabled = function () {
  6851. if (!this._isEnabled) {
  6852. return false;
  6853. }
  6854. if (this.parent) {
  6855. return this.parent.isEnabled();
  6856. }
  6857. return true;
  6858. };
  6859. /**
  6860. * Set the enabled state of this node.
  6861. * @param {boolean} value - the new enabled state
  6862. * @see isEnabled
  6863. */
  6864. Node.prototype.setEnabled = function (value) {
  6865. this._isEnabled = value;
  6866. };
  6867. /**
  6868. * Is this node a descendant of the given node.
  6869. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6870. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6871. * @see parent
  6872. */
  6873. Node.prototype.isDescendantOf = function (ancestor) {
  6874. if (this.parent) {
  6875. if (this.parent === ancestor) {
  6876. return true;
  6877. }
  6878. return this.parent.isDescendantOf(ancestor);
  6879. }
  6880. return false;
  6881. };
  6882. Node.prototype._getDescendants = function (list, results) {
  6883. for (var index = 0; index < list.length; index++) {
  6884. var item = list[index];
  6885. if (item.isDescendantOf(this)) {
  6886. results.push(item);
  6887. }
  6888. }
  6889. };
  6890. /**
  6891. * Will return all nodes that have this node as parent.
  6892. * @return {BABYLON.Node[]} all children nodes of all types.
  6893. */
  6894. Node.prototype.getDescendants = function () {
  6895. var results = [];
  6896. this._getDescendants(this._scene.meshes, results);
  6897. this._getDescendants(this._scene.lights, results);
  6898. this._getDescendants(this._scene.cameras, results);
  6899. return results;
  6900. };
  6901. Node.prototype._setReady = function (state) {
  6902. if (state == this._isReady) {
  6903. return;
  6904. }
  6905. if (!state) {
  6906. this._isReady = false;
  6907. return;
  6908. }
  6909. this._isReady = true;
  6910. if (this.onReady) {
  6911. this.onReady(this);
  6912. }
  6913. };
  6914. return Node;
  6915. })();
  6916. BABYLON.Node = Node;
  6917. })(BABYLON || (BABYLON = {}));
  6918. //# sourceMappingURL=babylon.node.js.map
  6919. var BABYLON;
  6920. (function (BABYLON) {
  6921. var FilesInput = (function () {
  6922. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6923. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6924. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6925. this._engine = p_engine;
  6926. this._canvas = p_canvas;
  6927. this._currentScene = p_scene;
  6928. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6929. this._progressCallback = p_progressCallback;
  6930. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6931. this._textureLoadingCallback = p_textureLoadingCallback;
  6932. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6933. }
  6934. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6935. var _this = this;
  6936. if (p_elementToMonitor) {
  6937. this._elementToMonitor = p_elementToMonitor;
  6938. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  6939. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  6940. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  6941. }
  6942. };
  6943. FilesInput.prototype.renderFunction = function () {
  6944. if (this._additionnalRenderLoopLogicCallback) {
  6945. this._additionnalRenderLoopLogicCallback();
  6946. }
  6947. if (this._currentScene) {
  6948. if (this._textureLoadingCallback) {
  6949. var remaining = this._currentScene.getWaitingItemsCount();
  6950. if (remaining > 0) {
  6951. this._textureLoadingCallback(remaining);
  6952. }
  6953. }
  6954. this._currentScene.render();
  6955. }
  6956. };
  6957. FilesInput.prototype.drag = function (e) {
  6958. e.stopPropagation();
  6959. e.preventDefault();
  6960. };
  6961. FilesInput.prototype.drop = function (eventDrop) {
  6962. eventDrop.stopPropagation();
  6963. eventDrop.preventDefault();
  6964. this.loadFiles(eventDrop);
  6965. };
  6966. FilesInput.prototype.loadFiles = function (event) {
  6967. if (this._startingProcessingFilesCallback)
  6968. this._startingProcessingFilesCallback();
  6969. // Handling data transfer via drag'n'drop
  6970. if (event && event.dataTransfer && event.dataTransfer.files) {
  6971. this._filesToLoad = event.dataTransfer.files;
  6972. }
  6973. // Handling files from input files
  6974. if (event && event.target && event.target.files) {
  6975. this._filesToLoad = event.target.files;
  6976. }
  6977. if (this._filesToLoad && this._filesToLoad.length > 0) {
  6978. for (var i = 0; i < this._filesToLoad.length; i++) {
  6979. switch (this._filesToLoad[i].type) {
  6980. case "image/jpeg":
  6981. case "image/png":
  6982. case "image/bmp":
  6983. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  6984. break;
  6985. case "image/targa":
  6986. case "image/vnd.ms-dds":
  6987. case "audio/wav":
  6988. case "audio/x-wav":
  6989. case "audio/mp3":
  6990. case "audio/mpeg":
  6991. case "audio/mpeg3":
  6992. case "audio/x-mpeg-3":
  6993. case "audio/ogg":
  6994. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  6995. break;
  6996. default:
  6997. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  6998. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  6999. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  7000. this._sceneFileToLoad = this._filesToLoad[i];
  7001. }
  7002. break;
  7003. }
  7004. }
  7005. this.reload();
  7006. }
  7007. };
  7008. FilesInput.prototype.reload = function () {
  7009. var _this = this;
  7010. var that = this;
  7011. // If a ".babylon" file has been provided
  7012. if (this._sceneFileToLoad) {
  7013. if (this._currentScene) {
  7014. this._engine.stopRenderLoop();
  7015. this._currentScene.dispose();
  7016. }
  7017. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7018. that._currentScene = newScene;
  7019. // Wait for textures and shaders to be ready
  7020. that._currentScene.executeWhenReady(function () {
  7021. // Attach camera to canvas inputs
  7022. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7023. that._currentScene.createDefaultCameraOrLight();
  7024. }
  7025. that._currentScene.activeCamera.attachControl(that._canvas);
  7026. if (that._sceneLoadedCallback) {
  7027. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7028. }
  7029. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7030. });
  7031. }, function (progress) {
  7032. if (_this._progressCallback) {
  7033. _this._progressCallback(progress);
  7034. }
  7035. });
  7036. }
  7037. else {
  7038. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7039. }
  7040. };
  7041. FilesInput.FilesTextures = new Array();
  7042. FilesInput.FilesToLoad = new Array();
  7043. return FilesInput;
  7044. })();
  7045. BABYLON.FilesInput = FilesInput;
  7046. })(BABYLON || (BABYLON = {}));
  7047. //# sourceMappingURL=babylon.filesInput.js.map
  7048. var BABYLON;
  7049. (function (BABYLON) {
  7050. var IntersectionInfo = (function () {
  7051. function IntersectionInfo(bu, bv, distance) {
  7052. this.bu = bu;
  7053. this.bv = bv;
  7054. this.distance = distance;
  7055. this.faceId = 0;
  7056. this.subMeshId = 0;
  7057. }
  7058. return IntersectionInfo;
  7059. })();
  7060. BABYLON.IntersectionInfo = IntersectionInfo;
  7061. var PickingInfo = (function () {
  7062. function PickingInfo() {
  7063. this.hit = false;
  7064. this.distance = 0;
  7065. this.pickedPoint = null;
  7066. this.pickedMesh = null;
  7067. this.bu = 0;
  7068. this.bv = 0;
  7069. this.faceId = -1;
  7070. this.subMeshId = 0;
  7071. }
  7072. // Methods
  7073. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7074. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7075. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7076. return null;
  7077. }
  7078. var indices = this.pickedMesh.getIndices();
  7079. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7080. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7081. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7082. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7083. normal0 = normal0.scale(this.bu);
  7084. normal1 = normal1.scale(this.bv);
  7085. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7086. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7087. if (useWorldCoordinates) {
  7088. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7089. }
  7090. return result;
  7091. };
  7092. PickingInfo.prototype.getTextureCoordinates = function () {
  7093. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7094. return null;
  7095. }
  7096. var indices = this.pickedMesh.getIndices();
  7097. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7098. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7099. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7100. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7101. uv0 = uv0.scale(this.bu);
  7102. uv1 = uv1.scale(this.bv);
  7103. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7104. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7105. };
  7106. return PickingInfo;
  7107. })();
  7108. BABYLON.PickingInfo = PickingInfo;
  7109. })(BABYLON || (BABYLON = {}));
  7110. //# sourceMappingURL=babylon.pickingInfo.js.map
  7111. var BABYLON;
  7112. (function (BABYLON) {
  7113. var BoundingSphere = (function () {
  7114. function BoundingSphere(minimum, maximum) {
  7115. this.minimum = minimum;
  7116. this.maximum = maximum;
  7117. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7118. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7119. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7120. this.radius = distance * 0.5;
  7121. this.centerWorld = BABYLON.Vector3.Zero();
  7122. this._update(BABYLON.Matrix.Identity());
  7123. }
  7124. // Methods
  7125. BoundingSphere.prototype._update = function (world) {
  7126. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7127. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7128. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7129. };
  7130. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7131. for (var i = 0; i < 6; i++) {
  7132. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7133. return false;
  7134. }
  7135. return true;
  7136. };
  7137. BoundingSphere.prototype.intersectsPoint = function (point) {
  7138. var x = this.centerWorld.x - point.x;
  7139. var y = this.centerWorld.y - point.y;
  7140. var z = this.centerWorld.z - point.z;
  7141. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7142. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7143. return false;
  7144. return true;
  7145. };
  7146. // Statics
  7147. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7148. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7149. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7150. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7151. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7152. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7153. return false;
  7154. return true;
  7155. };
  7156. return BoundingSphere;
  7157. })();
  7158. BABYLON.BoundingSphere = BoundingSphere;
  7159. })(BABYLON || (BABYLON = {}));
  7160. //# sourceMappingURL=babylon.boundingSphere.js.map
  7161. var BABYLON;
  7162. (function (BABYLON) {
  7163. var BoundingBox = (function () {
  7164. function BoundingBox(minimum, maximum) {
  7165. this.minimum = minimum;
  7166. this.maximum = maximum;
  7167. this.vectors = new Array();
  7168. this.vectorsWorld = new Array();
  7169. // Bounding vectors
  7170. this.vectors.push(this.minimum.clone());
  7171. this.vectors.push(this.maximum.clone());
  7172. this.vectors.push(this.minimum.clone());
  7173. this.vectors[2].x = this.maximum.x;
  7174. this.vectors.push(this.minimum.clone());
  7175. this.vectors[3].y = this.maximum.y;
  7176. this.vectors.push(this.minimum.clone());
  7177. this.vectors[4].z = this.maximum.z;
  7178. this.vectors.push(this.maximum.clone());
  7179. this.vectors[5].z = this.minimum.z;
  7180. this.vectors.push(this.maximum.clone());
  7181. this.vectors[6].x = this.minimum.x;
  7182. this.vectors.push(this.maximum.clone());
  7183. this.vectors[7].y = this.minimum.y;
  7184. // OBB
  7185. this.center = this.maximum.add(this.minimum).scale(0.5);
  7186. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7187. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7188. // World
  7189. for (var index = 0; index < this.vectors.length; index++) {
  7190. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7191. }
  7192. this.minimumWorld = BABYLON.Vector3.Zero();
  7193. this.maximumWorld = BABYLON.Vector3.Zero();
  7194. this._update(BABYLON.Matrix.Identity());
  7195. }
  7196. // Methods
  7197. BoundingBox.prototype.getWorldMatrix = function () {
  7198. return this._worldMatrix;
  7199. };
  7200. BoundingBox.prototype._update = function (world) {
  7201. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7202. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7203. for (var index = 0; index < this.vectors.length; index++) {
  7204. var v = this.vectorsWorld[index];
  7205. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7206. if (v.x < this.minimumWorld.x)
  7207. this.minimumWorld.x = v.x;
  7208. if (v.y < this.minimumWorld.y)
  7209. this.minimumWorld.y = v.y;
  7210. if (v.z < this.minimumWorld.z)
  7211. this.minimumWorld.z = v.z;
  7212. if (v.x > this.maximumWorld.x)
  7213. this.maximumWorld.x = v.x;
  7214. if (v.y > this.maximumWorld.y)
  7215. this.maximumWorld.y = v.y;
  7216. if (v.z > this.maximumWorld.z)
  7217. this.maximumWorld.z = v.z;
  7218. }
  7219. // OBB
  7220. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7221. this.center.scaleInPlace(0.5);
  7222. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7223. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7224. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7225. this._worldMatrix = world;
  7226. };
  7227. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7228. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7229. };
  7230. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7231. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7232. };
  7233. BoundingBox.prototype.intersectsPoint = function (point) {
  7234. var delta = -BABYLON.Engine.Epsilon;
  7235. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7236. return false;
  7237. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7238. return false;
  7239. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7240. return false;
  7241. return true;
  7242. };
  7243. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7244. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7245. };
  7246. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7247. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7248. return false;
  7249. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7250. return false;
  7251. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7252. return false;
  7253. return true;
  7254. };
  7255. // Statics
  7256. BoundingBox.Intersects = function (box0, box1) {
  7257. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7258. return false;
  7259. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7260. return false;
  7261. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7262. return false;
  7263. return true;
  7264. };
  7265. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7266. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7267. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7268. return (num <= (sphereRadius * sphereRadius));
  7269. };
  7270. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7271. for (var p = 0; p < 6; p++) {
  7272. for (var i = 0; i < 8; i++) {
  7273. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7274. return false;
  7275. }
  7276. }
  7277. }
  7278. return true;
  7279. };
  7280. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7281. for (var p = 0; p < 6; p++) {
  7282. var inCount = 8;
  7283. for (var i = 0; i < 8; i++) {
  7284. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7285. --inCount;
  7286. }
  7287. else {
  7288. break;
  7289. }
  7290. }
  7291. if (inCount === 0)
  7292. return false;
  7293. }
  7294. return true;
  7295. };
  7296. return BoundingBox;
  7297. })();
  7298. BABYLON.BoundingBox = BoundingBox;
  7299. })(BABYLON || (BABYLON = {}));
  7300. //# sourceMappingURL=babylon.boundingBox.js.map
  7301. var BABYLON;
  7302. (function (BABYLON) {
  7303. var computeBoxExtents = function (axis, box) {
  7304. var p = BABYLON.Vector3.Dot(box.center, axis);
  7305. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7306. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7307. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7308. var r = r0 + r1 + r2;
  7309. return {
  7310. min: p - r,
  7311. max: p + r
  7312. };
  7313. };
  7314. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7315. var axisOverlap = function (axis, box0, box1) {
  7316. var result0 = computeBoxExtents(axis, box0);
  7317. var result1 = computeBoxExtents(axis, box1);
  7318. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7319. };
  7320. var BoundingInfo = (function () {
  7321. function BoundingInfo(minimum, maximum) {
  7322. this.minimum = minimum;
  7323. this.maximum = maximum;
  7324. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7325. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7326. }
  7327. // Methods
  7328. BoundingInfo.prototype._update = function (world) {
  7329. this.boundingBox._update(world);
  7330. this.boundingSphere._update(world);
  7331. };
  7332. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7333. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7334. return false;
  7335. return this.boundingBox.isInFrustum(frustumPlanes);
  7336. };
  7337. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7338. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7339. };
  7340. BoundingInfo.prototype._checkCollision = function (collider) {
  7341. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7342. };
  7343. BoundingInfo.prototype.intersectsPoint = function (point) {
  7344. if (!this.boundingSphere.centerWorld) {
  7345. return false;
  7346. }
  7347. if (!this.boundingSphere.intersectsPoint(point)) {
  7348. return false;
  7349. }
  7350. if (!this.boundingBox.intersectsPoint(point)) {
  7351. return false;
  7352. }
  7353. return true;
  7354. };
  7355. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7356. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7357. return false;
  7358. }
  7359. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7360. return false;
  7361. }
  7362. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7363. return false;
  7364. }
  7365. if (!precise) {
  7366. return true;
  7367. }
  7368. var box0 = this.boundingBox;
  7369. var box1 = boundingInfo.boundingBox;
  7370. if (!axisOverlap(box0.directions[0], box0, box1))
  7371. return false;
  7372. if (!axisOverlap(box0.directions[1], box0, box1))
  7373. return false;
  7374. if (!axisOverlap(box0.directions[2], box0, box1))
  7375. return false;
  7376. if (!axisOverlap(box1.directions[0], box0, box1))
  7377. return false;
  7378. if (!axisOverlap(box1.directions[1], box0, box1))
  7379. return false;
  7380. if (!axisOverlap(box1.directions[2], box0, box1))
  7381. return false;
  7382. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7383. return false;
  7384. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7385. return false;
  7386. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7387. return false;
  7388. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7389. return false;
  7390. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7391. return false;
  7392. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7393. return false;
  7394. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7395. return false;
  7396. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7397. return false;
  7398. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7399. return false;
  7400. return true;
  7401. };
  7402. return BoundingInfo;
  7403. })();
  7404. BABYLON.BoundingInfo = BoundingInfo;
  7405. })(BABYLON || (BABYLON = {}));
  7406. //# sourceMappingURL=babylon.boundingInfo.js.map
  7407. var __extends = this.__extends || function (d, b) {
  7408. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7409. function __() { this.constructor = d; }
  7410. __.prototype = b.prototype;
  7411. d.prototype = new __();
  7412. };
  7413. var BABYLON;
  7414. (function (BABYLON) {
  7415. var AbstractMesh = (function (_super) {
  7416. __extends(AbstractMesh, _super);
  7417. function AbstractMesh(name, scene) {
  7418. var _this = this;
  7419. _super.call(this, name, scene);
  7420. // Properties
  7421. this.definedFacingForward = true; // orientation for POV movement & rotation
  7422. this.position = new BABYLON.Vector3(0, 0, 0);
  7423. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7424. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7425. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7426. this.visibility = 1.0;
  7427. this.alphaIndex = Number.MAX_VALUE;
  7428. this.infiniteDistance = false;
  7429. this.isVisible = true;
  7430. this.isPickable = true;
  7431. this.showBoundingBox = false;
  7432. this.showSubMeshesBoundingBox = false;
  7433. this.onDispose = null;
  7434. this.checkCollisions = false;
  7435. this.isBlocker = false;
  7436. this.renderingGroupId = 0;
  7437. this.receiveShadows = false;
  7438. this.renderOutline = false;
  7439. this.outlineColor = BABYLON.Color3.Red();
  7440. this.outlineWidth = 0.02;
  7441. this.renderOverlay = false;
  7442. this.overlayColor = BABYLON.Color3.Red();
  7443. this.overlayAlpha = 0.5;
  7444. this.hasVertexAlpha = false;
  7445. this.useVertexColors = true;
  7446. this.applyFog = true;
  7447. this.useOctreeForRenderingSelection = true;
  7448. this.useOctreeForPicking = true;
  7449. this.useOctreeForCollisions = true;
  7450. this.layerMask = 0x0FFFFFFF;
  7451. this.alwaysSelectAsActiveMesh = false;
  7452. // Physics
  7453. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7454. // Collisions
  7455. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7456. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7457. this._collider = new BABYLON.Collider();
  7458. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7459. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7460. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7461. // Cache
  7462. this._localScaling = BABYLON.Matrix.Zero();
  7463. this._localRotation = BABYLON.Matrix.Zero();
  7464. this._localTranslation = BABYLON.Matrix.Zero();
  7465. this._localBillboard = BABYLON.Matrix.Zero();
  7466. this._localPivotScaling = BABYLON.Matrix.Zero();
  7467. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7468. this._localWorld = BABYLON.Matrix.Zero();
  7469. this._worldMatrix = BABYLON.Matrix.Zero();
  7470. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7471. this._absolutePosition = BABYLON.Vector3.Zero();
  7472. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7473. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7474. this._isDirty = false;
  7475. this._pivotMatrix = BABYLON.Matrix.Identity();
  7476. this._isDisposed = false;
  7477. this._renderId = 0;
  7478. this._intersectionsInProgress = new Array();
  7479. this._onAfterWorldMatrixUpdate = new Array();
  7480. this._isWorldMatrixFrozen = false;
  7481. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7482. if (collidedMesh === void 0) { collidedMesh = null; }
  7483. //TODO move this to the collision coordinator!
  7484. if (_this.getScene().workerCollisions)
  7485. newPosition.multiplyInPlace(_this._collider.radius);
  7486. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7487. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7488. _this.position.addInPlace(_this._diffPositionForCollisions);
  7489. }
  7490. };
  7491. scene.addMesh(this);
  7492. }
  7493. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7494. get: function () {
  7495. return AbstractMesh._BILLBOARDMODE_NONE;
  7496. },
  7497. enumerable: true,
  7498. configurable: true
  7499. });
  7500. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7501. get: function () {
  7502. return AbstractMesh._BILLBOARDMODE_X;
  7503. },
  7504. enumerable: true,
  7505. configurable: true
  7506. });
  7507. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7508. get: function () {
  7509. return AbstractMesh._BILLBOARDMODE_Y;
  7510. },
  7511. enumerable: true,
  7512. configurable: true
  7513. });
  7514. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7515. get: function () {
  7516. return AbstractMesh._BILLBOARDMODE_Z;
  7517. },
  7518. enumerable: true,
  7519. configurable: true
  7520. });
  7521. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7522. get: function () {
  7523. return AbstractMesh._BILLBOARDMODE_ALL;
  7524. },
  7525. enumerable: true,
  7526. configurable: true
  7527. });
  7528. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7529. // Methods
  7530. get: function () {
  7531. return false;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. AbstractMesh.prototype.getLOD = function (camera) {
  7537. return this;
  7538. };
  7539. AbstractMesh.prototype.getTotalVertices = function () {
  7540. return 0;
  7541. };
  7542. AbstractMesh.prototype.getIndices = function () {
  7543. return null;
  7544. };
  7545. AbstractMesh.prototype.getVerticesData = function (kind) {
  7546. return null;
  7547. };
  7548. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7549. return false;
  7550. };
  7551. AbstractMesh.prototype.getBoundingInfo = function () {
  7552. if (this._masterMesh) {
  7553. return this._masterMesh.getBoundingInfo();
  7554. }
  7555. if (!this._boundingInfo) {
  7556. this._updateBoundingInfo();
  7557. }
  7558. return this._boundingInfo;
  7559. };
  7560. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7561. get: function () {
  7562. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. AbstractMesh.prototype._preActivate = function () {
  7568. };
  7569. AbstractMesh.prototype._activate = function (renderId) {
  7570. this._renderId = renderId;
  7571. };
  7572. AbstractMesh.prototype.getWorldMatrix = function () {
  7573. if (this._masterMesh) {
  7574. return this._masterMesh.getWorldMatrix();
  7575. }
  7576. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7577. this.computeWorldMatrix();
  7578. }
  7579. return this._worldMatrix;
  7580. };
  7581. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7582. get: function () {
  7583. return this._worldMatrix;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7589. get: function () {
  7590. return this._absolutePosition;
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7596. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7597. this.computeWorldMatrix(true);
  7598. this._isWorldMatrixFrozen = true;
  7599. };
  7600. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7601. this._isWorldMatrixFrozen = false;
  7602. this.computeWorldMatrix(true);
  7603. };
  7604. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7605. get: function () {
  7606. return this._isWorldMatrixFrozen;
  7607. },
  7608. enumerable: true,
  7609. configurable: true
  7610. });
  7611. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7612. if (!this.rotationQuaternion) {
  7613. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7614. this.rotation = BABYLON.Vector3.Zero();
  7615. }
  7616. if (!space || space === BABYLON.Space.LOCAL) {
  7617. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7618. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7619. }
  7620. else {
  7621. if (this.parent) {
  7622. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7623. invertParentWorldMatrix.invert();
  7624. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7625. }
  7626. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7627. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7628. }
  7629. };
  7630. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7631. var displacementVector = axis.scale(distance);
  7632. if (!space || space === BABYLON.Space.LOCAL) {
  7633. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7634. this.setPositionWithLocalVector(tempV3);
  7635. }
  7636. else {
  7637. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7638. }
  7639. };
  7640. AbstractMesh.prototype.getAbsolutePosition = function () {
  7641. this.computeWorldMatrix();
  7642. return this._absolutePosition;
  7643. };
  7644. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7645. if (!absolutePosition) {
  7646. return;
  7647. }
  7648. var absolutePositionX;
  7649. var absolutePositionY;
  7650. var absolutePositionZ;
  7651. if (absolutePosition.x === undefined) {
  7652. if (arguments.length < 3) {
  7653. return;
  7654. }
  7655. absolutePositionX = arguments[0];
  7656. absolutePositionY = arguments[1];
  7657. absolutePositionZ = arguments[2];
  7658. }
  7659. else {
  7660. absolutePositionX = absolutePosition.x;
  7661. absolutePositionY = absolutePosition.y;
  7662. absolutePositionZ = absolutePosition.z;
  7663. }
  7664. if (this.parent) {
  7665. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7666. invertParentWorldMatrix.invert();
  7667. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7668. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7669. }
  7670. else {
  7671. this.position.x = absolutePositionX;
  7672. this.position.y = absolutePositionY;
  7673. this.position.z = absolutePositionZ;
  7674. }
  7675. };
  7676. // ================================== Point of View Movement =================================
  7677. /**
  7678. * Perform relative position change from the point of view of behind the front of the mesh.
  7679. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7680. * Supports definition of mesh facing forward or backward.
  7681. * @param {number} amountRight
  7682. * @param {number} amountUp
  7683. * @param {number} amountForward
  7684. */
  7685. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7686. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7687. };
  7688. /**
  7689. * Calculate relative position change from the point of view of behind the front of the mesh.
  7690. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7691. * Supports definition of mesh facing forward or backward.
  7692. * @param {number} amountRight
  7693. * @param {number} amountUp
  7694. * @param {number} amountForward
  7695. */
  7696. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7697. var rotMatrix = new BABYLON.Matrix();
  7698. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7699. rotQuaternion.toRotationMatrix(rotMatrix);
  7700. var translationDelta = BABYLON.Vector3.Zero();
  7701. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7702. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7703. return translationDelta;
  7704. };
  7705. // ================================== Point of View Rotation =================================
  7706. /**
  7707. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7708. * Supports definition of mesh facing forward or backward.
  7709. * @param {number} flipBack
  7710. * @param {number} twirlClockwise
  7711. * @param {number} tiltRight
  7712. */
  7713. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7714. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7715. };
  7716. /**
  7717. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7718. * Supports definition of mesh facing forward or backward.
  7719. * @param {number} flipBack
  7720. * @param {number} twirlClockwise
  7721. * @param {number} tiltRight
  7722. */
  7723. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7724. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7725. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7726. };
  7727. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7728. this._pivotMatrix = matrix;
  7729. this._cache.pivotMatrixUpdated = true;
  7730. };
  7731. AbstractMesh.prototype.getPivotMatrix = function () {
  7732. return this._pivotMatrix;
  7733. };
  7734. AbstractMesh.prototype._isSynchronized = function () {
  7735. if (this._isDirty) {
  7736. return false;
  7737. }
  7738. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7739. return false;
  7740. if (this._cache.pivotMatrixUpdated) {
  7741. return false;
  7742. }
  7743. if (this.infiniteDistance) {
  7744. return false;
  7745. }
  7746. if (!this._cache.position.equals(this.position))
  7747. return false;
  7748. if (this.rotationQuaternion) {
  7749. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7750. return false;
  7751. }
  7752. else {
  7753. if (!this._cache.rotation.equals(this.rotation))
  7754. return false;
  7755. }
  7756. if (!this._cache.scaling.equals(this.scaling))
  7757. return false;
  7758. return true;
  7759. };
  7760. AbstractMesh.prototype._initCache = function () {
  7761. _super.prototype._initCache.call(this);
  7762. this._cache.localMatrixUpdated = false;
  7763. this._cache.position = BABYLON.Vector3.Zero();
  7764. this._cache.scaling = BABYLON.Vector3.Zero();
  7765. this._cache.rotation = BABYLON.Vector3.Zero();
  7766. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7767. };
  7768. AbstractMesh.prototype.markAsDirty = function (property) {
  7769. if (property === "rotation") {
  7770. this.rotationQuaternion = null;
  7771. }
  7772. this._currentRenderId = Number.MAX_VALUE;
  7773. this._isDirty = true;
  7774. };
  7775. AbstractMesh.prototype._updateBoundingInfo = function () {
  7776. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7777. this._boundingInfo._update(this.worldMatrixFromCache);
  7778. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7779. };
  7780. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7781. if (!this.subMeshes) {
  7782. return;
  7783. }
  7784. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7785. var subMesh = this.subMeshes[subIndex];
  7786. subMesh.updateBoundingInfo(matrix);
  7787. }
  7788. };
  7789. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7790. if (this._isWorldMatrixFrozen) {
  7791. return this._worldMatrix;
  7792. }
  7793. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7794. return this._worldMatrix;
  7795. }
  7796. this._cache.position.copyFrom(this.position);
  7797. this._cache.scaling.copyFrom(this.scaling);
  7798. this._cache.pivotMatrixUpdated = false;
  7799. this._currentRenderId = this.getScene().getRenderId();
  7800. this._isDirty = false;
  7801. // Scaling
  7802. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7803. // Rotation
  7804. if (this.rotationQuaternion) {
  7805. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7806. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7807. }
  7808. else {
  7809. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7810. this._cache.rotation.copyFrom(this.rotation);
  7811. }
  7812. // Translation
  7813. if (this.infiniteDistance && !this.parent) {
  7814. var camera = this.getScene().activeCamera;
  7815. var cameraWorldMatrix = camera.getWorldMatrix();
  7816. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7817. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7818. }
  7819. else {
  7820. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7821. }
  7822. // Composing transformations
  7823. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7824. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7825. // Billboarding
  7826. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7827. var localPosition = this.position.clone();
  7828. var zero = this.getScene().activeCamera.globalPosition.clone();
  7829. if (this.parent && this.parent.position) {
  7830. localPosition.addInPlace(this.parent.position);
  7831. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7832. }
  7833. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7834. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7835. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7836. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7837. zero.y = localPosition.y + 0.001;
  7838. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7839. zero.z = localPosition.z + 0.001;
  7840. }
  7841. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7842. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7843. this._localBillboard.invert();
  7844. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7845. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7846. }
  7847. // Local world
  7848. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7849. // Parent
  7850. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7851. this._markSyncedWithParent();
  7852. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7853. }
  7854. else {
  7855. this._worldMatrix.copyFrom(this._localWorld);
  7856. }
  7857. // Bounding info
  7858. this._updateBoundingInfo();
  7859. // Absolute position
  7860. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7861. // Callbacks
  7862. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7863. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7864. }
  7865. return this._worldMatrix;
  7866. };
  7867. /**
  7868. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7869. * @param func: callback function to add
  7870. */
  7871. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7872. this._onAfterWorldMatrixUpdate.push(func);
  7873. };
  7874. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7875. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7876. if (index > -1) {
  7877. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7878. }
  7879. };
  7880. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7881. this.computeWorldMatrix();
  7882. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7883. };
  7884. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7885. this.computeWorldMatrix();
  7886. var invLocalWorldMatrix = this._localWorld.clone();
  7887. invLocalWorldMatrix.invert();
  7888. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7889. };
  7890. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7891. this.computeWorldMatrix();
  7892. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7893. };
  7894. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7895. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7896. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7897. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7898. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7899. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7900. /// <returns>Mesh oriented towards targetMesh</returns>
  7901. yawCor = yawCor || 0; // default to zero if undefined
  7902. pitchCor = pitchCor || 0;
  7903. rollCor = rollCor || 0;
  7904. var dv = targetPoint.subtract(this.position);
  7905. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7906. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7907. var pitch = Math.atan2(dv.y, len);
  7908. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7909. };
  7910. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7911. return this._boundingInfo.isInFrustum(frustumPlanes);
  7912. };
  7913. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7914. if (!camera) {
  7915. camera = this.getScene().activeCamera;
  7916. }
  7917. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7918. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7919. return false;
  7920. }
  7921. return true;
  7922. };
  7923. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7924. if (!this._boundingInfo || !mesh._boundingInfo) {
  7925. return false;
  7926. }
  7927. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7928. };
  7929. AbstractMesh.prototype.intersectsPoint = function (point) {
  7930. if (!this._boundingInfo) {
  7931. return false;
  7932. }
  7933. return this._boundingInfo.intersectsPoint(point);
  7934. };
  7935. // Physics
  7936. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7937. var physicsEngine = this.getScene().getPhysicsEngine();
  7938. if (!physicsEngine) {
  7939. return;
  7940. }
  7941. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7942. if (impostor.impostor) {
  7943. // Old API
  7944. options = impostor;
  7945. impostor = impostor.impostor;
  7946. }
  7947. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7948. physicsEngine._unregisterMesh(this);
  7949. return;
  7950. }
  7951. if (!options) {
  7952. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  7953. }
  7954. else {
  7955. if (!options.mass && options.mass !== 0)
  7956. options.mass = 0;
  7957. if (!options.friction && options.friction !== 0)
  7958. options.friction = 0.2;
  7959. if (!options.restitution && options.restitution !== 0)
  7960. options.restitution = 0.2;
  7961. }
  7962. this._physicImpostor = impostor;
  7963. this._physicsMass = options.mass;
  7964. this._physicsFriction = options.friction;
  7965. this._physicRestitution = options.restitution;
  7966. return physicsEngine._registerMesh(this, impostor, options);
  7967. };
  7968. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7969. if (!this._physicImpostor) {
  7970. return BABYLON.PhysicsEngine.NoImpostor;
  7971. }
  7972. return this._physicImpostor;
  7973. };
  7974. AbstractMesh.prototype.getPhysicsMass = function () {
  7975. if (!this._physicsMass) {
  7976. return 0;
  7977. }
  7978. return this._physicsMass;
  7979. };
  7980. AbstractMesh.prototype.getPhysicsFriction = function () {
  7981. if (!this._physicsFriction) {
  7982. return 0;
  7983. }
  7984. return this._physicsFriction;
  7985. };
  7986. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7987. if (!this._physicRestitution) {
  7988. return 0;
  7989. }
  7990. return this._physicRestitution;
  7991. };
  7992. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  7993. if (!camera) {
  7994. camera = this.getScene().activeCamera;
  7995. }
  7996. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  7997. };
  7998. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  7999. if (!camera) {
  8000. camera = this.getScene().activeCamera;
  8001. }
  8002. return this.absolutePosition.subtract(camera.position).length();
  8003. };
  8004. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8005. if (!this._physicImpostor) {
  8006. return;
  8007. }
  8008. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8009. };
  8010. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8011. if (!this._physicImpostor) {
  8012. return;
  8013. }
  8014. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8015. };
  8016. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8017. if (!this._physicImpostor) {
  8018. return;
  8019. }
  8020. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8021. };
  8022. // Collisions
  8023. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8024. var globalPosition = this.getAbsolutePosition();
  8025. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8026. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8027. this._collider.radius = this.ellipsoid;
  8028. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8029. };
  8030. // Submeshes octree
  8031. /**
  8032. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8033. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8034. */
  8035. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8036. if (maxCapacity === void 0) { maxCapacity = 64; }
  8037. if (maxDepth === void 0) { maxDepth = 2; }
  8038. if (!this._submeshesOctree) {
  8039. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8040. }
  8041. this.computeWorldMatrix(true);
  8042. // Update octree
  8043. var bbox = this.getBoundingInfo().boundingBox;
  8044. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8045. return this._submeshesOctree;
  8046. };
  8047. // Collisions
  8048. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8049. this._generatePointsArray();
  8050. // Transformation
  8051. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8052. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8053. subMesh._lastColliderWorldVertices = [];
  8054. subMesh._trianglePlanes = [];
  8055. var start = subMesh.verticesStart;
  8056. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8057. for (var i = start; i < end; i++) {
  8058. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8059. }
  8060. }
  8061. // Collide
  8062. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8063. if (collider.collisionFound) {
  8064. collider.collidedMesh = this;
  8065. }
  8066. };
  8067. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8068. var subMeshes;
  8069. var len;
  8070. // Octrees
  8071. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8072. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8073. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8074. len = intersections.length;
  8075. subMeshes = intersections.data;
  8076. }
  8077. else {
  8078. subMeshes = this.subMeshes;
  8079. len = subMeshes.length;
  8080. }
  8081. for (var index = 0; index < len; index++) {
  8082. var subMesh = subMeshes[index];
  8083. // Bounding test
  8084. if (len > 1 && !subMesh._checkCollision(collider))
  8085. continue;
  8086. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8087. }
  8088. };
  8089. AbstractMesh.prototype._checkCollision = function (collider) {
  8090. // Bounding box test
  8091. if (!this._boundingInfo._checkCollision(collider))
  8092. return;
  8093. // Transformation matrix
  8094. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8095. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8096. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8097. };
  8098. // Picking
  8099. AbstractMesh.prototype._generatePointsArray = function () {
  8100. return false;
  8101. };
  8102. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8103. var pickingInfo = new BABYLON.PickingInfo();
  8104. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8105. return pickingInfo;
  8106. }
  8107. if (!this._generatePointsArray()) {
  8108. return pickingInfo;
  8109. }
  8110. var intersectInfo = null;
  8111. // Octrees
  8112. var subMeshes;
  8113. var len;
  8114. if (this._submeshesOctree && this.useOctreeForPicking) {
  8115. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8116. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8117. len = intersections.length;
  8118. subMeshes = intersections.data;
  8119. }
  8120. else {
  8121. subMeshes = this.subMeshes;
  8122. len = subMeshes.length;
  8123. }
  8124. for (var index = 0; index < len; index++) {
  8125. var subMesh = subMeshes[index];
  8126. // Bounding test
  8127. if (len > 1 && !subMesh.canIntersects(ray))
  8128. continue;
  8129. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8130. if (currentIntersectInfo) {
  8131. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8132. intersectInfo = currentIntersectInfo;
  8133. intersectInfo.subMeshId = index;
  8134. if (fastCheck) {
  8135. break;
  8136. }
  8137. }
  8138. }
  8139. }
  8140. if (intersectInfo) {
  8141. // Get picked point
  8142. var world = this.getWorldMatrix();
  8143. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8144. var direction = ray.direction.clone();
  8145. direction = direction.scale(intersectInfo.distance);
  8146. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8147. var pickedPoint = worldOrigin.add(worldDirection);
  8148. // Return result
  8149. pickingInfo.hit = true;
  8150. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8151. pickingInfo.pickedPoint = pickedPoint;
  8152. pickingInfo.pickedMesh = this;
  8153. pickingInfo.bu = intersectInfo.bu;
  8154. pickingInfo.bv = intersectInfo.bv;
  8155. pickingInfo.faceId = intersectInfo.faceId;
  8156. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8157. return pickingInfo;
  8158. }
  8159. return pickingInfo;
  8160. };
  8161. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8162. return null;
  8163. };
  8164. AbstractMesh.prototype.releaseSubMeshes = function () {
  8165. if (this.subMeshes) {
  8166. while (this.subMeshes.length) {
  8167. this.subMeshes[0].dispose();
  8168. }
  8169. }
  8170. else {
  8171. this.subMeshes = new Array();
  8172. }
  8173. };
  8174. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8175. var index;
  8176. // Physics
  8177. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8178. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8179. }
  8180. // Intersections in progress
  8181. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8182. var other = this._intersectionsInProgress[index];
  8183. var pos = other._intersectionsInProgress.indexOf(this);
  8184. other._intersectionsInProgress.splice(pos, 1);
  8185. }
  8186. this._intersectionsInProgress = [];
  8187. // SubMeshes
  8188. this.releaseSubMeshes();
  8189. // Remove from scene
  8190. this.getScene().removeMesh(this);
  8191. if (!doNotRecurse) {
  8192. // Particles
  8193. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8194. if (this.getScene().particleSystems[index].emitter === this) {
  8195. this.getScene().particleSystems[index].dispose();
  8196. index--;
  8197. }
  8198. }
  8199. // Children
  8200. var objects = this.getScene().meshes.slice(0);
  8201. for (index = 0; index < objects.length; index++) {
  8202. if (objects[index].parent === this) {
  8203. objects[index].dispose();
  8204. }
  8205. }
  8206. }
  8207. else {
  8208. for (index = 0; index < this.getScene().meshes.length; index++) {
  8209. var obj = this.getScene().meshes[index];
  8210. if (obj.parent === this) {
  8211. obj.parent = null;
  8212. obj.computeWorldMatrix(true);
  8213. }
  8214. }
  8215. }
  8216. this._onAfterWorldMatrixUpdate = [];
  8217. this._isDisposed = true;
  8218. // Callback
  8219. if (this.onDispose) {
  8220. this.onDispose();
  8221. }
  8222. };
  8223. // Statics
  8224. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8225. AbstractMesh._BILLBOARDMODE_X = 1;
  8226. AbstractMesh._BILLBOARDMODE_Y = 2;
  8227. AbstractMesh._BILLBOARDMODE_Z = 4;
  8228. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8229. return AbstractMesh;
  8230. })(BABYLON.Node);
  8231. BABYLON.AbstractMesh = AbstractMesh;
  8232. })(BABYLON || (BABYLON = {}));
  8233. //# sourceMappingURL=babylon.abstractMesh.js.map
  8234. var __extends = this.__extends || function (d, b) {
  8235. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8236. function __() { this.constructor = d; }
  8237. __.prototype = b.prototype;
  8238. d.prototype = new __();
  8239. };
  8240. var BABYLON;
  8241. (function (BABYLON) {
  8242. var Light = (function (_super) {
  8243. __extends(Light, _super);
  8244. function Light(name, scene) {
  8245. _super.call(this, name, scene);
  8246. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8247. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8248. this.intensity = 1.0;
  8249. this.range = Number.MAX_VALUE;
  8250. this.includeOnlyWithLayerMask = 0;
  8251. this.includedOnlyMeshes = new Array();
  8252. this.excludedMeshes = new Array();
  8253. this.excludeWithLayerMask = 0;
  8254. this._excludedMeshesIds = new Array();
  8255. this._includedOnlyMeshesIds = new Array();
  8256. scene.addLight(this);
  8257. }
  8258. Light.prototype.getShadowGenerator = function () {
  8259. return this._shadowGenerator;
  8260. };
  8261. Light.prototype.getAbsolutePosition = function () {
  8262. return BABYLON.Vector3.Zero();
  8263. };
  8264. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8265. };
  8266. Light.prototype._getWorldMatrix = function () {
  8267. return BABYLON.Matrix.Identity();
  8268. };
  8269. Light.prototype.canAffectMesh = function (mesh) {
  8270. if (!mesh) {
  8271. return true;
  8272. }
  8273. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8274. return false;
  8275. }
  8276. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8277. return false;
  8278. }
  8279. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8280. return false;
  8281. }
  8282. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8283. return false;
  8284. }
  8285. return true;
  8286. };
  8287. Light.prototype.getWorldMatrix = function () {
  8288. this._currentRenderId = this.getScene().getRenderId();
  8289. var worldMatrix = this._getWorldMatrix();
  8290. if (this.parent && this.parent.getWorldMatrix) {
  8291. if (!this._parentedWorldMatrix) {
  8292. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8293. }
  8294. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8295. this._markSyncedWithParent();
  8296. return this._parentedWorldMatrix;
  8297. }
  8298. return worldMatrix;
  8299. };
  8300. Light.prototype.dispose = function () {
  8301. if (this._shadowGenerator) {
  8302. this._shadowGenerator.dispose();
  8303. this._shadowGenerator = null;
  8304. }
  8305. // Remove from scene
  8306. this.getScene().removeLight(this);
  8307. };
  8308. return Light;
  8309. })(BABYLON.Node);
  8310. BABYLON.Light = Light;
  8311. })(BABYLON || (BABYLON = {}));
  8312. //# sourceMappingURL=babylon.light.js.map
  8313. var __extends = this.__extends || function (d, b) {
  8314. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8315. function __() { this.constructor = d; }
  8316. __.prototype = b.prototype;
  8317. d.prototype = new __();
  8318. };
  8319. var BABYLON;
  8320. (function (BABYLON) {
  8321. var PointLight = (function (_super) {
  8322. __extends(PointLight, _super);
  8323. function PointLight(name, position, scene) {
  8324. _super.call(this, name, scene);
  8325. this.position = position;
  8326. }
  8327. PointLight.prototype.getAbsolutePosition = function () {
  8328. return this._transformedPosition ? this._transformedPosition : this.position;
  8329. };
  8330. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8331. if (this.parent && this.parent.getWorldMatrix) {
  8332. if (!this._transformedPosition) {
  8333. this._transformedPosition = BABYLON.Vector3.Zero();
  8334. }
  8335. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8336. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8337. return;
  8338. }
  8339. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8340. };
  8341. PointLight.prototype.getShadowGenerator = function () {
  8342. return null;
  8343. };
  8344. PointLight.prototype._getWorldMatrix = function () {
  8345. if (!this._worldMatrix) {
  8346. this._worldMatrix = BABYLON.Matrix.Identity();
  8347. }
  8348. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8349. return this._worldMatrix;
  8350. };
  8351. return PointLight;
  8352. })(BABYLON.Light);
  8353. BABYLON.PointLight = PointLight;
  8354. })(BABYLON || (BABYLON = {}));
  8355. //# sourceMappingURL=babylon.pointLight.js.map
  8356. var __extends = this.__extends || function (d, b) {
  8357. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8358. function __() { this.constructor = d; }
  8359. __.prototype = b.prototype;
  8360. d.prototype = new __();
  8361. };
  8362. var BABYLON;
  8363. (function (BABYLON) {
  8364. var SpotLight = (function (_super) {
  8365. __extends(SpotLight, _super);
  8366. function SpotLight(name, position, direction, angle, exponent, scene) {
  8367. _super.call(this, name, scene);
  8368. this.position = position;
  8369. this.direction = direction;
  8370. this.angle = angle;
  8371. this.exponent = exponent;
  8372. }
  8373. SpotLight.prototype.getAbsolutePosition = function () {
  8374. return this.transformedPosition ? this.transformedPosition : this.position;
  8375. };
  8376. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8377. var activeCamera = this.getScene().activeCamera;
  8378. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8379. };
  8380. SpotLight.prototype.supportsVSM = function () {
  8381. return true;
  8382. };
  8383. SpotLight.prototype.needRefreshPerFrame = function () {
  8384. return false;
  8385. };
  8386. SpotLight.prototype.setDirectionToTarget = function (target) {
  8387. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8388. return this.direction;
  8389. };
  8390. SpotLight.prototype.computeTransformedPosition = function () {
  8391. if (this.parent && this.parent.getWorldMatrix) {
  8392. if (!this.transformedPosition) {
  8393. this.transformedPosition = BABYLON.Vector3.Zero();
  8394. }
  8395. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8396. return true;
  8397. }
  8398. return false;
  8399. };
  8400. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8401. var normalizeDirection;
  8402. if (this.parent && this.parent.getWorldMatrix) {
  8403. if (!this._transformedDirection) {
  8404. this._transformedDirection = BABYLON.Vector3.Zero();
  8405. }
  8406. this.computeTransformedPosition();
  8407. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8408. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8409. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8410. }
  8411. else {
  8412. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8413. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8414. }
  8415. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8416. };
  8417. SpotLight.prototype._getWorldMatrix = function () {
  8418. if (!this._worldMatrix) {
  8419. this._worldMatrix = BABYLON.Matrix.Identity();
  8420. }
  8421. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8422. return this._worldMatrix;
  8423. };
  8424. return SpotLight;
  8425. })(BABYLON.Light);
  8426. BABYLON.SpotLight = SpotLight;
  8427. })(BABYLON || (BABYLON = {}));
  8428. //# sourceMappingURL=babylon.spotLight.js.map
  8429. var __extends = this.__extends || function (d, b) {
  8430. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8431. function __() { this.constructor = d; }
  8432. __.prototype = b.prototype;
  8433. d.prototype = new __();
  8434. };
  8435. var BABYLON;
  8436. (function (BABYLON) {
  8437. var HemisphericLight = (function (_super) {
  8438. __extends(HemisphericLight, _super);
  8439. function HemisphericLight(name, direction, scene) {
  8440. _super.call(this, name, scene);
  8441. this.direction = direction;
  8442. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8443. }
  8444. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8445. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8446. return this.direction;
  8447. };
  8448. HemisphericLight.prototype.getShadowGenerator = function () {
  8449. return null;
  8450. };
  8451. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8452. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8453. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8454. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8455. };
  8456. HemisphericLight.prototype._getWorldMatrix = function () {
  8457. if (!this._worldMatrix) {
  8458. this._worldMatrix = BABYLON.Matrix.Identity();
  8459. }
  8460. return this._worldMatrix;
  8461. };
  8462. return HemisphericLight;
  8463. })(BABYLON.Light);
  8464. BABYLON.HemisphericLight = HemisphericLight;
  8465. })(BABYLON || (BABYLON = {}));
  8466. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8467. var __extends = this.__extends || function (d, b) {
  8468. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8469. function __() { this.constructor = d; }
  8470. __.prototype = b.prototype;
  8471. d.prototype = new __();
  8472. };
  8473. var BABYLON;
  8474. (function (BABYLON) {
  8475. var DirectionalLight = (function (_super) {
  8476. __extends(DirectionalLight, _super);
  8477. function DirectionalLight(name, direction, scene) {
  8478. _super.call(this, name, scene);
  8479. this.direction = direction;
  8480. this.shadowOrthoScale = 0.5;
  8481. this.position = direction.scale(-1);
  8482. }
  8483. DirectionalLight.prototype.getAbsolutePosition = function () {
  8484. return this.transformedPosition ? this.transformedPosition : this.position;
  8485. };
  8486. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8487. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8488. return this.direction;
  8489. };
  8490. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8491. var orthoLeft = Number.MAX_VALUE;
  8492. var orthoRight = Number.MIN_VALUE;
  8493. var orthoTop = Number.MIN_VALUE;
  8494. var orthoBottom = Number.MAX_VALUE;
  8495. var tempVector3 = BABYLON.Vector3.Zero();
  8496. var activeCamera = this.getScene().activeCamera;
  8497. // Check extends
  8498. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8499. var mesh = renderList[meshIndex];
  8500. if (!mesh) {
  8501. continue;
  8502. }
  8503. var boundingInfo = mesh.getBoundingInfo();
  8504. if (!boundingInfo) {
  8505. continue;
  8506. }
  8507. var boundingBox = boundingInfo.boundingBox;
  8508. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8509. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8510. if (tempVector3.x < orthoLeft)
  8511. orthoLeft = tempVector3.x;
  8512. if (tempVector3.y < orthoBottom)
  8513. orthoBottom = tempVector3.y;
  8514. if (tempVector3.x > orthoRight)
  8515. orthoRight = tempVector3.x;
  8516. if (tempVector3.y > orthoTop)
  8517. orthoTop = tempVector3.y;
  8518. }
  8519. }
  8520. var xOffset = orthoRight - orthoLeft;
  8521. var yOffset = orthoTop - orthoBottom;
  8522. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8523. };
  8524. DirectionalLight.prototype.supportsVSM = function () {
  8525. return true;
  8526. };
  8527. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8528. return true;
  8529. };
  8530. DirectionalLight.prototype.computeTransformedPosition = function () {
  8531. if (this.parent && this.parent.getWorldMatrix) {
  8532. if (!this.transformedPosition) {
  8533. this.transformedPosition = BABYLON.Vector3.Zero();
  8534. }
  8535. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8536. return true;
  8537. }
  8538. return false;
  8539. };
  8540. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8541. if (this.parent && this.parent.getWorldMatrix) {
  8542. if (!this._transformedDirection) {
  8543. this._transformedDirection = BABYLON.Vector3.Zero();
  8544. }
  8545. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8546. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8547. return;
  8548. }
  8549. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8550. };
  8551. DirectionalLight.prototype._getWorldMatrix = function () {
  8552. if (!this._worldMatrix) {
  8553. this._worldMatrix = BABYLON.Matrix.Identity();
  8554. }
  8555. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8556. return this._worldMatrix;
  8557. };
  8558. return DirectionalLight;
  8559. })(BABYLON.Light);
  8560. BABYLON.DirectionalLight = DirectionalLight;
  8561. })(BABYLON || (BABYLON = {}));
  8562. //# sourceMappingURL=babylon.directionalLight.js.map
  8563. var BABYLON;
  8564. (function (BABYLON) {
  8565. var ShadowGenerator = (function () {
  8566. function ShadowGenerator(mapSize, light) {
  8567. var _this = this;
  8568. // Members
  8569. this._filter = ShadowGenerator.FILTER_NONE;
  8570. this.blurScale = 2;
  8571. this._blurBoxOffset = 0;
  8572. this._bias = 0.00005;
  8573. this._darkness = 0;
  8574. this._transparencyShadow = false;
  8575. this._viewMatrix = BABYLON.Matrix.Zero();
  8576. this._projectionMatrix = BABYLON.Matrix.Zero();
  8577. this._transformMatrix = BABYLON.Matrix.Zero();
  8578. this._worldViewProjection = BABYLON.Matrix.Zero();
  8579. this._light = light;
  8580. this._scene = light.getScene();
  8581. this._mapSize = mapSize;
  8582. light._shadowGenerator = this;
  8583. // Render target
  8584. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8585. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8586. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8587. this._shadowMap.anisotropicFilteringLevel = 1;
  8588. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8589. this._shadowMap.renderParticles = false;
  8590. this._shadowMap.onAfterUnbind = function () {
  8591. if (!_this.useBlurVarianceShadowMap) {
  8592. return;
  8593. }
  8594. if (!_this._shadowMap2) {
  8595. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8596. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8597. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8598. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8599. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8600. _this._downSamplePostprocess.onApply = function (effect) {
  8601. effect.setTexture("textureSampler", _this._shadowMap);
  8602. };
  8603. _this.blurBoxOffset = 1;
  8604. }
  8605. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8606. };
  8607. // Custom render function
  8608. var renderSubMesh = function (subMesh) {
  8609. var mesh = subMesh.getRenderingMesh();
  8610. var scene = _this._scene;
  8611. var engine = scene.getEngine();
  8612. // Culling
  8613. engine.setState(subMesh.getMaterial().backFaceCulling);
  8614. // Managing instances
  8615. var batch = mesh._getInstancesRenderList(subMesh._id);
  8616. if (batch.mustReturn) {
  8617. return;
  8618. }
  8619. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8620. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8621. engine.enableEffect(_this._effect);
  8622. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8623. var material = subMesh.getMaterial();
  8624. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8625. // Alpha test
  8626. if (material && material.needAlphaTesting()) {
  8627. var alphaTexture = material.getAlphaTestTexture();
  8628. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8629. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8630. }
  8631. // Bones
  8632. if (mesh.useBones) {
  8633. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8634. }
  8635. // Draw
  8636. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8637. }
  8638. else {
  8639. // Need to reset refresh rate of the shadowMap
  8640. _this._shadowMap.resetRefreshCounter();
  8641. }
  8642. };
  8643. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8644. var index;
  8645. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8646. renderSubMesh(opaqueSubMeshes.data[index]);
  8647. }
  8648. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8649. renderSubMesh(alphaTestSubMeshes.data[index]);
  8650. }
  8651. if (_this._transparencyShadow) {
  8652. for (index = 0; index < transparentSubMeshes.length; index++) {
  8653. renderSubMesh(transparentSubMeshes.data[index]);
  8654. }
  8655. }
  8656. };
  8657. this._shadowMap.onClear = function (engine) {
  8658. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8659. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8660. }
  8661. else {
  8662. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8663. }
  8664. };
  8665. }
  8666. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8667. // Static
  8668. get: function () {
  8669. return ShadowGenerator._FILTER_NONE;
  8670. },
  8671. enumerable: true,
  8672. configurable: true
  8673. });
  8674. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8675. get: function () {
  8676. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8677. },
  8678. enumerable: true,
  8679. configurable: true
  8680. });
  8681. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8682. get: function () {
  8683. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8684. },
  8685. enumerable: true,
  8686. configurable: true
  8687. });
  8688. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8689. get: function () {
  8690. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8691. },
  8692. enumerable: true,
  8693. configurable: true
  8694. });
  8695. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8696. get: function () {
  8697. return this._bias;
  8698. },
  8699. set: function (bias) {
  8700. this._bias = bias;
  8701. },
  8702. enumerable: true,
  8703. configurable: true
  8704. });
  8705. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8706. get: function () {
  8707. return this._blurBoxOffset;
  8708. },
  8709. set: function (value) {
  8710. var _this = this;
  8711. if (this._blurBoxOffset === value) {
  8712. return;
  8713. }
  8714. this._blurBoxOffset = value;
  8715. if (this._boxBlurPostprocess) {
  8716. this._boxBlurPostprocess.dispose();
  8717. }
  8718. 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);
  8719. this._boxBlurPostprocess.onApply = function (effect) {
  8720. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8721. };
  8722. },
  8723. enumerable: true,
  8724. configurable: true
  8725. });
  8726. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8727. get: function () {
  8728. return this._filter;
  8729. },
  8730. set: function (value) {
  8731. if (this._filter === value) {
  8732. return;
  8733. }
  8734. this._filter = value;
  8735. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8736. this._shadowMap.anisotropicFilteringLevel = 16;
  8737. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8738. }
  8739. else {
  8740. this._shadowMap.anisotropicFilteringLevel = 1;
  8741. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8742. }
  8743. },
  8744. enumerable: true,
  8745. configurable: true
  8746. });
  8747. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8748. get: function () {
  8749. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8750. },
  8751. set: function (value) {
  8752. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8753. },
  8754. enumerable: true,
  8755. configurable: true
  8756. });
  8757. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8758. get: function () {
  8759. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8760. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8761. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8762. },
  8763. set: function (value) {
  8764. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8765. },
  8766. enumerable: true,
  8767. configurable: true
  8768. });
  8769. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8770. get: function () {
  8771. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8772. },
  8773. set: function (value) {
  8774. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8775. },
  8776. enumerable: true,
  8777. configurable: true
  8778. });
  8779. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8780. var defines = [];
  8781. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8782. defines.push("#define VSM");
  8783. }
  8784. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8785. var mesh = subMesh.getMesh();
  8786. var material = subMesh.getMaterial();
  8787. // Alpha test
  8788. if (material && material.needAlphaTesting()) {
  8789. defines.push("#define ALPHATEST");
  8790. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8791. attribs.push(BABYLON.VertexBuffer.UVKind);
  8792. defines.push("#define UV1");
  8793. }
  8794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8795. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8796. defines.push("#define UV2");
  8797. }
  8798. }
  8799. // Bones
  8800. if (mesh.useBones) {
  8801. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8802. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8803. defines.push("#define BONES");
  8804. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8805. }
  8806. // Instances
  8807. if (useInstances) {
  8808. defines.push("#define INSTANCES");
  8809. attribs.push("world0");
  8810. attribs.push("world1");
  8811. attribs.push("world2");
  8812. attribs.push("world3");
  8813. }
  8814. // Get correct effect
  8815. var join = defines.join("\n");
  8816. if (this._cachedDefines !== join) {
  8817. this._cachedDefines = join;
  8818. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8819. }
  8820. return this._effect.isReady();
  8821. };
  8822. ShadowGenerator.prototype.getShadowMap = function () {
  8823. return this._shadowMap;
  8824. };
  8825. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8826. if (this._shadowMap2) {
  8827. return this._shadowMap2;
  8828. }
  8829. return this._shadowMap;
  8830. };
  8831. ShadowGenerator.prototype.getLight = function () {
  8832. return this._light;
  8833. };
  8834. // Methods
  8835. ShadowGenerator.prototype.getTransformMatrix = function () {
  8836. var scene = this._scene;
  8837. if (this._currentRenderID === scene.getRenderId()) {
  8838. return this._transformMatrix;
  8839. }
  8840. this._currentRenderID = scene.getRenderId();
  8841. var lightPosition = this._light.position;
  8842. var lightDirection = this._light.direction;
  8843. if (this._light.computeTransformedPosition()) {
  8844. lightPosition = this._light.transformedPosition;
  8845. }
  8846. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8847. this._cachedPosition = lightPosition.clone();
  8848. this._cachedDirection = lightDirection.clone();
  8849. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8850. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8851. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8852. }
  8853. return this._transformMatrix;
  8854. };
  8855. ShadowGenerator.prototype.getDarkness = function () {
  8856. return this._darkness;
  8857. };
  8858. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8859. if (darkness >= 1.0)
  8860. this._darkness = 1.0;
  8861. else if (darkness <= 0.0)
  8862. this._darkness = 0.0;
  8863. else
  8864. this._darkness = darkness;
  8865. };
  8866. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8867. this._transparencyShadow = hasShadow;
  8868. };
  8869. ShadowGenerator.prototype._packHalf = function (depth) {
  8870. var scale = depth * 255.0;
  8871. var fract = scale - Math.floor(scale);
  8872. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8873. };
  8874. ShadowGenerator.prototype.dispose = function () {
  8875. this._shadowMap.dispose();
  8876. if (this._shadowMap2) {
  8877. this._shadowMap2.dispose();
  8878. }
  8879. if (this._downSamplePostprocess) {
  8880. this._downSamplePostprocess.dispose();
  8881. }
  8882. if (this._boxBlurPostprocess) {
  8883. this._boxBlurPostprocess.dispose();
  8884. }
  8885. };
  8886. ShadowGenerator._FILTER_NONE = 0;
  8887. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8888. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8889. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8890. return ShadowGenerator;
  8891. })();
  8892. BABYLON.ShadowGenerator = ShadowGenerator;
  8893. })(BABYLON || (BABYLON = {}));
  8894. //# sourceMappingURL=babylon.shadowGenerator.js.map
  8895. var BABYLON;
  8896. (function (BABYLON) {
  8897. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8898. if (boxMin.x > sphereCenter.x + sphereRadius)
  8899. return false;
  8900. if (sphereCenter.x - sphereRadius > boxMax.x)
  8901. return false;
  8902. if (boxMin.y > sphereCenter.y + sphereRadius)
  8903. return false;
  8904. if (sphereCenter.y - sphereRadius > boxMax.y)
  8905. return false;
  8906. if (boxMin.z > sphereCenter.z + sphereRadius)
  8907. return false;
  8908. if (sphereCenter.z - sphereRadius > boxMax.z)
  8909. return false;
  8910. return true;
  8911. };
  8912. var getLowestRoot = function (a, b, c, maxR) {
  8913. var determinant = b * b - 4.0 * a * c;
  8914. var result = { root: 0, found: false };
  8915. if (determinant < 0)
  8916. return result;
  8917. var sqrtD = Math.sqrt(determinant);
  8918. var r1 = (-b - sqrtD) / (2.0 * a);
  8919. var r2 = (-b + sqrtD) / (2.0 * a);
  8920. if (r1 > r2) {
  8921. var temp = r2;
  8922. r2 = r1;
  8923. r1 = temp;
  8924. }
  8925. if (r1 > 0 && r1 < maxR) {
  8926. result.root = r1;
  8927. result.found = true;
  8928. return result;
  8929. }
  8930. if (r2 > 0 && r2 < maxR) {
  8931. result.root = r2;
  8932. result.found = true;
  8933. return result;
  8934. }
  8935. return result;
  8936. };
  8937. var Collider = (function () {
  8938. function Collider() {
  8939. this.radius = new BABYLON.Vector3(1, 1, 1);
  8940. this.retry = 0;
  8941. this.basePointWorld = BABYLON.Vector3.Zero();
  8942. this.velocityWorld = BABYLON.Vector3.Zero();
  8943. this.normalizedVelocity = BABYLON.Vector3.Zero();
  8944. this._collisionPoint = BABYLON.Vector3.Zero();
  8945. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  8946. this._tempVector = BABYLON.Vector3.Zero();
  8947. this._tempVector2 = BABYLON.Vector3.Zero();
  8948. this._tempVector3 = BABYLON.Vector3.Zero();
  8949. this._tempVector4 = BABYLON.Vector3.Zero();
  8950. this._edge = BABYLON.Vector3.Zero();
  8951. this._baseToVertex = BABYLON.Vector3.Zero();
  8952. this._destinationPoint = BABYLON.Vector3.Zero();
  8953. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  8954. this._displacementVector = BABYLON.Vector3.Zero();
  8955. }
  8956. // Methods
  8957. Collider.prototype._initialize = function (source, dir, e) {
  8958. this.velocity = dir;
  8959. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  8960. this.basePoint = source;
  8961. source.multiplyToRef(this.radius, this.basePointWorld);
  8962. dir.multiplyToRef(this.radius, this.velocityWorld);
  8963. this.velocityWorldLength = this.velocityWorld.length();
  8964. this.epsilon = e;
  8965. this.collisionFound = false;
  8966. };
  8967. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  8968. pa.subtractToRef(point, this._tempVector);
  8969. pb.subtractToRef(point, this._tempVector2);
  8970. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  8971. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8972. if (d < 0)
  8973. return false;
  8974. pc.subtractToRef(point, this._tempVector3);
  8975. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  8976. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8977. if (d < 0)
  8978. return false;
  8979. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  8980. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8981. return d >= 0;
  8982. };
  8983. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  8984. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  8985. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  8986. if (distance > this.velocityWorldLength + max + sphereRadius) {
  8987. return false;
  8988. }
  8989. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  8990. return false;
  8991. return true;
  8992. };
  8993. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  8994. var t0;
  8995. var embeddedInPlane = false;
  8996. //defensive programming, actually not needed.
  8997. if (!trianglePlaneArray) {
  8998. trianglePlaneArray = [];
  8999. }
  9000. if (!trianglePlaneArray[faceIndex]) {
  9001. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9002. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9003. }
  9004. var trianglePlane = trianglePlaneArray[faceIndex];
  9005. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9006. return;
  9007. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9008. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9009. if (normalDotVelocity == 0) {
  9010. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9011. return;
  9012. embeddedInPlane = true;
  9013. t0 = 0;
  9014. }
  9015. else {
  9016. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9017. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9018. if (t0 > t1) {
  9019. var temp = t1;
  9020. t1 = t0;
  9021. t0 = temp;
  9022. }
  9023. if (t0 > 1.0 || t1 < 0.0)
  9024. return;
  9025. if (t0 < 0)
  9026. t0 = 0;
  9027. if (t0 > 1.0)
  9028. t0 = 1.0;
  9029. }
  9030. this._collisionPoint.copyFromFloats(0, 0, 0);
  9031. var found = false;
  9032. var t = 1.0;
  9033. if (!embeddedInPlane) {
  9034. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9035. this.velocity.scaleToRef(t0, this._tempVector);
  9036. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9037. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9038. found = true;
  9039. t = t0;
  9040. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9041. }
  9042. }
  9043. if (!found) {
  9044. var velocitySquaredLength = this.velocity.lengthSquared();
  9045. var a = velocitySquaredLength;
  9046. this.basePoint.subtractToRef(p1, this._tempVector);
  9047. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9048. var c = this._tempVector.lengthSquared() - 1.0;
  9049. var lowestRoot = getLowestRoot(a, b, c, t);
  9050. if (lowestRoot.found) {
  9051. t = lowestRoot.root;
  9052. found = true;
  9053. this._collisionPoint.copyFrom(p1);
  9054. }
  9055. this.basePoint.subtractToRef(p2, this._tempVector);
  9056. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9057. c = this._tempVector.lengthSquared() - 1.0;
  9058. lowestRoot = getLowestRoot(a, b, c, t);
  9059. if (lowestRoot.found) {
  9060. t = lowestRoot.root;
  9061. found = true;
  9062. this._collisionPoint.copyFrom(p2);
  9063. }
  9064. this.basePoint.subtractToRef(p3, this._tempVector);
  9065. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9066. c = this._tempVector.lengthSquared() - 1.0;
  9067. lowestRoot = getLowestRoot(a, b, c, t);
  9068. if (lowestRoot.found) {
  9069. t = lowestRoot.root;
  9070. found = true;
  9071. this._collisionPoint.copyFrom(p3);
  9072. }
  9073. p2.subtractToRef(p1, this._edge);
  9074. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9075. var edgeSquaredLength = this._edge.lengthSquared();
  9076. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9077. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9078. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9079. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9080. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9081. lowestRoot = getLowestRoot(a, b, c, t);
  9082. if (lowestRoot.found) {
  9083. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9084. if (f >= 0.0 && f <= 1.0) {
  9085. t = lowestRoot.root;
  9086. found = true;
  9087. this._edge.scaleInPlace(f);
  9088. p1.addToRef(this._edge, this._collisionPoint);
  9089. }
  9090. }
  9091. p3.subtractToRef(p2, this._edge);
  9092. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9093. edgeSquaredLength = this._edge.lengthSquared();
  9094. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9095. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9096. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9097. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9098. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9099. lowestRoot = getLowestRoot(a, b, c, t);
  9100. if (lowestRoot.found) {
  9101. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9102. if (f >= 0.0 && f <= 1.0) {
  9103. t = lowestRoot.root;
  9104. found = true;
  9105. this._edge.scaleInPlace(f);
  9106. p2.addToRef(this._edge, this._collisionPoint);
  9107. }
  9108. }
  9109. p1.subtractToRef(p3, this._edge);
  9110. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9111. edgeSquaredLength = this._edge.lengthSquared();
  9112. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9113. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9114. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9115. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9116. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9117. lowestRoot = getLowestRoot(a, b, c, t);
  9118. if (lowestRoot.found) {
  9119. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9120. if (f >= 0.0 && f <= 1.0) {
  9121. t = lowestRoot.root;
  9122. found = true;
  9123. this._edge.scaleInPlace(f);
  9124. p3.addToRef(this._edge, this._collisionPoint);
  9125. }
  9126. }
  9127. }
  9128. if (found) {
  9129. var distToCollision = t * this.velocity.length();
  9130. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9131. if (!this.intersectionPoint) {
  9132. this.intersectionPoint = this._collisionPoint.clone();
  9133. }
  9134. else {
  9135. this.intersectionPoint.copyFrom(this._collisionPoint);
  9136. }
  9137. this.nearestDistance = distToCollision;
  9138. this.collisionFound = true;
  9139. }
  9140. }
  9141. };
  9142. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9143. for (var i = indexStart; i < indexEnd; i += 3) {
  9144. var p1 = pts[indices[i] - decal];
  9145. var p2 = pts[indices[i + 1] - decal];
  9146. var p3 = pts[indices[i + 2] - decal];
  9147. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9148. }
  9149. };
  9150. Collider.prototype._getResponse = function (pos, vel) {
  9151. pos.addToRef(vel, this._destinationPoint);
  9152. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9153. this.basePoint.addToRef(vel, pos);
  9154. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9155. this._slidePlaneNormal.normalize();
  9156. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9157. pos.addInPlace(this._displacementVector);
  9158. this.intersectionPoint.addInPlace(this._displacementVector);
  9159. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9160. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9161. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9162. };
  9163. return Collider;
  9164. })();
  9165. BABYLON.Collider = Collider;
  9166. })(BABYLON || (BABYLON = {}));
  9167. //# sourceMappingURL=babylon.collider.js.map
  9168. var BABYLON;
  9169. (function (BABYLON) {
  9170. //WebWorker code will be inserted to this variable.
  9171. BABYLON.CollisionWorker = "";
  9172. (function (WorkerTaskType) {
  9173. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9174. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9175. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9176. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9177. var WorkerTaskType = BABYLON.WorkerTaskType;
  9178. (function (WorkerReplyType) {
  9179. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9180. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9181. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9182. var WorkerReplyType = BABYLON.WorkerReplyType;
  9183. var CollisionCoordinatorWorker = (function () {
  9184. function CollisionCoordinatorWorker() {
  9185. var _this = this;
  9186. this._scaledPosition = BABYLON.Vector3.Zero();
  9187. this._scaledVelocity = BABYLON.Vector3.Zero();
  9188. this.onMeshUpdated = function (mesh) {
  9189. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9190. };
  9191. this.onGeometryUpdated = function (geometry) {
  9192. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9193. };
  9194. this._afterRender = function () {
  9195. if (!_this._init)
  9196. return;
  9197. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9198. return;
  9199. }
  9200. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9201. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9202. if (_this._runningUpdated > 4) {
  9203. return;
  9204. }
  9205. ++_this._runningUpdated;
  9206. var payload = {
  9207. updatedMeshes: _this._addUpdateMeshesList,
  9208. updatedGeometries: _this._addUpdateGeometriesList,
  9209. removedGeometries: _this._toRemoveGeometryArray,
  9210. removedMeshes: _this._toRemoveMeshesArray
  9211. };
  9212. var message = {
  9213. payload: payload,
  9214. taskType: WorkerTaskType.UPDATE
  9215. };
  9216. var serializable = [];
  9217. for (var id in payload.updatedGeometries) {
  9218. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9219. //prepare transferables
  9220. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9221. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9222. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9223. }
  9224. }
  9225. _this._worker.postMessage(message, serializable);
  9226. _this._addUpdateMeshesList = {};
  9227. _this._addUpdateGeometriesList = {};
  9228. _this._toRemoveGeometryArray = [];
  9229. _this._toRemoveMeshesArray = [];
  9230. };
  9231. this._onMessageFromWorker = function (e) {
  9232. var returnData = e.data;
  9233. if (returnData.error != WorkerReplyType.SUCCESS) {
  9234. //TODO what errors can be returned from the worker?
  9235. BABYLON.Tools.Warn("error returned from worker!");
  9236. return;
  9237. }
  9238. switch (returnData.taskType) {
  9239. case WorkerTaskType.INIT:
  9240. _this._init = true;
  9241. //Update the worked with ALL of the scene's current state
  9242. _this._scene.meshes.forEach(function (mesh) {
  9243. _this.onMeshAdded(mesh);
  9244. });
  9245. _this._scene.getGeometries().forEach(function (geometry) {
  9246. _this.onGeometryAdded(geometry);
  9247. });
  9248. break;
  9249. case WorkerTaskType.UPDATE:
  9250. _this._runningUpdated--;
  9251. break;
  9252. case WorkerTaskType.COLLIDE:
  9253. _this._runningCollisionTask = false;
  9254. var returnPayload = returnData.payload;
  9255. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9256. return;
  9257. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9258. //cleanup
  9259. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9260. break;
  9261. }
  9262. };
  9263. this._collisionsCallbackArray = [];
  9264. this._init = false;
  9265. this._runningUpdated = 0;
  9266. this._runningCollisionTask = false;
  9267. this._addUpdateMeshesList = {};
  9268. this._addUpdateGeometriesList = {};
  9269. this._toRemoveGeometryArray = [];
  9270. this._toRemoveMeshesArray = [];
  9271. }
  9272. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9273. if (!this._init)
  9274. return;
  9275. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9276. return;
  9277. position.divideToRef(collider.radius, this._scaledPosition);
  9278. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9279. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9280. var payload = {
  9281. collider: {
  9282. position: this._scaledPosition.asArray(),
  9283. velocity: this._scaledVelocity.asArray(),
  9284. radius: collider.radius.asArray()
  9285. },
  9286. collisionId: collisionIndex,
  9287. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9288. maximumRetry: maximumRetry
  9289. };
  9290. var message = {
  9291. payload: payload,
  9292. taskType: WorkerTaskType.COLLIDE
  9293. };
  9294. this._worker.postMessage(message);
  9295. };
  9296. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9297. this._scene = scene;
  9298. this._scene.registerAfterRender(this._afterRender);
  9299. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9300. this._worker = new Worker(workerUrl);
  9301. this._worker.onmessage = this._onMessageFromWorker;
  9302. var message = {
  9303. payload: {},
  9304. taskType: WorkerTaskType.INIT
  9305. };
  9306. this._worker.postMessage(message);
  9307. };
  9308. CollisionCoordinatorWorker.prototype.destroy = function () {
  9309. this._scene.unregisterAfterRender(this._afterRender);
  9310. this._worker.terminate();
  9311. };
  9312. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9313. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9314. this.onMeshUpdated(mesh);
  9315. };
  9316. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9317. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9318. };
  9319. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9320. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9321. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9322. this.onGeometryUpdated(geometry);
  9323. };
  9324. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9325. this._toRemoveGeometryArray.push(geometry.id);
  9326. };
  9327. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9328. var submeshes = [];
  9329. if (mesh.subMeshes) {
  9330. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9331. return {
  9332. position: idx,
  9333. verticesStart: sm.verticesStart,
  9334. verticesCount: sm.verticesCount,
  9335. indexStart: sm.indexStart,
  9336. indexCount: sm.indexCount,
  9337. hasMaterial: !!sm.getMaterial(),
  9338. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9339. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9340. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9341. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9342. };
  9343. });
  9344. }
  9345. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9346. return {
  9347. uniqueId: mesh.uniqueId,
  9348. id: mesh.id,
  9349. name: mesh.name,
  9350. geometryId: geometryId,
  9351. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9352. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9353. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9354. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9355. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9356. subMeshes: submeshes,
  9357. checkCollisions: mesh.checkCollisions
  9358. };
  9359. };
  9360. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9361. return {
  9362. id: geometry.id,
  9363. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9364. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9365. indices: new Int32Array(geometry.getIndices() || []),
  9366. };
  9367. };
  9368. return CollisionCoordinatorWorker;
  9369. })();
  9370. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9371. var CollisionCoordinatorLegacy = (function () {
  9372. function CollisionCoordinatorLegacy() {
  9373. this._scaledPosition = BABYLON.Vector3.Zero();
  9374. this._scaledVelocity = BABYLON.Vector3.Zero();
  9375. this._finalPosition = BABYLON.Vector3.Zero();
  9376. }
  9377. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9378. position.divideToRef(collider.radius, this._scaledPosition);
  9379. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9380. collider.retry = 0;
  9381. collider.initialVelocity = this._scaledVelocity;
  9382. collider.initialPosition = this._scaledPosition;
  9383. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9384. this._finalPosition.multiplyInPlace(collider.radius);
  9385. //run the callback
  9386. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9387. };
  9388. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9389. this._scene = scene;
  9390. };
  9391. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9392. //Legacy need no destruction method.
  9393. };
  9394. //No update in legacy mode
  9395. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9396. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9397. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9398. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9399. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9400. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9401. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9402. if (excludedMesh === void 0) { excludedMesh = null; }
  9403. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9404. if (collider.retry >= maximumRetry) {
  9405. finalPosition.copyFrom(position);
  9406. return;
  9407. }
  9408. collider._initialize(position, velocity, closeDistance);
  9409. // Check all meshes
  9410. for (var index = 0; index < this._scene.meshes.length; index++) {
  9411. var mesh = this._scene.meshes[index];
  9412. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9413. mesh._checkCollision(collider);
  9414. }
  9415. }
  9416. if (!collider.collisionFound) {
  9417. position.addToRef(velocity, finalPosition);
  9418. return;
  9419. }
  9420. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9421. collider._getResponse(position, velocity);
  9422. }
  9423. if (velocity.length() <= closeDistance) {
  9424. finalPosition.copyFrom(position);
  9425. return;
  9426. }
  9427. collider.retry++;
  9428. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9429. };
  9430. return CollisionCoordinatorLegacy;
  9431. })();
  9432. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9433. })(BABYLON || (BABYLON = {}));
  9434. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9435. var __extends = this.__extends || function (d, b) {
  9436. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9437. function __() { this.constructor = d; }
  9438. __.prototype = b.prototype;
  9439. d.prototype = new __();
  9440. };
  9441. var BABYLON;
  9442. (function (BABYLON) {
  9443. var Camera = (function (_super) {
  9444. __extends(Camera, _super);
  9445. function Camera(name, position, scene) {
  9446. _super.call(this, name, scene);
  9447. this.position = position;
  9448. // Members
  9449. this.upVector = BABYLON.Vector3.Up();
  9450. this.orthoLeft = null;
  9451. this.orthoRight = null;
  9452. this.orthoBottom = null;
  9453. this.orthoTop = null;
  9454. this.fov = 0.8;
  9455. this.minZ = 1.0;
  9456. this.maxZ = 10000.0;
  9457. this.inertia = 0.9;
  9458. this.mode = Camera.PERSPECTIVE_CAMERA;
  9459. this.isIntermediate = false;
  9460. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9461. this.subCameras = [];
  9462. this.layerMask = 0xFFFFFFFF;
  9463. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9464. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9465. this._projectionMatrix = new BABYLON.Matrix();
  9466. this._postProcesses = new Array();
  9467. this._postProcessesTakenIndices = [];
  9468. this._activeMeshes = new BABYLON.SmartArray(256);
  9469. this._globalPosition = BABYLON.Vector3.Zero();
  9470. scene.addCamera(this);
  9471. if (!scene.activeCamera) {
  9472. scene.activeCamera = this;
  9473. }
  9474. }
  9475. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9476. get: function () {
  9477. return Camera._PERSPECTIVE_CAMERA;
  9478. },
  9479. enumerable: true,
  9480. configurable: true
  9481. });
  9482. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9483. get: function () {
  9484. return Camera._ORTHOGRAPHIC_CAMERA;
  9485. },
  9486. enumerable: true,
  9487. configurable: true
  9488. });
  9489. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9490. get: function () {
  9491. return Camera._FOVMODE_VERTICAL_FIXED;
  9492. },
  9493. enumerable: true,
  9494. configurable: true
  9495. });
  9496. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9497. get: function () {
  9498. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9499. },
  9500. enumerable: true,
  9501. configurable: true
  9502. });
  9503. Object.defineProperty(Camera.prototype, "globalPosition", {
  9504. get: function () {
  9505. return this._globalPosition;
  9506. },
  9507. enumerable: true,
  9508. configurable: true
  9509. });
  9510. Camera.prototype.getActiveMeshes = function () {
  9511. return this._activeMeshes;
  9512. };
  9513. Camera.prototype.isActiveMesh = function (mesh) {
  9514. return (this._activeMeshes.indexOf(mesh) !== -1);
  9515. };
  9516. //Cache
  9517. Camera.prototype._initCache = function () {
  9518. _super.prototype._initCache.call(this);
  9519. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9520. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9521. this._cache.mode = undefined;
  9522. this._cache.minZ = undefined;
  9523. this._cache.maxZ = undefined;
  9524. this._cache.fov = undefined;
  9525. this._cache.aspectRatio = undefined;
  9526. this._cache.orthoLeft = undefined;
  9527. this._cache.orthoRight = undefined;
  9528. this._cache.orthoBottom = undefined;
  9529. this._cache.orthoTop = undefined;
  9530. this._cache.renderWidth = undefined;
  9531. this._cache.renderHeight = undefined;
  9532. };
  9533. Camera.prototype._updateCache = function (ignoreParentClass) {
  9534. if (!ignoreParentClass) {
  9535. _super.prototype._updateCache.call(this);
  9536. }
  9537. var engine = this.getEngine();
  9538. this._cache.position.copyFrom(this.position);
  9539. this._cache.upVector.copyFrom(this.upVector);
  9540. this._cache.mode = this.mode;
  9541. this._cache.minZ = this.minZ;
  9542. this._cache.maxZ = this.maxZ;
  9543. this._cache.fov = this.fov;
  9544. this._cache.aspectRatio = engine.getAspectRatio(this);
  9545. this._cache.orthoLeft = this.orthoLeft;
  9546. this._cache.orthoRight = this.orthoRight;
  9547. this._cache.orthoBottom = this.orthoBottom;
  9548. this._cache.orthoTop = this.orthoTop;
  9549. this._cache.renderWidth = engine.getRenderWidth();
  9550. this._cache.renderHeight = engine.getRenderHeight();
  9551. };
  9552. Camera.prototype._updateFromScene = function () {
  9553. this.updateCache();
  9554. this._update();
  9555. };
  9556. // Synchronized
  9557. Camera.prototype._isSynchronized = function () {
  9558. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9559. };
  9560. Camera.prototype._isSynchronizedViewMatrix = function () {
  9561. if (!_super.prototype._isSynchronized.call(this))
  9562. return false;
  9563. return this._cache.position.equals(this.position)
  9564. && this._cache.upVector.equals(this.upVector)
  9565. && this.isSynchronizedWithParent();
  9566. };
  9567. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9568. var check = this._cache.mode === this.mode
  9569. && this._cache.minZ === this.minZ
  9570. && this._cache.maxZ === this.maxZ;
  9571. if (!check) {
  9572. return false;
  9573. }
  9574. var engine = this.getEngine();
  9575. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9576. check = this._cache.fov === this.fov
  9577. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9578. }
  9579. else {
  9580. check = this._cache.orthoLeft === this.orthoLeft
  9581. && this._cache.orthoRight === this.orthoRight
  9582. && this._cache.orthoBottom === this.orthoBottom
  9583. && this._cache.orthoTop === this.orthoTop
  9584. && this._cache.renderWidth === engine.getRenderWidth()
  9585. && this._cache.renderHeight === engine.getRenderHeight();
  9586. }
  9587. return check;
  9588. };
  9589. // Controls
  9590. Camera.prototype.attachControl = function (element) {
  9591. };
  9592. Camera.prototype.detachControl = function (element) {
  9593. };
  9594. Camera.prototype._update = function () {
  9595. };
  9596. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9597. if (insertAt === void 0) { insertAt = null; }
  9598. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9599. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9600. return 0;
  9601. }
  9602. if (insertAt == null || insertAt < 0) {
  9603. this._postProcesses.push(postProcess);
  9604. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9605. return this._postProcesses.length - 1;
  9606. }
  9607. var add = 0;
  9608. if (this._postProcesses[insertAt]) {
  9609. var start = this._postProcesses.length - 1;
  9610. for (var i = start; i >= insertAt + 1; --i) {
  9611. this._postProcesses[i + 1] = this._postProcesses[i];
  9612. }
  9613. add = 1;
  9614. }
  9615. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9616. if (this._postProcessesTakenIndices[i] < insertAt) {
  9617. continue;
  9618. }
  9619. start = this._postProcessesTakenIndices.length - 1;
  9620. for (var j = start; j >= i; --j) {
  9621. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9622. }
  9623. this._postProcessesTakenIndices[i] = insertAt;
  9624. break;
  9625. }
  9626. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9627. this._postProcessesTakenIndices.push(insertAt);
  9628. }
  9629. var result = insertAt + add;
  9630. this._postProcesses[result] = postProcess;
  9631. return result;
  9632. };
  9633. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9634. if (atIndices === void 0) { atIndices = null; }
  9635. var result = [];
  9636. if (!atIndices) {
  9637. var length = this._postProcesses.length;
  9638. for (var i = 0; i < length; i++) {
  9639. if (this._postProcesses[i] !== postProcess) {
  9640. continue;
  9641. }
  9642. delete this._postProcesses[i];
  9643. var index = this._postProcessesTakenIndices.indexOf(i);
  9644. this._postProcessesTakenIndices.splice(index, 1);
  9645. }
  9646. }
  9647. else {
  9648. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9649. for (i = 0; i < atIndices.length; i++) {
  9650. var foundPostProcess = this._postProcesses[atIndices[i]];
  9651. if (foundPostProcess !== postProcess) {
  9652. result.push(i);
  9653. continue;
  9654. }
  9655. delete this._postProcesses[atIndices[i]];
  9656. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9657. this._postProcessesTakenIndices.splice(index, 1);
  9658. }
  9659. }
  9660. return result;
  9661. };
  9662. Camera.prototype.getWorldMatrix = function () {
  9663. if (!this._worldMatrix) {
  9664. this._worldMatrix = BABYLON.Matrix.Identity();
  9665. }
  9666. var viewMatrix = this.getViewMatrix();
  9667. viewMatrix.invertToRef(this._worldMatrix);
  9668. return this._worldMatrix;
  9669. };
  9670. Camera.prototype._getViewMatrix = function () {
  9671. return BABYLON.Matrix.Identity();
  9672. };
  9673. Camera.prototype.getViewMatrix = function (force) {
  9674. this._computedViewMatrix = this._computeViewMatrix(force);
  9675. if (!force && this._isSynchronizedViewMatrix()) {
  9676. return this._computedViewMatrix;
  9677. }
  9678. if (!this.parent || !this.parent.getWorldMatrix) {
  9679. this._globalPosition.copyFrom(this.position);
  9680. }
  9681. else {
  9682. if (!this._worldMatrix) {
  9683. this._worldMatrix = BABYLON.Matrix.Identity();
  9684. }
  9685. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9686. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9687. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9688. this._computedViewMatrix.invert();
  9689. this._markSyncedWithParent();
  9690. }
  9691. this._currentRenderId = this.getScene().getRenderId();
  9692. return this._computedViewMatrix;
  9693. };
  9694. Camera.prototype._computeViewMatrix = function (force) {
  9695. if (!force && this._isSynchronizedViewMatrix()) {
  9696. return this._computedViewMatrix;
  9697. }
  9698. this._computedViewMatrix = this._getViewMatrix();
  9699. this._currentRenderId = this.getScene().getRenderId();
  9700. return this._computedViewMatrix;
  9701. };
  9702. Camera.prototype.getProjectionMatrix = function (force) {
  9703. if (!force && this._isSynchronizedProjectionMatrix()) {
  9704. return this._projectionMatrix;
  9705. }
  9706. var engine = this.getEngine();
  9707. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9708. if (this.minZ <= 0) {
  9709. this.minZ = 0.1;
  9710. }
  9711. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9712. return this._projectionMatrix;
  9713. }
  9714. var halfWidth = engine.getRenderWidth() / 2.0;
  9715. var halfHeight = engine.getRenderHeight() / 2.0;
  9716. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9717. return this._projectionMatrix;
  9718. };
  9719. Camera.prototype.dispose = function () {
  9720. // Remove from scene
  9721. this.getScene().removeCamera(this);
  9722. // Postprocesses
  9723. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9724. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9725. }
  9726. };
  9727. // Statics
  9728. Camera._PERSPECTIVE_CAMERA = 0;
  9729. Camera._ORTHOGRAPHIC_CAMERA = 1;
  9730. Camera._FOVMODE_VERTICAL_FIXED = 0;
  9731. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  9732. return Camera;
  9733. })(BABYLON.Node);
  9734. BABYLON.Camera = Camera;
  9735. })(BABYLON || (BABYLON = {}));
  9736. //# sourceMappingURL=babylon.camera.js.map
  9737. var __extends = this.__extends || function (d, b) {
  9738. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9739. function __() { this.constructor = d; }
  9740. __.prototype = b.prototype;
  9741. d.prototype = new __();
  9742. };
  9743. var BABYLON;
  9744. (function (BABYLON) {
  9745. var TargetCamera = (function (_super) {
  9746. __extends(TargetCamera, _super);
  9747. function TargetCamera(name, position, scene) {
  9748. _super.call(this, name, position, scene);
  9749. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  9750. this.cameraRotation = new BABYLON.Vector2(0, 0);
  9751. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9752. this.speed = 2.0;
  9753. this.noRotationConstraint = false;
  9754. this.lockedTarget = null;
  9755. this._currentTarget = BABYLON.Vector3.Zero();
  9756. this._viewMatrix = BABYLON.Matrix.Zero();
  9757. this._camMatrix = BABYLON.Matrix.Zero();
  9758. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  9759. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  9760. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  9761. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  9762. this._lookAtTemp = BABYLON.Matrix.Zero();
  9763. this._tempMatrix = BABYLON.Matrix.Zero();
  9764. }
  9765. TargetCamera.prototype._getLockedTargetPosition = function () {
  9766. if (!this.lockedTarget) {
  9767. return null;
  9768. }
  9769. return this.lockedTarget.position || this.lockedTarget;
  9770. };
  9771. // Cache
  9772. TargetCamera.prototype._initCache = function () {
  9773. _super.prototype._initCache.call(this);
  9774. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9775. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9776. };
  9777. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  9778. if (!ignoreParentClass) {
  9779. _super.prototype._updateCache.call(this);
  9780. }
  9781. var lockedTargetPosition = this._getLockedTargetPosition();
  9782. if (!lockedTargetPosition) {
  9783. this._cache.lockedTarget = null;
  9784. }
  9785. else {
  9786. if (!this._cache.lockedTarget) {
  9787. this._cache.lockedTarget = lockedTargetPosition.clone();
  9788. }
  9789. else {
  9790. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  9791. }
  9792. }
  9793. this._cache.rotation.copyFrom(this.rotation);
  9794. };
  9795. // Synchronized
  9796. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  9797. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  9798. return false;
  9799. }
  9800. var lockedTargetPosition = this._getLockedTargetPosition();
  9801. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  9802. && this._cache.rotation.equals(this.rotation);
  9803. };
  9804. // Methods
  9805. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  9806. var engine = this.getEngine();
  9807. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  9808. };
  9809. // Target
  9810. TargetCamera.prototype.setTarget = function (target) {
  9811. this.upVector.normalize();
  9812. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  9813. this._camMatrix.invert();
  9814. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  9815. var vDir = target.subtract(this.position);
  9816. if (vDir.x >= 0.0) {
  9817. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  9818. }
  9819. else {
  9820. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  9821. }
  9822. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  9823. if (isNaN(this.rotation.x)) {
  9824. this.rotation.x = 0;
  9825. }
  9826. if (isNaN(this.rotation.y)) {
  9827. this.rotation.y = 0;
  9828. }
  9829. if (isNaN(this.rotation.z)) {
  9830. this.rotation.z = 0;
  9831. }
  9832. };
  9833. TargetCamera.prototype.getTarget = function () {
  9834. return this._currentTarget;
  9835. };
  9836. TargetCamera.prototype._decideIfNeedsToMove = function () {
  9837. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  9838. };
  9839. TargetCamera.prototype._updatePosition = function () {
  9840. this.position.addInPlace(this.cameraDirection);
  9841. };
  9842. TargetCamera.prototype._update = function () {
  9843. var needToMove = this._decideIfNeedsToMove();
  9844. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  9845. // Move
  9846. if (needToMove) {
  9847. this._updatePosition();
  9848. }
  9849. // Rotate
  9850. if (needToRotate) {
  9851. this.rotation.x += this.cameraRotation.x;
  9852. this.rotation.y += this.cameraRotation.y;
  9853. if (!this.noRotationConstraint) {
  9854. var limit = (Math.PI / 2) * 0.95;
  9855. if (this.rotation.x > limit)
  9856. this.rotation.x = limit;
  9857. if (this.rotation.x < -limit)
  9858. this.rotation.x = -limit;
  9859. }
  9860. }
  9861. // Inertia
  9862. if (needToMove) {
  9863. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  9864. this.cameraDirection.x = 0;
  9865. }
  9866. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  9867. this.cameraDirection.y = 0;
  9868. }
  9869. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  9870. this.cameraDirection.z = 0;
  9871. }
  9872. this.cameraDirection.scaleInPlace(this.inertia);
  9873. }
  9874. if (needToRotate) {
  9875. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  9876. this.cameraRotation.x = 0;
  9877. }
  9878. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  9879. this.cameraRotation.y = 0;
  9880. }
  9881. this.cameraRotation.scaleInPlace(this.inertia);
  9882. }
  9883. };
  9884. TargetCamera.prototype._getViewMatrix = function () {
  9885. if (!this.lockedTarget) {
  9886. // Compute
  9887. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  9888. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  9889. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9890. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  9891. this._lookAtTemp.invert();
  9892. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  9893. }
  9894. else {
  9895. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9896. }
  9897. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  9898. // Computing target and final matrix
  9899. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  9900. }
  9901. else {
  9902. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  9903. }
  9904. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  9905. return this._viewMatrix;
  9906. };
  9907. return TargetCamera;
  9908. })(BABYLON.Camera);
  9909. BABYLON.TargetCamera = TargetCamera;
  9910. })(BABYLON || (BABYLON = {}));
  9911. //# sourceMappingURL=babylon.targetCamera.js.map
  9912. var __extends = this.__extends || function (d, b) {
  9913. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9914. function __() { this.constructor = d; }
  9915. __.prototype = b.prototype;
  9916. d.prototype = new __();
  9917. };
  9918. var BABYLON;
  9919. (function (BABYLON) {
  9920. var FreeCamera = (function (_super) {
  9921. __extends(FreeCamera, _super);
  9922. function FreeCamera(name, position, scene) {
  9923. var _this = this;
  9924. _super.call(this, name, position, scene);
  9925. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9926. this.keysUp = [38];
  9927. this.keysDown = [40];
  9928. this.keysLeft = [37];
  9929. this.keysRight = [39];
  9930. this.checkCollisions = false;
  9931. this.applyGravity = false;
  9932. this.angularSensibility = 2000.0;
  9933. this._keys = [];
  9934. this._collider = new BABYLON.Collider();
  9935. this._needMoveForGravity = false;
  9936. this._oldPosition = BABYLON.Vector3.Zero();
  9937. this._diffPosition = BABYLON.Vector3.Zero();
  9938. this._newPosition = BABYLON.Vector3.Zero();
  9939. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9940. if (collidedMesh === void 0) { collidedMesh = null; }
  9941. //TODO move this to the collision coordinator!
  9942. if (_this.getScene().workerCollisions)
  9943. newPosition.multiplyInPlace(_this._collider.radius);
  9944. var updatePosition = function (newPos) {
  9945. _this._newPosition.copyFrom(newPos);
  9946. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  9947. var oldPosition = _this.position.clone();
  9948. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  9949. _this.position.addInPlace(_this._diffPosition);
  9950. if (_this.onCollide && collidedMesh) {
  9951. _this.onCollide(collidedMesh);
  9952. }
  9953. }
  9954. };
  9955. updatePosition(newPosition);
  9956. };
  9957. }
  9958. // Controls
  9959. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  9960. var _this = this;
  9961. var previousPosition;
  9962. var engine = this.getEngine();
  9963. if (this._attachedElement) {
  9964. return;
  9965. }
  9966. this._attachedElement = element;
  9967. if (this._onMouseDown === undefined) {
  9968. this._onMouseDown = function (evt) {
  9969. previousPosition = {
  9970. x: evt.clientX,
  9971. y: evt.clientY
  9972. };
  9973. if (!noPreventDefault) {
  9974. evt.preventDefault();
  9975. }
  9976. };
  9977. this._onMouseUp = function (evt) {
  9978. previousPosition = null;
  9979. if (!noPreventDefault) {
  9980. evt.preventDefault();
  9981. }
  9982. };
  9983. this._onMouseOut = function (evt) {
  9984. previousPosition = null;
  9985. _this._keys = [];
  9986. if (!noPreventDefault) {
  9987. evt.preventDefault();
  9988. }
  9989. };
  9990. this._onMouseMove = function (evt) {
  9991. if (!previousPosition && !engine.isPointerLock) {
  9992. return;
  9993. }
  9994. var offsetX;
  9995. var offsetY;
  9996. if (!engine.isPointerLock) {
  9997. offsetX = evt.clientX - previousPosition.x;
  9998. offsetY = evt.clientY - previousPosition.y;
  9999. }
  10000. else {
  10001. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10002. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10003. }
  10004. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10005. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10006. previousPosition = {
  10007. x: evt.clientX,
  10008. y: evt.clientY
  10009. };
  10010. if (!noPreventDefault) {
  10011. evt.preventDefault();
  10012. }
  10013. };
  10014. this._onKeyDown = function (evt) {
  10015. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10016. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10017. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10018. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10019. var index = _this._keys.indexOf(evt.keyCode);
  10020. if (index === -1) {
  10021. _this._keys.push(evt.keyCode);
  10022. }
  10023. if (!noPreventDefault) {
  10024. evt.preventDefault();
  10025. }
  10026. }
  10027. };
  10028. this._onKeyUp = function (evt) {
  10029. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10030. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10031. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10032. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10033. var index = _this._keys.indexOf(evt.keyCode);
  10034. if (index >= 0) {
  10035. _this._keys.splice(index, 1);
  10036. }
  10037. if (!noPreventDefault) {
  10038. evt.preventDefault();
  10039. }
  10040. }
  10041. };
  10042. this._onLostFocus = function () {
  10043. _this._keys = [];
  10044. };
  10045. this._reset = function () {
  10046. _this._keys = [];
  10047. previousPosition = null;
  10048. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10049. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10050. };
  10051. }
  10052. element.addEventListener("mousedown", this._onMouseDown, false);
  10053. element.addEventListener("mouseup", this._onMouseUp, false);
  10054. element.addEventListener("mouseout", this._onMouseOut, false);
  10055. element.addEventListener("mousemove", this._onMouseMove, false);
  10056. BABYLON.Tools.RegisterTopRootEvents([
  10057. { name: "keydown", handler: this._onKeyDown },
  10058. { name: "keyup", handler: this._onKeyUp },
  10059. { name: "blur", handler: this._onLostFocus }
  10060. ]);
  10061. };
  10062. FreeCamera.prototype.detachControl = function (element) {
  10063. if (this._attachedElement != element) {
  10064. return;
  10065. }
  10066. element.removeEventListener("mousedown", this._onMouseDown);
  10067. element.removeEventListener("mouseup", this._onMouseUp);
  10068. element.removeEventListener("mouseout", this._onMouseOut);
  10069. element.removeEventListener("mousemove", this._onMouseMove);
  10070. BABYLON.Tools.UnregisterTopRootEvents([
  10071. { name: "keydown", handler: this._onKeyDown },
  10072. { name: "keyup", handler: this._onKeyUp },
  10073. { name: "blur", handler: this._onLostFocus }
  10074. ]);
  10075. this._attachedElement = null;
  10076. if (this._reset) {
  10077. this._reset();
  10078. }
  10079. };
  10080. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10081. var globalPosition;
  10082. if (this.parent) {
  10083. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10084. }
  10085. else {
  10086. globalPosition = this.position;
  10087. }
  10088. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10089. this._collider.radius = this.ellipsoid;
  10090. //add gravity to the velocity to prevent the dual-collision checking
  10091. if (this.applyGravity) {
  10092. velocity.addInPlace(this.getScene().gravity);
  10093. }
  10094. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10095. };
  10096. FreeCamera.prototype._checkInputs = function () {
  10097. if (!this._localDirection) {
  10098. this._localDirection = BABYLON.Vector3.Zero();
  10099. this._transformedDirection = BABYLON.Vector3.Zero();
  10100. }
  10101. // Keyboard
  10102. for (var index = 0; index < this._keys.length; index++) {
  10103. var keyCode = this._keys[index];
  10104. var speed = this._computeLocalCameraSpeed();
  10105. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10106. this._localDirection.copyFromFloats(-speed, 0, 0);
  10107. }
  10108. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10109. this._localDirection.copyFromFloats(0, 0, speed);
  10110. }
  10111. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10112. this._localDirection.copyFromFloats(speed, 0, 0);
  10113. }
  10114. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10115. this._localDirection.copyFromFloats(0, 0, -speed);
  10116. }
  10117. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10118. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10119. this.cameraDirection.addInPlace(this._transformedDirection);
  10120. }
  10121. };
  10122. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10123. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10124. };
  10125. FreeCamera.prototype._updatePosition = function () {
  10126. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10127. this._collideWithWorld(this.cameraDirection);
  10128. }
  10129. else {
  10130. this.position.addInPlace(this.cameraDirection);
  10131. }
  10132. };
  10133. FreeCamera.prototype._update = function () {
  10134. this._checkInputs();
  10135. _super.prototype._update.call(this);
  10136. };
  10137. return FreeCamera;
  10138. })(BABYLON.TargetCamera);
  10139. BABYLON.FreeCamera = FreeCamera;
  10140. })(BABYLON || (BABYLON = {}));
  10141. //# sourceMappingURL=babylon.freeCamera.js.map
  10142. var __extends = this.__extends || function (d, b) {
  10143. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10144. function __() { this.constructor = d; }
  10145. __.prototype = b.prototype;
  10146. d.prototype = new __();
  10147. };
  10148. var BABYLON;
  10149. (function (BABYLON) {
  10150. var FollowCamera = (function (_super) {
  10151. __extends(FollowCamera, _super);
  10152. function FollowCamera(name, position, scene) {
  10153. _super.call(this, name, position, scene);
  10154. this.radius = 12;
  10155. this.rotationOffset = 0;
  10156. this.heightOffset = 4;
  10157. this.cameraAcceleration = 0.05;
  10158. this.maxCameraSpeed = 20;
  10159. }
  10160. FollowCamera.prototype.getRadians = function (degrees) {
  10161. return degrees * Math.PI / 180;
  10162. };
  10163. FollowCamera.prototype.follow = function (cameraTarget) {
  10164. if (!cameraTarget)
  10165. return;
  10166. var yRotation;
  10167. if (cameraTarget.rotationQuaternion) {
  10168. var rotMatrix = new BABYLON.Matrix();
  10169. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10170. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10171. }
  10172. else {
  10173. yRotation = cameraTarget.rotation.y;
  10174. }
  10175. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10176. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10177. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10178. var dx = targetX - this.position.x;
  10179. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10180. var dz = (targetZ) - this.position.z;
  10181. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10182. var vy = dy * this.cameraAcceleration;
  10183. var vz = dz * this.cameraAcceleration * 2;
  10184. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10185. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10186. }
  10187. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10188. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10189. }
  10190. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10191. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10192. }
  10193. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10194. this.setTarget(cameraTarget.position);
  10195. };
  10196. FollowCamera.prototype._update = function () {
  10197. _super.prototype._update.call(this);
  10198. this.follow(this.target);
  10199. };
  10200. return FollowCamera;
  10201. })(BABYLON.TargetCamera);
  10202. BABYLON.FollowCamera = FollowCamera;
  10203. })(BABYLON || (BABYLON = {}));
  10204. //# sourceMappingURL=babylon.followCamera.js.map
  10205. var __extends = this.__extends || function (d, b) {
  10206. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10207. function __() { this.constructor = d; }
  10208. __.prototype = b.prototype;
  10209. d.prototype = new __();
  10210. };
  10211. var BABYLON;
  10212. (function (BABYLON) {
  10213. // We're mainly based on the logic defined into the FreeCamera code
  10214. var TouchCamera = (function (_super) {
  10215. __extends(TouchCamera, _super);
  10216. function TouchCamera(name, position, scene) {
  10217. _super.call(this, name, position, scene);
  10218. this._offsetX = null;
  10219. this._offsetY = null;
  10220. this._pointerCount = 0;
  10221. this._pointerPressed = [];
  10222. this.angularSensibility = 200000.0;
  10223. this.moveSensibility = 500.0;
  10224. }
  10225. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10226. var _this = this;
  10227. var previousPosition;
  10228. if (this._attachedCanvas) {
  10229. return;
  10230. }
  10231. this._attachedCanvas = canvas;
  10232. if (this._onPointerDown === undefined) {
  10233. this._onPointerDown = function (evt) {
  10234. if (!noPreventDefault) {
  10235. evt.preventDefault();
  10236. }
  10237. _this._pointerPressed.push(evt.pointerId);
  10238. if (_this._pointerPressed.length !== 1) {
  10239. return;
  10240. }
  10241. previousPosition = {
  10242. x: evt.clientX,
  10243. y: evt.clientY
  10244. };
  10245. };
  10246. this._onPointerUp = function (evt) {
  10247. if (!noPreventDefault) {
  10248. evt.preventDefault();
  10249. }
  10250. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10251. if (index === -1) {
  10252. return;
  10253. }
  10254. _this._pointerPressed.splice(index, 1);
  10255. if (index != 0) {
  10256. return;
  10257. }
  10258. previousPosition = null;
  10259. _this._offsetX = null;
  10260. _this._offsetY = null;
  10261. };
  10262. this._onPointerMove = function (evt) {
  10263. if (!noPreventDefault) {
  10264. evt.preventDefault();
  10265. }
  10266. if (!previousPosition) {
  10267. return;
  10268. }
  10269. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10270. if (index != 0) {
  10271. return;
  10272. }
  10273. _this._offsetX = evt.clientX - previousPosition.x;
  10274. _this._offsetY = -(evt.clientY - previousPosition.y);
  10275. };
  10276. this._onLostFocus = function () {
  10277. _this._offsetX = null;
  10278. _this._offsetY = null;
  10279. };
  10280. }
  10281. canvas.addEventListener("pointerdown", this._onPointerDown);
  10282. canvas.addEventListener("pointerup", this._onPointerUp);
  10283. canvas.addEventListener("pointerout", this._onPointerUp);
  10284. canvas.addEventListener("pointermove", this._onPointerMove);
  10285. BABYLON.Tools.RegisterTopRootEvents([
  10286. { name: "blur", handler: this._onLostFocus }
  10287. ]);
  10288. };
  10289. TouchCamera.prototype.detachControl = function (canvas) {
  10290. if (this._attachedCanvas != canvas) {
  10291. return;
  10292. }
  10293. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10294. canvas.removeEventListener("pointerup", this._onPointerUp);
  10295. canvas.removeEventListener("pointerout", this._onPointerUp);
  10296. canvas.removeEventListener("pointermove", this._onPointerMove);
  10297. BABYLON.Tools.UnregisterTopRootEvents([
  10298. { name: "blur", handler: this._onLostFocus }
  10299. ]);
  10300. this._attachedCanvas = null;
  10301. };
  10302. TouchCamera.prototype._checkInputs = function () {
  10303. if (!this._offsetX) {
  10304. return;
  10305. }
  10306. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10307. if (this._pointerPressed.length > 1) {
  10308. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10309. }
  10310. else {
  10311. var speed = this._computeLocalCameraSpeed();
  10312. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10313. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10314. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10315. }
  10316. };
  10317. return TouchCamera;
  10318. })(BABYLON.FreeCamera);
  10319. BABYLON.TouchCamera = TouchCamera;
  10320. })(BABYLON || (BABYLON = {}));
  10321. //# sourceMappingURL=babylon.touchCamera.js.map
  10322. var __extends = this.__extends || function (d, b) {
  10323. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10324. function __() { this.constructor = d; }
  10325. __.prototype = b.prototype;
  10326. d.prototype = new __();
  10327. };
  10328. var BABYLON;
  10329. (function (BABYLON) {
  10330. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10331. var ArcRotateCamera = (function (_super) {
  10332. __extends(ArcRotateCamera, _super);
  10333. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10334. var _this = this;
  10335. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10336. this.alpha = alpha;
  10337. this.beta = beta;
  10338. this.radius = radius;
  10339. this.target = target;
  10340. this.inertialAlphaOffset = 0;
  10341. this.inertialBetaOffset = 0;
  10342. this.inertialRadiusOffset = 0;
  10343. this.lowerAlphaLimit = null;
  10344. this.upperAlphaLimit = null;
  10345. this.lowerBetaLimit = 0.01;
  10346. this.upperBetaLimit = Math.PI;
  10347. this.lowerRadiusLimit = null;
  10348. this.upperRadiusLimit = null;
  10349. this.angularSensibility = 1000.0;
  10350. this.wheelPrecision = 3.0;
  10351. this.pinchPrecision = 2.0;
  10352. this.keysUp = [38];
  10353. this.keysDown = [40];
  10354. this.keysLeft = [37];
  10355. this.keysRight = [39];
  10356. this.zoomOnFactor = 1;
  10357. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10358. this.pinchInwards = true;
  10359. this._keys = [];
  10360. this._viewMatrix = new BABYLON.Matrix();
  10361. this.checkCollisions = false;
  10362. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10363. this._collider = new BABYLON.Collider();
  10364. this._previousPosition = BABYLON.Vector3.Zero();
  10365. this._collisionVelocity = BABYLON.Vector3.Zero();
  10366. this._newPosition = BABYLON.Vector3.Zero();
  10367. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10368. if (collidedMesh === void 0) { collidedMesh = null; }
  10369. if (collisionId != null || collisionId != undefined)
  10370. newPosition.multiplyInPlace(_this._collider.radius);
  10371. if (!newPosition.equalsWithEpsilon(_this.position)) {
  10372. _this.position.copyFrom(_this._previousPosition);
  10373. _this.alpha = _this._previousAlpha;
  10374. _this.beta = _this._previousBeta;
  10375. _this.radius = _this._previousRadius;
  10376. if (_this.onCollide && collidedMesh) {
  10377. _this.onCollide(collidedMesh);
  10378. }
  10379. }
  10380. _this._collisionTriggered = false;
  10381. };
  10382. if (!this.target) {
  10383. this.target = BABYLON.Vector3.Zero();
  10384. }
  10385. this.getViewMatrix();
  10386. }
  10387. ArcRotateCamera.prototype._getTargetPosition = function () {
  10388. return this.target.position || this.target;
  10389. };
  10390. // Cache
  10391. ArcRotateCamera.prototype._initCache = function () {
  10392. _super.prototype._initCache.call(this);
  10393. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10394. this._cache.alpha = undefined;
  10395. this._cache.beta = undefined;
  10396. this._cache.radius = undefined;
  10397. this._cache.targetScreenOffset = undefined;
  10398. };
  10399. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10400. if (!ignoreParentClass) {
  10401. _super.prototype._updateCache.call(this);
  10402. }
  10403. this._cache.target.copyFrom(this._getTargetPosition());
  10404. this._cache.alpha = this.alpha;
  10405. this._cache.beta = this.beta;
  10406. this._cache.radius = this.radius;
  10407. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10408. };
  10409. // Synchronized
  10410. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10411. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10412. return false;
  10413. return this._cache.target.equals(this._getTargetPosition())
  10414. && this._cache.alpha === this.alpha
  10415. && this._cache.beta === this.beta
  10416. && this._cache.radius === this.radius
  10417. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10418. };
  10419. // Methods
  10420. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10421. var _this = this;
  10422. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10423. var previousPinchDistance = 0;
  10424. var pointers = new BABYLON.SmartCollection();
  10425. if (this._attachedElement) {
  10426. return;
  10427. }
  10428. this._attachedElement = element;
  10429. var engine = this.getEngine();
  10430. if (this._onPointerDown === undefined) {
  10431. this._onPointerDown = function (evt) {
  10432. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10433. cacheSoloPointer = pointers.item(evt.pointerId);
  10434. if (!noPreventDefault) {
  10435. evt.preventDefault();
  10436. }
  10437. };
  10438. this._onPointerUp = function (evt) {
  10439. cacheSoloPointer = null;
  10440. previousPinchDistance = 0;
  10441. pointers.remove(evt.pointerId);
  10442. if (!noPreventDefault) {
  10443. evt.preventDefault();
  10444. }
  10445. };
  10446. this._onPointerMove = function (evt) {
  10447. if (!noPreventDefault) {
  10448. evt.preventDefault();
  10449. }
  10450. switch (pointers.count) {
  10451. case 1:
  10452. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  10453. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  10454. var offsetX = evt.clientX - cacheSoloPointer.x;
  10455. var offsetY = evt.clientY - cacheSoloPointer.y;
  10456. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10457. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10458. //pointers.item(evt.pointerId).x = evt.clientX;
  10459. //pointers.item(evt.pointerId).y = evt.clientY;
  10460. cacheSoloPointer.x = evt.clientX;
  10461. cacheSoloPointer.y = evt.clientY;
  10462. break;
  10463. case 2:
  10464. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10465. pointers.item(evt.pointerId).x = evt.clientX;
  10466. pointers.item(evt.pointerId).y = evt.clientY;
  10467. var direction = _this.pinchInwards ? 1 : -1;
  10468. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10469. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10470. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10471. if (previousPinchDistance === 0) {
  10472. previousPinchDistance = pinchSquaredDistance;
  10473. return;
  10474. }
  10475. if (pinchSquaredDistance !== previousPinchDistance) {
  10476. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10477. previousPinchDistance = pinchSquaredDistance;
  10478. }
  10479. break;
  10480. default:
  10481. if (pointers.item(evt.pointerId)) {
  10482. pointers.item(evt.pointerId).x = evt.clientX;
  10483. pointers.item(evt.pointerId).y = evt.clientY;
  10484. }
  10485. }
  10486. };
  10487. this._onMouseMove = function (evt) {
  10488. if (!engine.isPointerLock) {
  10489. return;
  10490. }
  10491. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10492. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10493. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10494. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10495. if (!noPreventDefault) {
  10496. evt.preventDefault();
  10497. }
  10498. };
  10499. this._wheel = function (event) {
  10500. var delta = 0;
  10501. if (event.wheelDelta) {
  10502. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10503. }
  10504. else if (event.detail) {
  10505. delta = -event.detail / _this.wheelPrecision;
  10506. }
  10507. if (delta)
  10508. _this.inertialRadiusOffset += delta;
  10509. if (event.preventDefault) {
  10510. if (!noPreventDefault) {
  10511. event.preventDefault();
  10512. }
  10513. }
  10514. };
  10515. this._onKeyDown = function (evt) {
  10516. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10517. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10518. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10519. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10520. var index = _this._keys.indexOf(evt.keyCode);
  10521. if (index === -1) {
  10522. _this._keys.push(evt.keyCode);
  10523. }
  10524. if (evt.preventDefault) {
  10525. if (!noPreventDefault) {
  10526. evt.preventDefault();
  10527. }
  10528. }
  10529. }
  10530. };
  10531. this._onKeyUp = function (evt) {
  10532. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10533. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10534. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10535. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10536. var index = _this._keys.indexOf(evt.keyCode);
  10537. if (index >= 0) {
  10538. _this._keys.splice(index, 1);
  10539. }
  10540. if (evt.preventDefault) {
  10541. if (!noPreventDefault) {
  10542. evt.preventDefault();
  10543. }
  10544. }
  10545. }
  10546. };
  10547. this._onLostFocus = function () {
  10548. _this._keys = [];
  10549. pointers.empty();
  10550. previousPinchDistance = 0;
  10551. cacheSoloPointer = null;
  10552. };
  10553. this._onGestureStart = function (e) {
  10554. if (window.MSGesture === undefined) {
  10555. return;
  10556. }
  10557. if (!_this._MSGestureHandler) {
  10558. _this._MSGestureHandler = new MSGesture();
  10559. _this._MSGestureHandler.target = element;
  10560. }
  10561. _this._MSGestureHandler.addPointer(e.pointerId);
  10562. };
  10563. this._onGesture = function (e) {
  10564. _this.radius *= e.scale;
  10565. if (e.preventDefault) {
  10566. if (!noPreventDefault) {
  10567. e.stopPropagation();
  10568. e.preventDefault();
  10569. }
  10570. }
  10571. };
  10572. this._reset = function () {
  10573. _this._keys = [];
  10574. _this.inertialAlphaOffset = 0;
  10575. _this.inertialBetaOffset = 0;
  10576. _this.inertialRadiusOffset = 0;
  10577. pointers.empty();
  10578. previousPinchDistance = 0;
  10579. cacheSoloPointer = null;
  10580. };
  10581. }
  10582. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10583. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10584. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10585. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10586. element.addEventListener("mousemove", this._onMouseMove, false);
  10587. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10588. element.addEventListener("MSGestureChange", this._onGesture, false);
  10589. element.addEventListener('mousewheel', this._wheel, false);
  10590. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10591. BABYLON.Tools.RegisterTopRootEvents([
  10592. { name: "keydown", handler: this._onKeyDown },
  10593. { name: "keyup", handler: this._onKeyUp },
  10594. { name: "blur", handler: this._onLostFocus }
  10595. ]);
  10596. };
  10597. ArcRotateCamera.prototype.detachControl = function (element) {
  10598. if (this._attachedElement !== element) {
  10599. return;
  10600. }
  10601. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10602. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10603. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10604. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10605. element.removeEventListener("mousemove", this._onMouseMove);
  10606. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10607. element.removeEventListener("MSGestureChange", this._onGesture);
  10608. element.removeEventListener('mousewheel', this._wheel);
  10609. element.removeEventListener('DOMMouseScroll', this._wheel);
  10610. BABYLON.Tools.UnregisterTopRootEvents([
  10611. { name: "keydown", handler: this._onKeyDown },
  10612. { name: "keyup", handler: this._onKeyUp },
  10613. { name: "blur", handler: this._onLostFocus }
  10614. ]);
  10615. this._MSGestureHandler = null;
  10616. this._attachedElement = null;
  10617. if (this._reset) {
  10618. this._reset();
  10619. }
  10620. };
  10621. ArcRotateCamera.prototype._update = function () {
  10622. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10623. if (this._collisionTriggered) {
  10624. return;
  10625. }
  10626. // Keyboard
  10627. for (var index = 0; index < this._keys.length; index++) {
  10628. var keyCode = this._keys[index];
  10629. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10630. this.inertialAlphaOffset -= 0.01;
  10631. }
  10632. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10633. this.inertialBetaOffset -= 0.01;
  10634. }
  10635. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10636. this.inertialAlphaOffset += 0.01;
  10637. }
  10638. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10639. this.inertialBetaOffset += 0.01;
  10640. }
  10641. }
  10642. // Inertia
  10643. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  10644. this.alpha += this.inertialAlphaOffset;
  10645. this.beta += this.inertialBetaOffset;
  10646. this.radius -= this.inertialRadiusOffset;
  10647. this.inertialAlphaOffset *= this.inertia;
  10648. this.inertialBetaOffset *= this.inertia;
  10649. this.inertialRadiusOffset *= this.inertia;
  10650. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  10651. this.inertialAlphaOffset = 0;
  10652. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  10653. this.inertialBetaOffset = 0;
  10654. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  10655. this.inertialRadiusOffset = 0;
  10656. }
  10657. // Limits
  10658. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  10659. this.alpha = this.lowerAlphaLimit;
  10660. }
  10661. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  10662. this.alpha = this.upperAlphaLimit;
  10663. }
  10664. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  10665. this.beta = this.lowerBetaLimit;
  10666. }
  10667. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  10668. this.beta = this.upperBetaLimit;
  10669. }
  10670. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  10671. this.radius = this.lowerRadiusLimit;
  10672. }
  10673. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  10674. this.radius = this.upperRadiusLimit;
  10675. }
  10676. };
  10677. ArcRotateCamera.prototype.setPosition = function (position) {
  10678. var radiusv3 = position.subtract(this._getTargetPosition());
  10679. this.radius = radiusv3.length();
  10680. // Alpha
  10681. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  10682. if (radiusv3.z < 0) {
  10683. this.alpha = 2 * Math.PI - this.alpha;
  10684. }
  10685. // Beta
  10686. this.beta = Math.acos(radiusv3.y / this.radius);
  10687. };
  10688. ArcRotateCamera.prototype._getViewMatrix = function () {
  10689. // Compute
  10690. var cosa = Math.cos(this.alpha);
  10691. var sina = Math.sin(this.alpha);
  10692. var cosb = Math.cos(this.beta);
  10693. var sinb = Math.sin(this.beta);
  10694. var target = this._getTargetPosition();
  10695. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  10696. if (this.checkCollisions) {
  10697. this._collider.radius = this.collisionRadius;
  10698. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  10699. this._collisionTriggered = true;
  10700. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10701. }
  10702. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  10703. this._previousAlpha = this.alpha;
  10704. this._previousBeta = this.beta;
  10705. this._previousRadius = this.radius;
  10706. this._previousPosition.copyFrom(this.position);
  10707. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  10708. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  10709. return this._viewMatrix;
  10710. };
  10711. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  10712. meshes = meshes || this.getScene().meshes;
  10713. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  10714. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  10715. this.radius = distance * this.zoomOnFactor;
  10716. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  10717. };
  10718. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  10719. var meshesOrMinMaxVector;
  10720. var distance;
  10721. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  10722. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  10723. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10724. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  10725. }
  10726. else {
  10727. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  10728. distance = meshesOrMinMaxVectorAndDistance.distance;
  10729. }
  10730. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  10731. this.maxZ = distance * 2;
  10732. };
  10733. return ArcRotateCamera;
  10734. })(BABYLON.Camera);
  10735. BABYLON.ArcRotateCamera = ArcRotateCamera;
  10736. })(BABYLON || (BABYLON = {}));
  10737. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  10738. var __extends = this.__extends || function (d, b) {
  10739. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10740. function __() { this.constructor = d; }
  10741. __.prototype = b.prototype;
  10742. d.prototype = new __();
  10743. };
  10744. var BABYLON;
  10745. (function (BABYLON) {
  10746. // We're mainly based on the logic defined into the FreeCamera code
  10747. var DeviceOrientationCamera = (function (_super) {
  10748. __extends(DeviceOrientationCamera, _super);
  10749. function DeviceOrientationCamera(name, position, scene) {
  10750. var _this = this;
  10751. _super.call(this, name, position, scene);
  10752. this._offsetX = null;
  10753. this._offsetY = null;
  10754. this._orientationGamma = 0;
  10755. this._orientationBeta = 0;
  10756. this._initialOrientationGamma = 0;
  10757. this._initialOrientationBeta = 0;
  10758. this.angularSensibility = 10000.0;
  10759. this.moveSensibility = 50.0;
  10760. window.addEventListener("resize", function () {
  10761. _this._initialOrientationGamma = null;
  10762. }, false);
  10763. }
  10764. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10765. var _this = this;
  10766. if (this._attachedCanvas) {
  10767. return;
  10768. }
  10769. this._attachedCanvas = canvas;
  10770. if (!this._orientationChanged) {
  10771. this._orientationChanged = function (evt) {
  10772. if (!_this._initialOrientationGamma) {
  10773. _this._initialOrientationGamma = evt.gamma;
  10774. _this._initialOrientationBeta = evt.beta;
  10775. }
  10776. _this._orientationGamma = evt.gamma;
  10777. _this._orientationBeta = evt.beta;
  10778. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  10779. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  10780. };
  10781. }
  10782. window.addEventListener("deviceorientation", this._orientationChanged);
  10783. };
  10784. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  10785. if (this._attachedCanvas != canvas) {
  10786. return;
  10787. }
  10788. window.removeEventListener("deviceorientation", this._orientationChanged);
  10789. this._attachedCanvas = null;
  10790. this._orientationGamma = 0;
  10791. this._orientationBeta = 0;
  10792. this._initialOrientationGamma = 0;
  10793. this._initialOrientationBeta = 0;
  10794. };
  10795. DeviceOrientationCamera.prototype._checkInputs = function () {
  10796. if (!this._offsetX) {
  10797. return;
  10798. }
  10799. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  10800. var speed = this._computeLocalCameraSpeed();
  10801. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10802. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10803. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10804. };
  10805. return DeviceOrientationCamera;
  10806. })(BABYLON.FreeCamera);
  10807. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  10808. })(BABYLON || (BABYLON = {}));
  10809. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  10810. var BABYLON;
  10811. (function (BABYLON) {
  10812. var RenderingManager = (function () {
  10813. function RenderingManager(scene) {
  10814. this._renderingGroups = new Array();
  10815. this._scene = scene;
  10816. }
  10817. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10818. if (this._scene._activeParticleSystems.length === 0) {
  10819. return;
  10820. }
  10821. // Particles
  10822. var beforeParticlesDate = BABYLON.Tools.Now;
  10823. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10824. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10825. if (particleSystem.renderingGroupId !== index) {
  10826. continue;
  10827. }
  10828. this._clearDepthBuffer();
  10829. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10830. this._scene._activeParticles += particleSystem.render();
  10831. }
  10832. }
  10833. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10834. };
  10835. RenderingManager.prototype._renderSprites = function (index) {
  10836. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  10837. return;
  10838. }
  10839. // Sprites
  10840. var beforeSpritessDate = BABYLON.Tools.Now;
  10841. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10842. var spriteManager = this._scene.spriteManagers[id];
  10843. if (spriteManager.renderingGroupId === index) {
  10844. this._clearDepthBuffer();
  10845. spriteManager.render();
  10846. }
  10847. }
  10848. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10849. };
  10850. RenderingManager.prototype._clearDepthBuffer = function () {
  10851. if (this._depthBufferAlreadyCleaned) {
  10852. return;
  10853. }
  10854. this._scene.getEngine().clear(0, false, true);
  10855. this._depthBufferAlreadyCleaned = true;
  10856. };
  10857. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10858. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10859. this._depthBufferAlreadyCleaned = false;
  10860. var renderingGroup = this._renderingGroups[index];
  10861. var needToStepBack = false;
  10862. if (renderingGroup) {
  10863. this._clearDepthBuffer();
  10864. if (!renderingGroup.render(customRenderFunction)) {
  10865. this._renderingGroups.splice(index, 1);
  10866. needToStepBack = true;
  10867. }
  10868. }
  10869. if (renderSprites) {
  10870. this._renderSprites(index);
  10871. }
  10872. if (renderParticles) {
  10873. this._renderParticles(index, activeMeshes);
  10874. }
  10875. if (needToStepBack) {
  10876. index--;
  10877. }
  10878. }
  10879. };
  10880. RenderingManager.prototype.reset = function () {
  10881. for (var index in this._renderingGroups) {
  10882. var renderingGroup = this._renderingGroups[index];
  10883. renderingGroup.prepare();
  10884. }
  10885. };
  10886. RenderingManager.prototype.dispatch = function (subMesh) {
  10887. var mesh = subMesh.getMesh();
  10888. var renderingGroupId = mesh.renderingGroupId || 0;
  10889. if (!this._renderingGroups[renderingGroupId]) {
  10890. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10891. }
  10892. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10893. };
  10894. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10895. return RenderingManager;
  10896. })();
  10897. BABYLON.RenderingManager = RenderingManager;
  10898. })(BABYLON || (BABYLON = {}));
  10899. //# sourceMappingURL=babylon.renderingManager.js.map
  10900. var BABYLON;
  10901. (function (BABYLON) {
  10902. var RenderingGroup = (function () {
  10903. function RenderingGroup(index, scene) {
  10904. this.index = index;
  10905. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10906. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10907. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10908. this._scene = scene;
  10909. }
  10910. RenderingGroup.prototype.render = function (customRenderFunction) {
  10911. if (customRenderFunction) {
  10912. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10913. return true;
  10914. }
  10915. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10916. return false;
  10917. }
  10918. var engine = this._scene.getEngine();
  10919. // Opaque
  10920. var subIndex;
  10921. var submesh;
  10922. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10923. submesh = this._opaqueSubMeshes.data[subIndex];
  10924. submesh.render();
  10925. }
  10926. // Alpha test
  10927. engine.setAlphaTesting(true);
  10928. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10929. submesh = this._alphaTestSubMeshes.data[subIndex];
  10930. submesh.render();
  10931. }
  10932. engine.setAlphaTesting(false);
  10933. // Transparent
  10934. if (this._transparentSubMeshes.length) {
  10935. // Sorting
  10936. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10937. submesh = this._transparentSubMeshes.data[subIndex];
  10938. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10939. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10940. }
  10941. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10942. sortedArray.sort(function (a, b) {
  10943. // Alpha index first
  10944. if (a._alphaIndex > b._alphaIndex) {
  10945. return 1;
  10946. }
  10947. if (a._alphaIndex < b._alphaIndex) {
  10948. return -1;
  10949. }
  10950. // Then distance to camera
  10951. if (a._distanceToCamera < b._distanceToCamera) {
  10952. return 1;
  10953. }
  10954. if (a._distanceToCamera > b._distanceToCamera) {
  10955. return -1;
  10956. }
  10957. return 0;
  10958. });
  10959. // Rendering
  10960. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10961. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10962. submesh = sortedArray[subIndex];
  10963. submesh.render();
  10964. }
  10965. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10966. }
  10967. return true;
  10968. };
  10969. RenderingGroup.prototype.prepare = function () {
  10970. this._opaqueSubMeshes.reset();
  10971. this._transparentSubMeshes.reset();
  10972. this._alphaTestSubMeshes.reset();
  10973. };
  10974. RenderingGroup.prototype.dispatch = function (subMesh) {
  10975. var material = subMesh.getMaterial();
  10976. var mesh = subMesh.getMesh();
  10977. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10978. this._transparentSubMeshes.push(subMesh);
  10979. }
  10980. else if (material.needAlphaTesting()) {
  10981. this._alphaTestSubMeshes.push(subMesh);
  10982. }
  10983. else {
  10984. this._opaqueSubMeshes.push(subMesh); // Opaque
  10985. }
  10986. };
  10987. return RenderingGroup;
  10988. })();
  10989. BABYLON.RenderingGroup = RenderingGroup;
  10990. })(BABYLON || (BABYLON = {}));
  10991. //# sourceMappingURL=babylon.renderingGroup.js.map
  10992. var BABYLON;
  10993. (function (BABYLON) {
  10994. /**
  10995. * Represents a scene to be rendered by the engine.
  10996. * @see http://doc.babylonjs.com/page.php?p=21911
  10997. */
  10998. var Scene = (function () {
  10999. /**
  11000. * @constructor
  11001. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11002. */
  11003. function Scene(engine) {
  11004. // Members
  11005. this.autoClear = true;
  11006. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11007. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11008. this.forceWireframe = false;
  11009. this.forcePointsCloud = false;
  11010. this.forceShowBoundingBoxes = false;
  11011. this.animationsEnabled = true;
  11012. 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
  11013. // Fog
  11014. /**
  11015. * is fog enabled on this scene.
  11016. * @type {boolean}
  11017. */
  11018. this.fogEnabled = true;
  11019. this.fogMode = Scene.FOGMODE_NONE;
  11020. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11021. this.fogDensity = 0.1;
  11022. this.fogStart = 0;
  11023. this.fogEnd = 1000.0;
  11024. // Lights
  11025. /**
  11026. * is shadow enabled on this scene.
  11027. * @type {boolean}
  11028. */
  11029. this.shadowsEnabled = true;
  11030. /**
  11031. * is light enabled on this scene.
  11032. * @type {boolean}
  11033. */
  11034. this.lightsEnabled = true;
  11035. /**
  11036. * All of the lights added to this scene.
  11037. * @see BABYLON.Light
  11038. * @type {BABYLON.Light[]}
  11039. */
  11040. this.lights = new Array();
  11041. // Cameras
  11042. /**
  11043. * All of the cameras added to this scene.
  11044. * @see BABYLON.Camera
  11045. * @type {BABYLON.Camera[]}
  11046. */
  11047. this.cameras = new Array();
  11048. this.activeCameras = new Array();
  11049. // Meshes
  11050. /**
  11051. * All of the (abstract) meshes added to this scene.
  11052. * @see BABYLON.AbstractMesh
  11053. * @type {BABYLON.AbstractMesh[]}
  11054. */
  11055. this.meshes = new Array();
  11056. // Geometries
  11057. this._geometries = new Array();
  11058. this.materials = new Array();
  11059. this.multiMaterials = new Array();
  11060. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11061. // Textures
  11062. this.texturesEnabled = true;
  11063. this.textures = new Array();
  11064. // Particles
  11065. this.particlesEnabled = true;
  11066. this.particleSystems = new Array();
  11067. // Sprites
  11068. this.spritesEnabled = true;
  11069. this.spriteManagers = new Array();
  11070. // Layers
  11071. this.layers = new Array();
  11072. // Skeletons
  11073. this.skeletonsEnabled = true;
  11074. this.skeletons = new Array();
  11075. // Lens flares
  11076. this.lensFlaresEnabled = true;
  11077. this.lensFlareSystems = new Array();
  11078. // Collisions
  11079. this.collisionsEnabled = true;
  11080. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  11081. // Postprocesses
  11082. this.postProcessesEnabled = true;
  11083. // Customs render targets
  11084. this.renderTargetsEnabled = true;
  11085. this.dumpNextRenderTargets = false;
  11086. this.customRenderTargets = new Array();
  11087. // Imported meshes
  11088. this.importedMeshesFiles = new Array();
  11089. this._actionManagers = new Array();
  11090. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11091. // Procedural textures
  11092. this.proceduralTexturesEnabled = true;
  11093. this._proceduralTextures = new Array();
  11094. this.soundTracks = new Array();
  11095. this._audioEnabled = true;
  11096. this._headphone = false;
  11097. this._totalVertices = 0;
  11098. this._activeIndices = 0;
  11099. this._activeParticles = 0;
  11100. this._lastFrameDuration = 0;
  11101. this._evaluateActiveMeshesDuration = 0;
  11102. this._renderTargetsDuration = 0;
  11103. this._particlesDuration = 0;
  11104. this._renderDuration = 0;
  11105. this._spritesDuration = 0;
  11106. this._animationRatio = 0;
  11107. this._renderId = 0;
  11108. this._executeWhenReadyTimeoutId = -1;
  11109. this._toBeDisposed = new BABYLON.SmartArray(256);
  11110. this._onReadyCallbacks = new Array();
  11111. this._pendingData = []; //ANY
  11112. this._onBeforeRenderCallbacks = new Array();
  11113. this._onAfterRenderCallbacks = new Array();
  11114. this._activeMeshes = new BABYLON.SmartArray(256);
  11115. this._processedMaterials = new BABYLON.SmartArray(256);
  11116. this._renderTargets = new BABYLON.SmartArray(256);
  11117. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11118. this._activeSkeletons = new BABYLON.SmartArray(32);
  11119. this._activeBones = 0;
  11120. this._activeAnimatables = new Array();
  11121. this._transformMatrix = BABYLON.Matrix.Zero();
  11122. this._uniqueIdCounter = 0;
  11123. this._engine = engine;
  11124. engine.scenes.push(this);
  11125. this._renderingManager = new BABYLON.RenderingManager(this);
  11126. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11127. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11128. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11129. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11130. this.attachControl();
  11131. this._debugLayer = new BABYLON.DebugLayer(this);
  11132. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11133. //simplification queue
  11134. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11135. //collision coordinator initialization. For now legacy per default.
  11136. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11137. }
  11138. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11139. get: function () {
  11140. return Scene._FOGMODE_NONE;
  11141. },
  11142. enumerable: true,
  11143. configurable: true
  11144. });
  11145. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11146. get: function () {
  11147. return Scene._FOGMODE_EXP;
  11148. },
  11149. enumerable: true,
  11150. configurable: true
  11151. });
  11152. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11153. get: function () {
  11154. return Scene._FOGMODE_EXP2;
  11155. },
  11156. enumerable: true,
  11157. configurable: true
  11158. });
  11159. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11160. get: function () {
  11161. return Scene._FOGMODE_LINEAR;
  11162. },
  11163. enumerable: true,
  11164. configurable: true
  11165. });
  11166. Object.defineProperty(Scene.prototype, "debugLayer", {
  11167. // Properties
  11168. get: function () {
  11169. return this._debugLayer;
  11170. },
  11171. enumerable: true,
  11172. configurable: true
  11173. });
  11174. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11175. get: function () {
  11176. return this._workerCollisions;
  11177. },
  11178. set: function (enabled) {
  11179. enabled = (enabled && !!Worker);
  11180. this._workerCollisions = enabled;
  11181. if (this.collisionCoordinator) {
  11182. this.collisionCoordinator.destroy();
  11183. }
  11184. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11185. this.collisionCoordinator.init(this);
  11186. },
  11187. enumerable: true,
  11188. configurable: true
  11189. });
  11190. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11191. /**
  11192. * The mesh that is currently under the pointer.
  11193. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11194. */
  11195. get: function () {
  11196. return this._meshUnderPointer;
  11197. },
  11198. enumerable: true,
  11199. configurable: true
  11200. });
  11201. Object.defineProperty(Scene.prototype, "pointerX", {
  11202. /**
  11203. * Current on-screen X position of the pointer
  11204. * @return {number} X position of the pointer
  11205. */
  11206. get: function () {
  11207. return this._pointerX;
  11208. },
  11209. enumerable: true,
  11210. configurable: true
  11211. });
  11212. Object.defineProperty(Scene.prototype, "pointerY", {
  11213. /**
  11214. * Current on-screen Y position of the pointer
  11215. * @return {number} Y position of the pointer
  11216. */
  11217. get: function () {
  11218. return this._pointerY;
  11219. },
  11220. enumerable: true,
  11221. configurable: true
  11222. });
  11223. Scene.prototype.getCachedMaterial = function () {
  11224. return this._cachedMaterial;
  11225. };
  11226. Scene.prototype.getBoundingBoxRenderer = function () {
  11227. return this._boundingBoxRenderer;
  11228. };
  11229. Scene.prototype.getOutlineRenderer = function () {
  11230. return this._outlineRenderer;
  11231. };
  11232. Scene.prototype.getEngine = function () {
  11233. return this._engine;
  11234. };
  11235. Scene.prototype.getTotalVertices = function () {
  11236. return this._totalVertices;
  11237. };
  11238. Scene.prototype.getActiveIndices = function () {
  11239. return this._activeIndices;
  11240. };
  11241. Scene.prototype.getActiveParticles = function () {
  11242. return this._activeParticles;
  11243. };
  11244. Scene.prototype.getActiveBones = function () {
  11245. return this._activeBones;
  11246. };
  11247. // Stats
  11248. Scene.prototype.getLastFrameDuration = function () {
  11249. return this._lastFrameDuration;
  11250. };
  11251. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11252. return this._evaluateActiveMeshesDuration;
  11253. };
  11254. Scene.prototype.getActiveMeshes = function () {
  11255. return this._activeMeshes;
  11256. };
  11257. Scene.prototype.getRenderTargetsDuration = function () {
  11258. return this._renderTargetsDuration;
  11259. };
  11260. Scene.prototype.getRenderDuration = function () {
  11261. return this._renderDuration;
  11262. };
  11263. Scene.prototype.getParticlesDuration = function () {
  11264. return this._particlesDuration;
  11265. };
  11266. Scene.prototype.getSpritesDuration = function () {
  11267. return this._spritesDuration;
  11268. };
  11269. Scene.prototype.getAnimationRatio = function () {
  11270. return this._animationRatio;
  11271. };
  11272. Scene.prototype.getRenderId = function () {
  11273. return this._renderId;
  11274. };
  11275. Scene.prototype.incrementRenderId = function () {
  11276. this._renderId++;
  11277. };
  11278. Scene.prototype._updatePointerPosition = function (evt) {
  11279. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11280. this._pointerX = evt.clientX - canvasRect.left;
  11281. this._pointerY = evt.clientY - canvasRect.top;
  11282. if (this.cameraToUseForPointers) {
  11283. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11284. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11285. }
  11286. };
  11287. // Pointers handling
  11288. Scene.prototype.attachControl = function () {
  11289. var _this = this;
  11290. this._onPointerMove = function (evt) {
  11291. var canvas = _this._engine.getRenderingCanvas();
  11292. _this._updatePointerPosition(evt);
  11293. 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);
  11294. if (pickResult.hit) {
  11295. _this._meshUnderPointer = pickResult.pickedMesh;
  11296. _this.setPointerOverMesh(pickResult.pickedMesh);
  11297. canvas.style.cursor = "pointer";
  11298. }
  11299. else {
  11300. _this.setPointerOverMesh(null);
  11301. canvas.style.cursor = "";
  11302. _this._meshUnderPointer = null;
  11303. }
  11304. };
  11305. this._onPointerDown = function (evt) {
  11306. var predicate = null;
  11307. if (!_this.onPointerDown) {
  11308. predicate = function (mesh) {
  11309. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11310. };
  11311. }
  11312. _this._updatePointerPosition(evt);
  11313. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11314. if (pickResult.hit) {
  11315. if (pickResult.pickedMesh.actionManager) {
  11316. switch (evt.button) {
  11317. case 0:
  11318. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11319. break;
  11320. case 1:
  11321. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11322. break;
  11323. case 2:
  11324. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11325. break;
  11326. }
  11327. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11328. }
  11329. }
  11330. if (_this.onPointerDown) {
  11331. _this.onPointerDown(evt, pickResult);
  11332. }
  11333. };
  11334. this._onPointerUp = function (evt) {
  11335. var predicate = null;
  11336. if (!_this.onPointerUp) {
  11337. predicate = function (mesh) {
  11338. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11339. };
  11340. }
  11341. _this._updatePointerPosition(evt);
  11342. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11343. if (pickResult.hit) {
  11344. if (pickResult.pickedMesh.actionManager) {
  11345. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11346. }
  11347. }
  11348. if (_this.onPointerUp) {
  11349. _this.onPointerUp(evt, pickResult);
  11350. }
  11351. };
  11352. this._onKeyDown = function (evt) {
  11353. if (_this.actionManager) {
  11354. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11355. }
  11356. };
  11357. this._onKeyUp = function (evt) {
  11358. if (_this.actionManager) {
  11359. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11360. }
  11361. };
  11362. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11363. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11364. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11365. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11366. BABYLON.Tools.RegisterTopRootEvents([
  11367. { name: "keydown", handler: this._onKeyDown },
  11368. { name: "keyup", handler: this._onKeyUp }
  11369. ]);
  11370. };
  11371. Scene.prototype.detachControl = function () {
  11372. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11373. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11374. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11375. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11376. BABYLON.Tools.UnregisterTopRootEvents([
  11377. { name: "keydown", handler: this._onKeyDown },
  11378. { name: "keyup", handler: this._onKeyUp }
  11379. ]);
  11380. };
  11381. // Ready
  11382. Scene.prototype.isReady = function () {
  11383. if (this._pendingData.length > 0) {
  11384. return false;
  11385. }
  11386. for (var index = 0; index < this._geometries.length; index++) {
  11387. var geometry = this._geometries[index];
  11388. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11389. return false;
  11390. }
  11391. }
  11392. for (index = 0; index < this.meshes.length; index++) {
  11393. var mesh = this.meshes[index];
  11394. if (!mesh.isReady()) {
  11395. return false;
  11396. }
  11397. var mat = mesh.material;
  11398. if (mat) {
  11399. if (!mat.isReady(mesh)) {
  11400. return false;
  11401. }
  11402. }
  11403. }
  11404. return true;
  11405. };
  11406. Scene.prototype.resetCachedMaterial = function () {
  11407. this._cachedMaterial = null;
  11408. };
  11409. Scene.prototype.registerBeforeRender = function (func) {
  11410. this._onBeforeRenderCallbacks.push(func);
  11411. };
  11412. Scene.prototype.unregisterBeforeRender = function (func) {
  11413. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11414. if (index > -1) {
  11415. this._onBeforeRenderCallbacks.splice(index, 1);
  11416. }
  11417. };
  11418. Scene.prototype.registerAfterRender = function (func) {
  11419. this._onAfterRenderCallbacks.push(func);
  11420. };
  11421. Scene.prototype.unregisterAfterRender = function (func) {
  11422. var index = this._onAfterRenderCallbacks.indexOf(func);
  11423. if (index > -1) {
  11424. this._onAfterRenderCallbacks.splice(index, 1);
  11425. }
  11426. };
  11427. Scene.prototype._addPendingData = function (data) {
  11428. this._pendingData.push(data);
  11429. };
  11430. Scene.prototype._removePendingData = function (data) {
  11431. var index = this._pendingData.indexOf(data);
  11432. if (index !== -1) {
  11433. this._pendingData.splice(index, 1);
  11434. }
  11435. };
  11436. Scene.prototype.getWaitingItemsCount = function () {
  11437. return this._pendingData.length;
  11438. };
  11439. /**
  11440. * Registers a function to be executed when the scene is ready.
  11441. * @param {Function} func - the function to be executed.
  11442. */
  11443. Scene.prototype.executeWhenReady = function (func) {
  11444. var _this = this;
  11445. this._onReadyCallbacks.push(func);
  11446. if (this._executeWhenReadyTimeoutId !== -1) {
  11447. return;
  11448. }
  11449. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11450. _this._checkIsReady();
  11451. }, 150);
  11452. };
  11453. Scene.prototype._checkIsReady = function () {
  11454. var _this = this;
  11455. if (this.isReady()) {
  11456. this._onReadyCallbacks.forEach(function (func) {
  11457. func();
  11458. });
  11459. this._onReadyCallbacks = [];
  11460. this._executeWhenReadyTimeoutId = -1;
  11461. return;
  11462. }
  11463. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11464. _this._checkIsReady();
  11465. }, 150);
  11466. };
  11467. // Animations
  11468. /**
  11469. * Will start the animation sequence of a given target
  11470. * @param target - the target
  11471. * @param {number} from - from which frame should animation start
  11472. * @param {number} to - till which frame should animation run.
  11473. * @param {boolean} [loop] - should the animation loop
  11474. * @param {number} [speedRatio] - the speed in which to run the animation
  11475. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  11476. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  11477. * @return {BABYLON.Animatable} the animatable object created for this animation
  11478. * @see BABYLON.Animatable
  11479. * @see http://doc.babylonjs.com/page.php?p=22081
  11480. */
  11481. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  11482. if (speedRatio === undefined) {
  11483. speedRatio = 1.0;
  11484. }
  11485. this.stopAnimation(target);
  11486. if (!animatable) {
  11487. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  11488. }
  11489. // Local animations
  11490. if (target.animations) {
  11491. animatable.appendAnimations(target, target.animations);
  11492. }
  11493. // Children animations
  11494. if (target.getAnimatables) {
  11495. var animatables = target.getAnimatables();
  11496. for (var index = 0; index < animatables.length; index++) {
  11497. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  11498. }
  11499. }
  11500. return animatable;
  11501. };
  11502. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  11503. if (speedRatio === undefined) {
  11504. speedRatio = 1.0;
  11505. }
  11506. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  11507. return animatable;
  11508. };
  11509. Scene.prototype.getAnimatableByTarget = function (target) {
  11510. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11511. if (this._activeAnimatables[index].target === target) {
  11512. return this._activeAnimatables[index];
  11513. }
  11514. }
  11515. return null;
  11516. };
  11517. /**
  11518. * Will stop the animation of the given target
  11519. * @param target - the target
  11520. * @see beginAnimation
  11521. */
  11522. Scene.prototype.stopAnimation = function (target) {
  11523. var animatable = this.getAnimatableByTarget(target);
  11524. if (animatable) {
  11525. animatable.stop();
  11526. }
  11527. };
  11528. Scene.prototype._animate = function () {
  11529. if (!this.animationsEnabled) {
  11530. return;
  11531. }
  11532. if (!this._animationStartDate) {
  11533. this._animationStartDate = BABYLON.Tools.Now;
  11534. }
  11535. // Getting time
  11536. var now = BABYLON.Tools.Now;
  11537. var delay = now - this._animationStartDate;
  11538. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11539. this._activeAnimatables[index]._animate(delay);
  11540. }
  11541. };
  11542. // Matrix
  11543. Scene.prototype.getViewMatrix = function () {
  11544. return this._viewMatrix;
  11545. };
  11546. Scene.prototype.getProjectionMatrix = function () {
  11547. return this._projectionMatrix;
  11548. };
  11549. Scene.prototype.getTransformMatrix = function () {
  11550. return this._transformMatrix;
  11551. };
  11552. Scene.prototype.setTransformMatrix = function (view, projection) {
  11553. this._viewMatrix = view;
  11554. this._projectionMatrix = projection;
  11555. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11556. };
  11557. // Methods
  11558. Scene.prototype.addMesh = function (newMesh) {
  11559. newMesh.uniqueId = this._uniqueIdCounter++;
  11560. var position = this.meshes.push(newMesh);
  11561. //notify the collision coordinator
  11562. this.collisionCoordinator.onMeshAdded(newMesh);
  11563. if (this.onNewMeshAdded) {
  11564. this.onNewMeshAdded(newMesh, position, this);
  11565. }
  11566. };
  11567. Scene.prototype.removeMesh = function (toRemove) {
  11568. var index = this.meshes.indexOf(toRemove);
  11569. if (index !== -1) {
  11570. // Remove from the scene if mesh found
  11571. this.meshes.splice(index, 1);
  11572. }
  11573. //notify the collision coordinator
  11574. this.collisionCoordinator.onMeshRemoved(toRemove);
  11575. if (this.onMeshRemoved) {
  11576. this.onMeshRemoved(toRemove);
  11577. }
  11578. return index;
  11579. };
  11580. Scene.prototype.removeLight = function (toRemove) {
  11581. var index = this.lights.indexOf(toRemove);
  11582. if (index !== -1) {
  11583. // Remove from the scene if mesh found
  11584. this.lights.splice(index, 1);
  11585. }
  11586. if (this.onLightRemoved) {
  11587. this.onLightRemoved(toRemove);
  11588. }
  11589. return index;
  11590. };
  11591. Scene.prototype.removeCamera = function (toRemove) {
  11592. var index = this.cameras.indexOf(toRemove);
  11593. if (index !== -1) {
  11594. // Remove from the scene if mesh found
  11595. this.cameras.splice(index, 1);
  11596. }
  11597. // Remove from activeCameras
  11598. var index2 = this.activeCameras.indexOf(toRemove);
  11599. if (index2 !== -1) {
  11600. // Remove from the scene if mesh found
  11601. this.activeCameras.splice(index2, 1);
  11602. }
  11603. // Reset the activeCamera
  11604. if (this.activeCamera === toRemove) {
  11605. if (this.cameras.length > 0) {
  11606. this.activeCamera = this.cameras[0];
  11607. }
  11608. else {
  11609. this.activeCamera = null;
  11610. }
  11611. }
  11612. if (this.onCameraRemoved) {
  11613. this.onCameraRemoved(toRemove);
  11614. }
  11615. return index;
  11616. };
  11617. Scene.prototype.addLight = function (newLight) {
  11618. newLight.uniqueId = this._uniqueIdCounter++;
  11619. var position = this.lights.push(newLight);
  11620. if (this.onNewLightAdded) {
  11621. this.onNewLightAdded(newLight, position, this);
  11622. }
  11623. };
  11624. Scene.prototype.addCamera = function (newCamera) {
  11625. newCamera.uniqueId = this._uniqueIdCounter++;
  11626. var position = this.cameras.push(newCamera);
  11627. if (this.onNewCameraAdded) {
  11628. this.onNewCameraAdded(newCamera, position, this);
  11629. }
  11630. };
  11631. /**
  11632. * sets the active camera of the scene using its ID
  11633. * @param {string} id - the camera's ID
  11634. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11635. * @see activeCamera
  11636. */
  11637. Scene.prototype.setActiveCameraByID = function (id) {
  11638. var camera = this.getCameraByID(id);
  11639. if (camera) {
  11640. this.activeCamera = camera;
  11641. return camera;
  11642. }
  11643. return null;
  11644. };
  11645. /**
  11646. * sets the active camera of the scene using its name
  11647. * @param {string} name - the camera's name
  11648. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11649. * @see activeCamera
  11650. */
  11651. Scene.prototype.setActiveCameraByName = function (name) {
  11652. var camera = this.getCameraByName(name);
  11653. if (camera) {
  11654. this.activeCamera = camera;
  11655. return camera;
  11656. }
  11657. return null;
  11658. };
  11659. /**
  11660. * get a material using its id
  11661. * @param {string} the material's ID
  11662. * @return {BABYLON.Material|null} the material or null if none found.
  11663. */
  11664. Scene.prototype.getMaterialByID = function (id) {
  11665. for (var index = 0; index < this.materials.length; index++) {
  11666. if (this.materials[index].id === id) {
  11667. return this.materials[index];
  11668. }
  11669. }
  11670. return null;
  11671. };
  11672. /**
  11673. * get a material using its name
  11674. * @param {string} the material's name
  11675. * @return {BABYLON.Material|null} the material or null if none found.
  11676. */
  11677. Scene.prototype.getMaterialByName = function (name) {
  11678. for (var index = 0; index < this.materials.length; index++) {
  11679. if (this.materials[index].name === name) {
  11680. return this.materials[index];
  11681. }
  11682. }
  11683. return null;
  11684. };
  11685. Scene.prototype.getCameraByID = function (id) {
  11686. for (var index = 0; index < this.cameras.length; index++) {
  11687. if (this.cameras[index].id === id) {
  11688. return this.cameras[index];
  11689. }
  11690. }
  11691. return null;
  11692. };
  11693. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  11694. for (var index = 0; index < this.cameras.length; index++) {
  11695. if (this.cameras[index].uniqueId === uniqueId) {
  11696. return this.cameras[index];
  11697. }
  11698. }
  11699. return null;
  11700. };
  11701. /**
  11702. * get a camera using its name
  11703. * @param {string} the camera's name
  11704. * @return {BABYLON.Camera|null} the camera or null if none found.
  11705. */
  11706. Scene.prototype.getCameraByName = function (name) {
  11707. for (var index = 0; index < this.cameras.length; index++) {
  11708. if (this.cameras[index].name === name) {
  11709. return this.cameras[index];
  11710. }
  11711. }
  11712. return null;
  11713. };
  11714. /**
  11715. * get a light node using its name
  11716. * @param {string} the light's name
  11717. * @return {BABYLON.Light|null} the light or null if none found.
  11718. */
  11719. Scene.prototype.getLightByName = function (name) {
  11720. for (var index = 0; index < this.lights.length; index++) {
  11721. if (this.lights[index].name === name) {
  11722. return this.lights[index];
  11723. }
  11724. }
  11725. return null;
  11726. };
  11727. /**
  11728. * get a light node using its ID
  11729. * @param {string} the light's id
  11730. * @return {BABYLON.Light|null} the light or null if none found.
  11731. */
  11732. Scene.prototype.getLightByID = function (id) {
  11733. for (var index = 0; index < this.lights.length; index++) {
  11734. if (this.lights[index].id === id) {
  11735. return this.lights[index];
  11736. }
  11737. }
  11738. return null;
  11739. };
  11740. /**
  11741. * get a light node using its scene-generated unique ID
  11742. * @param {number} the light's unique id
  11743. * @return {BABYLON.Light|null} the light or null if none found.
  11744. */
  11745. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  11746. for (var index = 0; index < this.lights.length; index++) {
  11747. if (this.lights[index].uniqueId === uniqueId) {
  11748. return this.lights[index];
  11749. }
  11750. }
  11751. return null;
  11752. };
  11753. /**
  11754. * get a geometry using its ID
  11755. * @param {string} the geometry's id
  11756. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  11757. */
  11758. Scene.prototype.getGeometryByID = function (id) {
  11759. for (var index = 0; index < this._geometries.length; index++) {
  11760. if (this._geometries[index].id === id) {
  11761. return this._geometries[index];
  11762. }
  11763. }
  11764. return null;
  11765. };
  11766. /**
  11767. * add a new geometry to this scene.
  11768. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  11769. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  11770. * @return {boolean} was the geometry added or not
  11771. */
  11772. Scene.prototype.pushGeometry = function (geometry, force) {
  11773. if (!force && this.getGeometryByID(geometry.id)) {
  11774. return false;
  11775. }
  11776. this._geometries.push(geometry);
  11777. //notify the collision coordinator
  11778. this.collisionCoordinator.onGeometryAdded(geometry);
  11779. if (this.onGeometryAdded) {
  11780. this.onGeometryAdded(geometry);
  11781. }
  11782. return true;
  11783. };
  11784. /**
  11785. * Removes an existing geometry
  11786. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  11787. * @return {boolean} was the geometry removed or not
  11788. */
  11789. Scene.prototype.removeGeometry = function (geometry) {
  11790. var index = this._geometries.indexOf(geometry);
  11791. if (index > -1) {
  11792. this._geometries.splice(index, 1);
  11793. //notify the collision coordinator
  11794. this.collisionCoordinator.onGeometryDeleted(geometry);
  11795. if (this.onGeometryRemoved) {
  11796. this.onGeometryRemoved(geometry);
  11797. }
  11798. return true;
  11799. }
  11800. return false;
  11801. };
  11802. Scene.prototype.getGeometries = function () {
  11803. return this._geometries;
  11804. };
  11805. /**
  11806. * Get the first added mesh found of a given ID
  11807. * @param {string} id - the id to search for
  11808. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11809. */
  11810. Scene.prototype.getMeshByID = function (id) {
  11811. for (var index = 0; index < this.meshes.length; index++) {
  11812. if (this.meshes[index].id === id) {
  11813. return this.meshes[index];
  11814. }
  11815. }
  11816. return null;
  11817. };
  11818. /**
  11819. * Get a mesh with its auto-generated unique id
  11820. * @param {number} uniqueId - the unique id to search for
  11821. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11822. */
  11823. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  11824. for (var index = 0; index < this.meshes.length; index++) {
  11825. if (this.meshes[index].uniqueId === uniqueId) {
  11826. return this.meshes[index];
  11827. }
  11828. }
  11829. return null;
  11830. };
  11831. /**
  11832. * Get a the last added mesh found of a given ID
  11833. * @param {string} id - the id to search for
  11834. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11835. */
  11836. Scene.prototype.getLastMeshByID = function (id) {
  11837. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11838. if (this.meshes[index].id === id) {
  11839. return this.meshes[index];
  11840. }
  11841. }
  11842. return null;
  11843. };
  11844. /**
  11845. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  11846. * @param {string} id - the id to search for
  11847. * @return {BABYLON.Node|null} the node found or null if not found at all.
  11848. */
  11849. Scene.prototype.getLastEntryByID = function (id) {
  11850. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11851. if (this.meshes[index].id === id) {
  11852. return this.meshes[index];
  11853. }
  11854. }
  11855. for (index = this.cameras.length - 1; index >= 0; index--) {
  11856. if (this.cameras[index].id === id) {
  11857. return this.cameras[index];
  11858. }
  11859. }
  11860. for (index = this.lights.length - 1; index >= 0; index--) {
  11861. if (this.lights[index].id === id) {
  11862. return this.lights[index];
  11863. }
  11864. }
  11865. return null;
  11866. };
  11867. Scene.prototype.getNodeByName = function (name) {
  11868. var mesh = this.getMeshByName(name);
  11869. if (mesh) {
  11870. return mesh;
  11871. }
  11872. var light = this.getLightByName(name);
  11873. if (light) {
  11874. return light;
  11875. }
  11876. return this.getCameraByName(name);
  11877. };
  11878. Scene.prototype.getMeshByName = function (name) {
  11879. for (var index = 0; index < this.meshes.length; index++) {
  11880. if (this.meshes[index].name === name) {
  11881. return this.meshes[index];
  11882. }
  11883. }
  11884. return null;
  11885. };
  11886. Scene.prototype.getSoundByName = function (name) {
  11887. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  11888. if (this.mainSoundTrack.soundCollection[index].name === name) {
  11889. return this.mainSoundTrack.soundCollection[index];
  11890. }
  11891. }
  11892. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  11893. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  11894. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  11895. return this.soundTracks[sdIndex].soundCollection[index];
  11896. }
  11897. }
  11898. }
  11899. return null;
  11900. };
  11901. Scene.prototype.getLastSkeletonByID = function (id) {
  11902. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  11903. if (this.skeletons[index].id === id) {
  11904. return this.skeletons[index];
  11905. }
  11906. }
  11907. return null;
  11908. };
  11909. Scene.prototype.getSkeletonById = function (id) {
  11910. for (var index = 0; index < this.skeletons.length; index++) {
  11911. if (this.skeletons[index].id === id) {
  11912. return this.skeletons[index];
  11913. }
  11914. }
  11915. return null;
  11916. };
  11917. Scene.prototype.getSkeletonByName = function (name) {
  11918. for (var index = 0; index < this.skeletons.length; index++) {
  11919. if (this.skeletons[index].name === name) {
  11920. return this.skeletons[index];
  11921. }
  11922. }
  11923. return null;
  11924. };
  11925. Scene.prototype.isActiveMesh = function (mesh) {
  11926. return (this._activeMeshes.indexOf(mesh) !== -1);
  11927. };
  11928. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  11929. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  11930. var material = subMesh.getMaterial();
  11931. if (mesh.showSubMeshesBoundingBox) {
  11932. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  11933. }
  11934. if (material) {
  11935. // Render targets
  11936. if (material.getRenderTargetTextures) {
  11937. if (this._processedMaterials.indexOf(material) === -1) {
  11938. this._processedMaterials.push(material);
  11939. this._renderTargets.concat(material.getRenderTargetTextures());
  11940. }
  11941. }
  11942. // Dispatch
  11943. this._activeIndices += subMesh.indexCount;
  11944. this._renderingManager.dispatch(subMesh);
  11945. }
  11946. }
  11947. };
  11948. Scene.prototype._evaluateActiveMeshes = function () {
  11949. this.activeCamera._activeMeshes.reset();
  11950. this._activeMeshes.reset();
  11951. this._renderingManager.reset();
  11952. this._processedMaterials.reset();
  11953. this._activeParticleSystems.reset();
  11954. this._activeSkeletons.reset();
  11955. this._boundingBoxRenderer.reset();
  11956. if (!this._frustumPlanes) {
  11957. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  11958. }
  11959. else {
  11960. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  11961. }
  11962. // Meshes
  11963. var meshes;
  11964. var len;
  11965. if (this._selectionOctree) {
  11966. var selection = this._selectionOctree.select(this._frustumPlanes);
  11967. meshes = selection.data;
  11968. len = selection.length;
  11969. }
  11970. else {
  11971. len = this.meshes.length;
  11972. meshes = this.meshes;
  11973. }
  11974. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  11975. var mesh = meshes[meshIndex];
  11976. if (mesh.isBlocked) {
  11977. continue;
  11978. }
  11979. this._totalVertices += mesh.getTotalVertices();
  11980. if (!mesh.isReady() || !mesh.isEnabled()) {
  11981. continue;
  11982. }
  11983. mesh.computeWorldMatrix();
  11984. // Intersections
  11985. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  11986. this._meshesForIntersections.pushNoDuplicate(mesh);
  11987. }
  11988. // Switch to current LOD
  11989. var meshLOD = mesh.getLOD(this.activeCamera);
  11990. if (!meshLOD) {
  11991. continue;
  11992. }
  11993. mesh._preActivate();
  11994. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  11995. this._activeMeshes.push(mesh);
  11996. this.activeCamera._activeMeshes.push(mesh);
  11997. mesh._activate(this._renderId);
  11998. this._activeMesh(meshLOD);
  11999. }
  12000. }
  12001. // Particle systems
  12002. var beforeParticlesDate = BABYLON.Tools.Now;
  12003. if (this.particlesEnabled) {
  12004. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12005. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12006. var particleSystem = this.particleSystems[particleIndex];
  12007. if (!particleSystem.isStarted()) {
  12008. continue;
  12009. }
  12010. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12011. this._activeParticleSystems.push(particleSystem);
  12012. particleSystem.animate();
  12013. }
  12014. }
  12015. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12016. }
  12017. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12018. };
  12019. Scene.prototype._activeMesh = function (mesh) {
  12020. if (mesh.skeleton && this.skeletonsEnabled) {
  12021. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12022. }
  12023. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12024. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12025. }
  12026. if (mesh && mesh.subMeshes) {
  12027. // Submeshes Octrees
  12028. var len;
  12029. var subMeshes;
  12030. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12031. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12032. len = intersections.length;
  12033. subMeshes = intersections.data;
  12034. }
  12035. else {
  12036. subMeshes = mesh.subMeshes;
  12037. len = subMeshes.length;
  12038. }
  12039. for (var subIndex = 0; subIndex < len; subIndex++) {
  12040. var subMesh = subMeshes[subIndex];
  12041. this._evaluateSubMesh(subMesh, mesh);
  12042. }
  12043. }
  12044. };
  12045. Scene.prototype.updateTransformMatrix = function (force) {
  12046. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12047. };
  12048. Scene.prototype._renderForCamera = function (camera) {
  12049. var engine = this._engine;
  12050. this.activeCamera = camera;
  12051. if (!this.activeCamera)
  12052. throw new Error("Active camera not set");
  12053. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12054. // Viewport
  12055. engine.setViewport(this.activeCamera.viewport);
  12056. // Camera
  12057. this._renderId++;
  12058. this.updateTransformMatrix();
  12059. if (this.beforeCameraRender) {
  12060. this.beforeCameraRender(this.activeCamera);
  12061. }
  12062. // Meshes
  12063. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12064. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12065. this._evaluateActiveMeshes();
  12066. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12067. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12068. // Skeletons
  12069. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12070. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12071. skeleton.prepare();
  12072. }
  12073. // Render targets
  12074. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12075. if (this.renderTargetsEnabled) {
  12076. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12077. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12078. var renderTarget = this._renderTargets.data[renderIndex];
  12079. if (renderTarget._shouldRender()) {
  12080. this._renderId++;
  12081. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12082. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12083. }
  12084. }
  12085. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12086. this._renderId++;
  12087. }
  12088. if (this._renderTargets.length > 0) {
  12089. engine.restoreDefaultFramebuffer();
  12090. }
  12091. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12092. // Prepare Frame
  12093. this.postProcessManager._prepareFrame();
  12094. var beforeRenderDate = BABYLON.Tools.Now;
  12095. // Backgrounds
  12096. if (this.layers.length) {
  12097. engine.setDepthBuffer(false);
  12098. var layerIndex;
  12099. var layer;
  12100. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12101. layer = this.layers[layerIndex];
  12102. if (layer.isBackground) {
  12103. layer.render();
  12104. }
  12105. }
  12106. engine.setDepthBuffer(true);
  12107. }
  12108. // Render
  12109. BABYLON.Tools.StartPerformanceCounter("Main render");
  12110. this._renderingManager.render(null, null, true, true);
  12111. BABYLON.Tools.EndPerformanceCounter("Main render");
  12112. // Bounding boxes
  12113. this._boundingBoxRenderer.render();
  12114. // Lens flares
  12115. if (this.lensFlaresEnabled) {
  12116. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12117. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12118. this.lensFlareSystems[lensFlareSystemIndex].render();
  12119. }
  12120. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12121. }
  12122. // Foregrounds
  12123. if (this.layers.length) {
  12124. engine.setDepthBuffer(false);
  12125. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12126. layer = this.layers[layerIndex];
  12127. if (!layer.isBackground) {
  12128. layer.render();
  12129. }
  12130. }
  12131. engine.setDepthBuffer(true);
  12132. }
  12133. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12134. // Finalize frame
  12135. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12136. // Update camera
  12137. this.activeCamera._updateFromScene();
  12138. // Reset some special arrays
  12139. this._renderTargets.reset();
  12140. if (this.afterCameraRender) {
  12141. this.afterCameraRender(this.activeCamera);
  12142. }
  12143. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12144. };
  12145. Scene.prototype._processSubCameras = function (camera) {
  12146. if (camera.subCameras.length === 0) {
  12147. this._renderForCamera(camera);
  12148. return;
  12149. }
  12150. // Sub-cameras
  12151. for (var index = 0; index < camera.subCameras.length; index++) {
  12152. this._renderForCamera(camera.subCameras[index]);
  12153. }
  12154. this.activeCamera = camera;
  12155. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12156. // Update camera
  12157. this.activeCamera._updateFromScene();
  12158. };
  12159. Scene.prototype._checkIntersections = function () {
  12160. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12161. var sourceMesh = this._meshesForIntersections.data[index];
  12162. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12163. var action = sourceMesh.actionManager.actions[actionIndex];
  12164. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12165. var parameters = action.getTriggerParameter();
  12166. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12167. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12168. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12169. if (areIntersecting && currentIntersectionInProgress === -1) {
  12170. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12171. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12172. sourceMesh._intersectionsInProgress.push(otherMesh);
  12173. }
  12174. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12175. sourceMesh._intersectionsInProgress.push(otherMesh);
  12176. }
  12177. }
  12178. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12179. //They intersected, and now they don't.
  12180. //is this trigger an exit trigger? execute an event.
  12181. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12182. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12183. }
  12184. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12185. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12186. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12187. }
  12188. }
  12189. }
  12190. }
  12191. }
  12192. };
  12193. Scene.prototype.render = function () {
  12194. var startDate = BABYLON.Tools.Now;
  12195. this._particlesDuration = 0;
  12196. this._spritesDuration = 0;
  12197. this._activeParticles = 0;
  12198. this._renderDuration = 0;
  12199. this._renderTargetsDuration = 0;
  12200. this._evaluateActiveMeshesDuration = 0;
  12201. this._totalVertices = 0;
  12202. this._activeIndices = 0;
  12203. this._activeBones = 0;
  12204. this.getEngine().resetDrawCalls();
  12205. this._meshesForIntersections.reset();
  12206. this.resetCachedMaterial();
  12207. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12208. // Actions
  12209. if (this.actionManager) {
  12210. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12211. }
  12212. //Simplification Queue
  12213. if (!this.simplificationQueue.running) {
  12214. this.simplificationQueue.executeNext();
  12215. }
  12216. // Before render
  12217. if (this.beforeRender) {
  12218. this.beforeRender();
  12219. }
  12220. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12221. this._onBeforeRenderCallbacks[callbackIndex]();
  12222. }
  12223. // Animations
  12224. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12225. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12226. this._animate();
  12227. // Physics
  12228. if (this._physicsEngine) {
  12229. BABYLON.Tools.StartPerformanceCounter("Physics");
  12230. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12231. BABYLON.Tools.EndPerformanceCounter("Physics");
  12232. }
  12233. // Customs render targets
  12234. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12235. var engine = this.getEngine();
  12236. var currentActiveCamera = this.activeCamera;
  12237. if (this.renderTargetsEnabled) {
  12238. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12239. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12240. var renderTarget = this.customRenderTargets[customIndex];
  12241. if (renderTarget._shouldRender()) {
  12242. this._renderId++;
  12243. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12244. if (!this.activeCamera)
  12245. throw new Error("Active camera not set");
  12246. // Viewport
  12247. engine.setViewport(this.activeCamera.viewport);
  12248. // Camera
  12249. this.updateTransformMatrix();
  12250. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12251. }
  12252. }
  12253. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12254. this._renderId++;
  12255. }
  12256. if (this.customRenderTargets.length > 0) {
  12257. engine.restoreDefaultFramebuffer();
  12258. }
  12259. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12260. this.activeCamera = currentActiveCamera;
  12261. // Procedural textures
  12262. if (this.proceduralTexturesEnabled) {
  12263. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12264. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12265. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12266. if (proceduralTexture._shouldRender()) {
  12267. proceduralTexture.render();
  12268. }
  12269. }
  12270. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12271. }
  12272. // Clear
  12273. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12274. // Shadows
  12275. if (this.shadowsEnabled) {
  12276. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12277. var light = this.lights[lightIndex];
  12278. var shadowGenerator = light.getShadowGenerator();
  12279. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12280. this._renderTargets.push(shadowGenerator.getShadowMap());
  12281. }
  12282. }
  12283. }
  12284. // Depth renderer
  12285. if (this._depthRenderer) {
  12286. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12287. }
  12288. // RenderPipeline
  12289. this.postProcessRenderPipelineManager.update();
  12290. // Multi-cameras?
  12291. if (this.activeCameras.length > 0) {
  12292. var currentRenderId = this._renderId;
  12293. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12294. this._renderId = currentRenderId;
  12295. this._processSubCameras(this.activeCameras[cameraIndex]);
  12296. }
  12297. }
  12298. else {
  12299. if (!this.activeCamera) {
  12300. throw new Error("No camera defined");
  12301. }
  12302. this._processSubCameras(this.activeCamera);
  12303. }
  12304. // Intersection checks
  12305. this._checkIntersections();
  12306. // Update the audio listener attached to the camera
  12307. this._updateAudioParameters();
  12308. // After render
  12309. if (this.afterRender) {
  12310. this.afterRender();
  12311. }
  12312. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12313. this._onAfterRenderCallbacks[callbackIndex]();
  12314. }
  12315. // Cleaning
  12316. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12317. this._toBeDisposed.data[index].dispose();
  12318. this._toBeDisposed[index] = null;
  12319. }
  12320. this._toBeDisposed.reset();
  12321. if (this.dumpNextRenderTargets) {
  12322. this.dumpNextRenderTargets = false;
  12323. }
  12324. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12325. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12326. };
  12327. Scene.prototype._updateAudioParameters = function () {
  12328. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  12329. return;
  12330. }
  12331. var listeningCamera;
  12332. var audioEngine = BABYLON.Engine.audioEngine;
  12333. if (this.activeCameras.length > 0) {
  12334. listeningCamera = this.activeCameras[0];
  12335. }
  12336. else {
  12337. listeningCamera = this.activeCamera;
  12338. }
  12339. if (listeningCamera && audioEngine.canUseWebAudio) {
  12340. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12341. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12342. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12343. cameraDirection.normalize();
  12344. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12345. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12346. var sound = this.mainSoundTrack.soundCollection[i];
  12347. if (sound.useCustomAttenuation) {
  12348. sound.updateDistanceFromListener();
  12349. }
  12350. }
  12351. for (i = 0; i < this.soundTracks.length; i++) {
  12352. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12353. sound = this.soundTracks[i].soundCollection[j];
  12354. if (sound.useCustomAttenuation) {
  12355. sound.updateDistanceFromListener();
  12356. }
  12357. }
  12358. }
  12359. }
  12360. };
  12361. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12362. // Audio
  12363. get: function () {
  12364. return this._audioEnabled;
  12365. },
  12366. set: function (value) {
  12367. this._audioEnabled = value;
  12368. if (this._audioEnabled) {
  12369. this._enableAudio();
  12370. }
  12371. else {
  12372. this._disableAudio();
  12373. }
  12374. },
  12375. enumerable: true,
  12376. configurable: true
  12377. });
  12378. Scene.prototype._disableAudio = function () {
  12379. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12380. this.mainSoundTrack.soundCollection[i].pause();
  12381. }
  12382. for (i = 0; i < this.soundTracks.length; i++) {
  12383. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12384. this.soundTracks[i].soundCollection[j].pause();
  12385. }
  12386. }
  12387. };
  12388. Scene.prototype._enableAudio = function () {
  12389. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12390. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  12391. this.mainSoundTrack.soundCollection[i].play();
  12392. }
  12393. }
  12394. for (i = 0; i < this.soundTracks.length; i++) {
  12395. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12396. if (this.soundTracks[i].soundCollection[j].isPaused) {
  12397. this.soundTracks[i].soundCollection[j].play();
  12398. }
  12399. }
  12400. }
  12401. };
  12402. Object.defineProperty(Scene.prototype, "headphone", {
  12403. get: function () {
  12404. return this._headphone;
  12405. },
  12406. set: function (value) {
  12407. this._headphone = value;
  12408. if (this._headphone) {
  12409. this._switchAudioModeForHeadphones();
  12410. }
  12411. else {
  12412. this._switchAudioModeForNormalSpeakers();
  12413. }
  12414. },
  12415. enumerable: true,
  12416. configurable: true
  12417. });
  12418. Scene.prototype._switchAudioModeForHeadphones = function () {
  12419. this.mainSoundTrack.switchPanningModelToHRTF();
  12420. for (var i = 0; i < this.soundTracks.length; i++) {
  12421. this.soundTracks[i].switchPanningModelToHRTF();
  12422. }
  12423. };
  12424. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  12425. this.mainSoundTrack.switchPanningModelToEqualPower();
  12426. for (var i = 0; i < this.soundTracks.length; i++) {
  12427. this.soundTracks[i].switchPanningModelToEqualPower();
  12428. }
  12429. };
  12430. Scene.prototype.enableDepthRenderer = function () {
  12431. if (this._depthRenderer) {
  12432. return this._depthRenderer;
  12433. }
  12434. this._depthRenderer = new BABYLON.DepthRenderer(this);
  12435. return this._depthRenderer;
  12436. };
  12437. Scene.prototype.disableDepthRenderer = function () {
  12438. if (!this._depthRenderer) {
  12439. return;
  12440. }
  12441. this._depthRenderer.dispose();
  12442. this._depthRenderer = null;
  12443. };
  12444. Scene.prototype.dispose = function () {
  12445. this.beforeRender = null;
  12446. this.afterRender = null;
  12447. this.skeletons = [];
  12448. this._boundingBoxRenderer.dispose();
  12449. if (this._depthRenderer) {
  12450. this._depthRenderer.dispose();
  12451. }
  12452. // Debug layer
  12453. this.debugLayer.hide();
  12454. // Events
  12455. if (this.onDispose) {
  12456. this.onDispose();
  12457. }
  12458. this._onBeforeRenderCallbacks = [];
  12459. this._onAfterRenderCallbacks = [];
  12460. this.detachControl();
  12461. // Release sounds & sounds tracks
  12462. this.disposeSounds();
  12463. // Detach cameras
  12464. var canvas = this._engine.getRenderingCanvas();
  12465. var index;
  12466. for (index = 0; index < this.cameras.length; index++) {
  12467. this.cameras[index].detachControl(canvas);
  12468. }
  12469. // Release lights
  12470. while (this.lights.length) {
  12471. this.lights[0].dispose();
  12472. }
  12473. // Release meshes
  12474. while (this.meshes.length) {
  12475. this.meshes[0].dispose(true);
  12476. }
  12477. // Release cameras
  12478. while (this.cameras.length) {
  12479. this.cameras[0].dispose();
  12480. }
  12481. // Release materials
  12482. while (this.materials.length) {
  12483. this.materials[0].dispose();
  12484. }
  12485. // Release particles
  12486. while (this.particleSystems.length) {
  12487. this.particleSystems[0].dispose();
  12488. }
  12489. // Release sprites
  12490. while (this.spriteManagers.length) {
  12491. this.spriteManagers[0].dispose();
  12492. }
  12493. // Release layers
  12494. while (this.layers.length) {
  12495. this.layers[0].dispose();
  12496. }
  12497. // Release textures
  12498. while (this.textures.length) {
  12499. this.textures[0].dispose();
  12500. }
  12501. // Post-processes
  12502. this.postProcessManager.dispose();
  12503. // Physics
  12504. if (this._physicsEngine) {
  12505. this.disablePhysicsEngine();
  12506. }
  12507. // Remove from engine
  12508. index = this._engine.scenes.indexOf(this);
  12509. if (index > -1) {
  12510. this._engine.scenes.splice(index, 1);
  12511. }
  12512. this._engine.wipeCaches();
  12513. };
  12514. // Release sounds & sounds tracks
  12515. Scene.prototype.disposeSounds = function () {
  12516. this.mainSoundTrack.dispose();
  12517. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  12518. this.soundTracks[scIndex].dispose();
  12519. }
  12520. };
  12521. // Octrees
  12522. Scene.prototype.getWorldExtends = function () {
  12523. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12524. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  12525. for (var index = 0; index < this.meshes.length; index++) {
  12526. var mesh = this.meshes[index];
  12527. mesh.computeWorldMatrix(true);
  12528. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  12529. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  12530. BABYLON.Tools.CheckExtends(minBox, min, max);
  12531. BABYLON.Tools.CheckExtends(maxBox, min, max);
  12532. }
  12533. return {
  12534. min: min,
  12535. max: max
  12536. };
  12537. };
  12538. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  12539. if (maxCapacity === void 0) { maxCapacity = 64; }
  12540. if (maxDepth === void 0) { maxDepth = 2; }
  12541. if (!this._selectionOctree) {
  12542. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  12543. }
  12544. var worldExtends = this.getWorldExtends();
  12545. // Update octree
  12546. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  12547. return this._selectionOctree;
  12548. };
  12549. // Picking
  12550. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  12551. var engine = this._engine;
  12552. if (!camera) {
  12553. if (!this.activeCamera)
  12554. throw new Error("Active camera not set");
  12555. camera = this.activeCamera;
  12556. }
  12557. var cameraViewport = camera.viewport;
  12558. var viewport = cameraViewport.toGlobal(engine);
  12559. // Moving coordinates to local viewport world
  12560. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  12561. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  12562. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12563. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12564. };
  12565. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  12566. var pickingInfo = null;
  12567. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  12568. var mesh = this.meshes[meshIndex];
  12569. if (predicate) {
  12570. if (!predicate(mesh)) {
  12571. continue;
  12572. }
  12573. }
  12574. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  12575. continue;
  12576. }
  12577. var world = mesh.getWorldMatrix();
  12578. var ray = rayFunction(world);
  12579. var result = mesh.intersects(ray, fastCheck);
  12580. if (!result || !result.hit)
  12581. continue;
  12582. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  12583. continue;
  12584. pickingInfo = result;
  12585. if (fastCheck) {
  12586. break;
  12587. }
  12588. }
  12589. return pickingInfo || new BABYLON.PickingInfo();
  12590. };
  12591. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  12592. var _this = this;
  12593. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  12594. /// <param name="x">X position on screen</param>
  12595. /// <param name="y">Y position on screen</param>
  12596. /// <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>
  12597. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  12598. /// <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>
  12599. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  12600. };
  12601. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  12602. var _this = this;
  12603. return this._internalPick(function (world) {
  12604. if (!_this._pickWithRayInverseMatrix) {
  12605. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  12606. }
  12607. world.invertToRef(_this._pickWithRayInverseMatrix);
  12608. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  12609. }, predicate, fastCheck);
  12610. };
  12611. Scene.prototype.setPointerOverMesh = function (mesh) {
  12612. if (this._pointerOverMesh === mesh) {
  12613. return;
  12614. }
  12615. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12616. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12617. }
  12618. this._pointerOverMesh = mesh;
  12619. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12620. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12621. }
  12622. };
  12623. Scene.prototype.getPointerOverMesh = function () {
  12624. return this._pointerOverMesh;
  12625. };
  12626. // Physics
  12627. Scene.prototype.getPhysicsEngine = function () {
  12628. return this._physicsEngine;
  12629. };
  12630. Scene.prototype.enablePhysics = function (gravity, plugin) {
  12631. if (this._physicsEngine) {
  12632. return true;
  12633. }
  12634. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  12635. if (!this._physicsEngine.isSupported()) {
  12636. this._physicsEngine = null;
  12637. return false;
  12638. }
  12639. this._physicsEngine._initialize(gravity);
  12640. return true;
  12641. };
  12642. Scene.prototype.disablePhysicsEngine = function () {
  12643. if (!this._physicsEngine) {
  12644. return;
  12645. }
  12646. this._physicsEngine.dispose();
  12647. this._physicsEngine = undefined;
  12648. };
  12649. Scene.prototype.isPhysicsEnabled = function () {
  12650. return this._physicsEngine !== undefined;
  12651. };
  12652. Scene.prototype.setGravity = function (gravity) {
  12653. if (!this._physicsEngine) {
  12654. return;
  12655. }
  12656. this._physicsEngine._setGravity(gravity);
  12657. };
  12658. Scene.prototype.createCompoundImpostor = function (parts, options) {
  12659. if (parts.parts) {
  12660. options = parts;
  12661. parts = parts.parts;
  12662. }
  12663. if (!this._physicsEngine) {
  12664. return null;
  12665. }
  12666. for (var index = 0; index < parts.length; index++) {
  12667. var mesh = parts[index].mesh;
  12668. mesh._physicImpostor = parts[index].impostor;
  12669. mesh._physicsMass = options.mass / parts.length;
  12670. mesh._physicsFriction = options.friction;
  12671. mesh._physicRestitution = options.restitution;
  12672. }
  12673. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  12674. };
  12675. Scene.prototype.deleteCompoundImpostor = function (compound) {
  12676. for (var index = 0; index < compound.parts.length; index++) {
  12677. var mesh = compound.parts[index].mesh;
  12678. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  12679. this._physicsEngine._unregisterMesh(mesh);
  12680. }
  12681. };
  12682. // Misc.
  12683. Scene.prototype.createDefaultCameraOrLight = function () {
  12684. // Light
  12685. if (this.lights.length === 0) {
  12686. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  12687. }
  12688. // Camera
  12689. if (!this.activeCamera) {
  12690. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  12691. // Compute position
  12692. var worldExtends = this.getWorldExtends();
  12693. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  12694. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  12695. camera.setTarget(worldCenter);
  12696. this.activeCamera = camera;
  12697. }
  12698. };
  12699. // Tags
  12700. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  12701. if (tagsQuery === undefined) {
  12702. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  12703. return list;
  12704. }
  12705. var listByTags = [];
  12706. forEach = forEach || (function (item) { return; });
  12707. for (var i in list) {
  12708. var item = list[i];
  12709. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  12710. listByTags.push(item);
  12711. forEach(item);
  12712. }
  12713. }
  12714. return listByTags;
  12715. };
  12716. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  12717. return this._getByTags(this.meshes, tagsQuery, forEach);
  12718. };
  12719. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  12720. return this._getByTags(this.cameras, tagsQuery, forEach);
  12721. };
  12722. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  12723. return this._getByTags(this.lights, tagsQuery, forEach);
  12724. };
  12725. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  12726. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  12727. };
  12728. // Statics
  12729. Scene._FOGMODE_NONE = 0;
  12730. Scene._FOGMODE_EXP = 1;
  12731. Scene._FOGMODE_EXP2 = 2;
  12732. Scene._FOGMODE_LINEAR = 3;
  12733. Scene.MinDeltaTime = 1.0;
  12734. Scene.MaxDeltaTime = 1000.0;
  12735. return Scene;
  12736. })();
  12737. BABYLON.Scene = Scene;
  12738. })(BABYLON || (BABYLON = {}));
  12739. //# sourceMappingURL=babylon.scene.js.map
  12740. var BABYLON;
  12741. (function (BABYLON) {
  12742. var VertexBuffer = (function () {
  12743. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  12744. if (engine instanceof BABYLON.Mesh) {
  12745. this._engine = engine.getScene().getEngine();
  12746. }
  12747. else {
  12748. this._engine = engine;
  12749. }
  12750. this._updatable = updatable;
  12751. this._data = data;
  12752. if (!postponeInternalCreation) {
  12753. this.create();
  12754. }
  12755. this._kind = kind;
  12756. if (stride) {
  12757. this._strideSize = stride;
  12758. return;
  12759. }
  12760. // Deduce stride from kind
  12761. switch (kind) {
  12762. case VertexBuffer.PositionKind:
  12763. this._strideSize = 3;
  12764. break;
  12765. case VertexBuffer.NormalKind:
  12766. this._strideSize = 3;
  12767. break;
  12768. case VertexBuffer.UVKind:
  12769. this._strideSize = 2;
  12770. break;
  12771. case VertexBuffer.UV2Kind:
  12772. this._strideSize = 2;
  12773. break;
  12774. case VertexBuffer.ColorKind:
  12775. this._strideSize = 4;
  12776. break;
  12777. case VertexBuffer.MatricesIndicesKind:
  12778. this._strideSize = 4;
  12779. break;
  12780. case VertexBuffer.MatricesWeightsKind:
  12781. this._strideSize = 4;
  12782. break;
  12783. }
  12784. }
  12785. // Properties
  12786. VertexBuffer.prototype.isUpdatable = function () {
  12787. return this._updatable;
  12788. };
  12789. VertexBuffer.prototype.getData = function () {
  12790. return this._data;
  12791. };
  12792. VertexBuffer.prototype.getBuffer = function () {
  12793. return this._buffer;
  12794. };
  12795. VertexBuffer.prototype.getStrideSize = function () {
  12796. return this._strideSize;
  12797. };
  12798. // Methods
  12799. VertexBuffer.prototype.create = function (data) {
  12800. if (!data && this._buffer) {
  12801. return; // nothing to do
  12802. }
  12803. data = data || this._data;
  12804. if (!this._buffer) {
  12805. if (this._updatable) {
  12806. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  12807. }
  12808. else {
  12809. this._buffer = this._engine.createVertexBuffer(data);
  12810. }
  12811. }
  12812. if (this._updatable) {
  12813. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  12814. this._data = data;
  12815. }
  12816. };
  12817. VertexBuffer.prototype.update = function (data) {
  12818. this.create(data);
  12819. };
  12820. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  12821. if (!this._buffer) {
  12822. return;
  12823. }
  12824. if (this._updatable) {
  12825. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  12826. this._data = null;
  12827. }
  12828. };
  12829. VertexBuffer.prototype.dispose = function () {
  12830. if (!this._buffer) {
  12831. return;
  12832. }
  12833. if (this._engine._releaseBuffer(this._buffer)) {
  12834. this._buffer = null;
  12835. }
  12836. };
  12837. Object.defineProperty(VertexBuffer, "PositionKind", {
  12838. get: function () {
  12839. return VertexBuffer._PositionKind;
  12840. },
  12841. enumerable: true,
  12842. configurable: true
  12843. });
  12844. Object.defineProperty(VertexBuffer, "NormalKind", {
  12845. get: function () {
  12846. return VertexBuffer._NormalKind;
  12847. },
  12848. enumerable: true,
  12849. configurable: true
  12850. });
  12851. Object.defineProperty(VertexBuffer, "UVKind", {
  12852. get: function () {
  12853. return VertexBuffer._UVKind;
  12854. },
  12855. enumerable: true,
  12856. configurable: true
  12857. });
  12858. Object.defineProperty(VertexBuffer, "UV2Kind", {
  12859. get: function () {
  12860. return VertexBuffer._UV2Kind;
  12861. },
  12862. enumerable: true,
  12863. configurable: true
  12864. });
  12865. Object.defineProperty(VertexBuffer, "ColorKind", {
  12866. get: function () {
  12867. return VertexBuffer._ColorKind;
  12868. },
  12869. enumerable: true,
  12870. configurable: true
  12871. });
  12872. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  12873. get: function () {
  12874. return VertexBuffer._MatricesIndicesKind;
  12875. },
  12876. enumerable: true,
  12877. configurable: true
  12878. });
  12879. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  12880. get: function () {
  12881. return VertexBuffer._MatricesWeightsKind;
  12882. },
  12883. enumerable: true,
  12884. configurable: true
  12885. });
  12886. // Enums
  12887. VertexBuffer._PositionKind = "position";
  12888. VertexBuffer._NormalKind = "normal";
  12889. VertexBuffer._UVKind = "uv";
  12890. VertexBuffer._UV2Kind = "uv2";
  12891. VertexBuffer._ColorKind = "color";
  12892. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  12893. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  12894. return VertexBuffer;
  12895. })();
  12896. BABYLON.VertexBuffer = VertexBuffer;
  12897. })(BABYLON || (BABYLON = {}));
  12898. //# sourceMappingURL=babylon.vertexBuffer.js.map
  12899. var __extends = this.__extends || function (d, b) {
  12900. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12901. function __() { this.constructor = d; }
  12902. __.prototype = b.prototype;
  12903. d.prototype = new __();
  12904. };
  12905. var BABYLON;
  12906. (function (BABYLON) {
  12907. /**
  12908. * Creates an instance based on a source mesh.
  12909. */
  12910. var InstancedMesh = (function (_super) {
  12911. __extends(InstancedMesh, _super);
  12912. function InstancedMesh(name, source) {
  12913. _super.call(this, name, source.getScene());
  12914. source.instances.push(this);
  12915. this._sourceMesh = source;
  12916. this.position.copyFrom(source.position);
  12917. this.rotation.copyFrom(source.rotation);
  12918. this.scaling.copyFrom(source.scaling);
  12919. if (source.rotationQuaternion) {
  12920. this.rotationQuaternion = source.rotationQuaternion.clone();
  12921. }
  12922. this.infiniteDistance = source.infiniteDistance;
  12923. this.setPivotMatrix(source.getPivotMatrix());
  12924. this.refreshBoundingInfo();
  12925. this._syncSubMeshes();
  12926. }
  12927. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12928. // Methods
  12929. get: function () {
  12930. return this._sourceMesh.receiveShadows;
  12931. },
  12932. enumerable: true,
  12933. configurable: true
  12934. });
  12935. Object.defineProperty(InstancedMesh.prototype, "material", {
  12936. get: function () {
  12937. return this._sourceMesh.material;
  12938. },
  12939. enumerable: true,
  12940. configurable: true
  12941. });
  12942. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12943. get: function () {
  12944. return this._sourceMesh.visibility;
  12945. },
  12946. enumerable: true,
  12947. configurable: true
  12948. });
  12949. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12950. get: function () {
  12951. return this._sourceMesh.skeleton;
  12952. },
  12953. enumerable: true,
  12954. configurable: true
  12955. });
  12956. InstancedMesh.prototype.getTotalVertices = function () {
  12957. return this._sourceMesh.getTotalVertices();
  12958. };
  12959. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12960. get: function () {
  12961. return this._sourceMesh;
  12962. },
  12963. enumerable: true,
  12964. configurable: true
  12965. });
  12966. InstancedMesh.prototype.getVerticesData = function (kind) {
  12967. return this._sourceMesh.getVerticesData(kind);
  12968. };
  12969. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12970. return this._sourceMesh.isVerticesDataPresent(kind);
  12971. };
  12972. InstancedMesh.prototype.getIndices = function () {
  12973. return this._sourceMesh.getIndices();
  12974. };
  12975. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12976. get: function () {
  12977. return this._sourceMesh._positions;
  12978. },
  12979. enumerable: true,
  12980. configurable: true
  12981. });
  12982. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12983. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12984. if (data) {
  12985. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12986. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12987. }
  12988. this._updateBoundingInfo();
  12989. };
  12990. InstancedMesh.prototype._preActivate = function () {
  12991. if (this._currentLOD) {
  12992. this._currentLOD._preActivate();
  12993. }
  12994. };
  12995. InstancedMesh.prototype._activate = function (renderId) {
  12996. if (this._currentLOD) {
  12997. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12998. }
  12999. };
  13000. InstancedMesh.prototype.getLOD = function (camera) {
  13001. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13002. if (this._currentLOD === this.sourceMesh) {
  13003. return this;
  13004. }
  13005. return this._currentLOD;
  13006. };
  13007. InstancedMesh.prototype._syncSubMeshes = function () {
  13008. this.releaseSubMeshes();
  13009. if (this._sourceMesh.subMeshes) {
  13010. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13011. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13012. }
  13013. }
  13014. };
  13015. InstancedMesh.prototype._generatePointsArray = function () {
  13016. return this._sourceMesh._generatePointsArray();
  13017. };
  13018. // Clone
  13019. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13020. var result = this._sourceMesh.createInstance(name);
  13021. // Deep copy
  13022. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13023. // Bounding info
  13024. this.refreshBoundingInfo();
  13025. // Parent
  13026. if (newParent) {
  13027. result.parent = newParent;
  13028. }
  13029. if (!doNotCloneChildren) {
  13030. // Children
  13031. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13032. var mesh = this.getScene().meshes[index];
  13033. if (mesh.parent === this) {
  13034. mesh.clone(mesh.name, result);
  13035. }
  13036. }
  13037. }
  13038. result.computeWorldMatrix(true);
  13039. return result;
  13040. };
  13041. // Dispoe
  13042. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13043. // Remove from mesh
  13044. var index = this._sourceMesh.instances.indexOf(this);
  13045. this._sourceMesh.instances.splice(index, 1);
  13046. _super.prototype.dispose.call(this, doNotRecurse);
  13047. };
  13048. return InstancedMesh;
  13049. })(BABYLON.AbstractMesh);
  13050. BABYLON.InstancedMesh = InstancedMesh;
  13051. })(BABYLON || (BABYLON = {}));
  13052. //# sourceMappingURL=babylon.instancedMesh.js.map
  13053. var __extends = this.__extends || function (d, b) {
  13054. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13055. function __() { this.constructor = d; }
  13056. __.prototype = b.prototype;
  13057. d.prototype = new __();
  13058. };
  13059. var BABYLON;
  13060. (function (BABYLON) {
  13061. var _InstancesBatch = (function () {
  13062. function _InstancesBatch() {
  13063. this.mustReturn = false;
  13064. this.visibleInstances = new Array();
  13065. this.renderSelf = new Array();
  13066. }
  13067. return _InstancesBatch;
  13068. })();
  13069. BABYLON._InstancesBatch = _InstancesBatch;
  13070. var Mesh = (function (_super) {
  13071. __extends(Mesh, _super);
  13072. /**
  13073. * @constructor
  13074. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13075. * @param {Scene} scene - The scene to add this mesh to.
  13076. * @param {Node} parent - The parent of this mesh, if it has one
  13077. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13078. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13079. * When false, achieved by calling a clone(), also passing False.
  13080. * This will make creation of children, recursive.
  13081. */
  13082. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13083. if (parent === void 0) { parent = null; }
  13084. _super.call(this, name, scene);
  13085. // Members
  13086. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13087. this.instances = new Array();
  13088. this._LODLevels = new Array();
  13089. this._onBeforeRenderCallbacks = new Array();
  13090. this._onAfterRenderCallbacks = new Array();
  13091. this._visibleInstances = {};
  13092. this._renderIdForInstances = new Array();
  13093. this._batchCache = new _InstancesBatch();
  13094. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13095. this._sideOrientation = Mesh._DEFAULTSIDE;
  13096. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13097. if (source) {
  13098. // Geometry
  13099. if (source._geometry) {
  13100. source._geometry.applyToMesh(this);
  13101. }
  13102. // Deep copy
  13103. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13104. // Material
  13105. this.material = source.material;
  13106. if (!doNotCloneChildren) {
  13107. // Children
  13108. for (var index = 0; index < scene.meshes.length; index++) {
  13109. var mesh = scene.meshes[index];
  13110. if (mesh.parent === source) {
  13111. // doNotCloneChildren is always going to be False
  13112. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13113. }
  13114. }
  13115. }
  13116. // Particles
  13117. for (index = 0; index < scene.particleSystems.length; index++) {
  13118. var system = scene.particleSystems[index];
  13119. if (system.emitter === source) {
  13120. system.clone(system.name, this);
  13121. }
  13122. }
  13123. this.computeWorldMatrix(true);
  13124. }
  13125. // Parent
  13126. if (parent !== null) {
  13127. this.parent = parent;
  13128. }
  13129. }
  13130. Object.defineProperty(Mesh, "FRONTSIDE", {
  13131. get: function () {
  13132. return Mesh._FRONTSIDE;
  13133. },
  13134. enumerable: true,
  13135. configurable: true
  13136. });
  13137. Object.defineProperty(Mesh, "BACKSIDE", {
  13138. get: function () {
  13139. return Mesh._BACKSIDE;
  13140. },
  13141. enumerable: true,
  13142. configurable: true
  13143. });
  13144. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13145. get: function () {
  13146. return Mesh._DOUBLESIDE;
  13147. },
  13148. enumerable: true,
  13149. configurable: true
  13150. });
  13151. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13152. get: function () {
  13153. return Mesh._DEFAULTSIDE;
  13154. },
  13155. enumerable: true,
  13156. configurable: true
  13157. });
  13158. Object.defineProperty(Mesh, "NO_CAP", {
  13159. get: function () {
  13160. return Mesh._NO_CAP;
  13161. },
  13162. enumerable: true,
  13163. configurable: true
  13164. });
  13165. Object.defineProperty(Mesh, "CAP_START", {
  13166. get: function () {
  13167. return Mesh._CAP_START;
  13168. },
  13169. enumerable: true,
  13170. configurable: true
  13171. });
  13172. Object.defineProperty(Mesh, "CAP_END", {
  13173. get: function () {
  13174. return Mesh._CAP_END;
  13175. },
  13176. enumerable: true,
  13177. configurable: true
  13178. });
  13179. Object.defineProperty(Mesh, "CAP_ALL", {
  13180. get: function () {
  13181. return Mesh._CAP_ALL;
  13182. },
  13183. enumerable: true,
  13184. configurable: true
  13185. });
  13186. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13187. // Methods
  13188. get: function () {
  13189. return this._LODLevels.length > 0;
  13190. },
  13191. enumerable: true,
  13192. configurable: true
  13193. });
  13194. Mesh.prototype._sortLODLevels = function () {
  13195. this._LODLevels.sort(function (a, b) {
  13196. if (a.distance < b.distance) {
  13197. return 1;
  13198. }
  13199. if (a.distance > b.distance) {
  13200. return -1;
  13201. }
  13202. return 0;
  13203. });
  13204. };
  13205. /**
  13206. * Add a mesh as LOD level triggered at the given distance.
  13207. * @param {number} distance - the distance from the center of the object to show this level
  13208. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13209. * @return {BABYLON.Mesh} this mesh (for chaining)
  13210. */
  13211. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13212. if (mesh && mesh._masterMesh) {
  13213. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13214. return this;
  13215. }
  13216. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13217. this._LODLevels.push(level);
  13218. if (mesh) {
  13219. mesh._masterMesh = this;
  13220. }
  13221. this._sortLODLevels();
  13222. return this;
  13223. };
  13224. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13225. for (var index = 0; index < this._LODLevels.length; index++) {
  13226. var level = this._LODLevels[index];
  13227. if (level.distance === distance) {
  13228. return level.mesh;
  13229. }
  13230. }
  13231. return null;
  13232. };
  13233. /**
  13234. * Remove a mesh from the LOD array
  13235. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13236. * @return {BABYLON.Mesh} this mesh (for chaining)
  13237. */
  13238. Mesh.prototype.removeLODLevel = function (mesh) {
  13239. for (var index = 0; index < this._LODLevels.length; index++) {
  13240. if (this._LODLevels[index].mesh === mesh) {
  13241. this._LODLevels.splice(index, 1);
  13242. if (mesh) {
  13243. mesh._masterMesh = null;
  13244. }
  13245. }
  13246. }
  13247. this._sortLODLevels();
  13248. return this;
  13249. };
  13250. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13251. if (!this._LODLevels || this._LODLevels.length === 0) {
  13252. return this;
  13253. }
  13254. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13255. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13256. if (this.onLODLevelSelection) {
  13257. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13258. }
  13259. return this;
  13260. }
  13261. for (var index = 0; index < this._LODLevels.length; index++) {
  13262. var level = this._LODLevels[index];
  13263. if (level.distance < distanceToCamera) {
  13264. if (level.mesh) {
  13265. level.mesh._preActivate();
  13266. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13267. }
  13268. if (this.onLODLevelSelection) {
  13269. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13270. }
  13271. return level.mesh;
  13272. }
  13273. }
  13274. if (this.onLODLevelSelection) {
  13275. this.onLODLevelSelection(distanceToCamera, this, this);
  13276. }
  13277. return this;
  13278. };
  13279. Object.defineProperty(Mesh.prototype, "geometry", {
  13280. get: function () {
  13281. return this._geometry;
  13282. },
  13283. enumerable: true,
  13284. configurable: true
  13285. });
  13286. Mesh.prototype.getTotalVertices = function () {
  13287. if (!this._geometry) {
  13288. return 0;
  13289. }
  13290. return this._geometry.getTotalVertices();
  13291. };
  13292. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  13293. if (!this._geometry) {
  13294. return null;
  13295. }
  13296. return this._geometry.getVerticesData(kind, copyWhenShared);
  13297. };
  13298. Mesh.prototype.getVertexBuffer = function (kind) {
  13299. if (!this._geometry) {
  13300. return undefined;
  13301. }
  13302. return this._geometry.getVertexBuffer(kind);
  13303. };
  13304. Mesh.prototype.isVerticesDataPresent = function (kind) {
  13305. if (!this._geometry) {
  13306. if (this._delayInfo) {
  13307. return this._delayInfo.indexOf(kind) !== -1;
  13308. }
  13309. return false;
  13310. }
  13311. return this._geometry.isVerticesDataPresent(kind);
  13312. };
  13313. Mesh.prototype.getVerticesDataKinds = function () {
  13314. if (!this._geometry) {
  13315. var result = [];
  13316. if (this._delayInfo) {
  13317. for (var kind in this._delayInfo) {
  13318. result.push(kind);
  13319. }
  13320. }
  13321. return result;
  13322. }
  13323. return this._geometry.getVerticesDataKinds();
  13324. };
  13325. Mesh.prototype.getTotalIndices = function () {
  13326. if (!this._geometry) {
  13327. return 0;
  13328. }
  13329. return this._geometry.getTotalIndices();
  13330. };
  13331. Mesh.prototype.getIndices = function (copyWhenShared) {
  13332. if (!this._geometry) {
  13333. return [];
  13334. }
  13335. return this._geometry.getIndices(copyWhenShared);
  13336. };
  13337. Object.defineProperty(Mesh.prototype, "isBlocked", {
  13338. get: function () {
  13339. return this._masterMesh !== null && this._masterMesh !== undefined;
  13340. },
  13341. enumerable: true,
  13342. configurable: true
  13343. });
  13344. Mesh.prototype.isReady = function () {
  13345. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13346. return false;
  13347. }
  13348. return _super.prototype.isReady.call(this);
  13349. };
  13350. Mesh.prototype.isDisposed = function () {
  13351. return this._isDisposed;
  13352. };
  13353. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  13354. get: function () {
  13355. return this._sideOrientation;
  13356. },
  13357. set: function (sideO) {
  13358. this._sideOrientation = sideO;
  13359. },
  13360. enumerable: true,
  13361. configurable: true
  13362. });
  13363. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  13364. get: function () {
  13365. return this._areNormalsFrozen;
  13366. },
  13367. enumerable: true,
  13368. configurable: true
  13369. });
  13370. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13371. Mesh.prototype.freezeNormals = function () {
  13372. this._areNormalsFrozen = true;
  13373. };
  13374. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13375. Mesh.prototype.unfreezeNormals = function () {
  13376. this._areNormalsFrozen = false;
  13377. };
  13378. // Methods
  13379. Mesh.prototype._preActivate = function () {
  13380. var sceneRenderId = this.getScene().getRenderId();
  13381. if (this._preActivateId === sceneRenderId) {
  13382. return;
  13383. }
  13384. this._preActivateId = sceneRenderId;
  13385. this._visibleInstances = null;
  13386. };
  13387. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  13388. if (!this._visibleInstances) {
  13389. this._visibleInstances = {};
  13390. this._visibleInstances.defaultRenderId = renderId;
  13391. this._visibleInstances.selfDefaultRenderId = this._renderId;
  13392. }
  13393. if (!this._visibleInstances[renderId]) {
  13394. this._visibleInstances[renderId] = new Array();
  13395. }
  13396. this._visibleInstances[renderId].push(instance);
  13397. };
  13398. Mesh.prototype.refreshBoundingInfo = function () {
  13399. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13400. if (data) {
  13401. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  13402. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13403. }
  13404. if (this.subMeshes) {
  13405. for (var index = 0; index < this.subMeshes.length; index++) {
  13406. this.subMeshes[index].refreshBoundingInfo();
  13407. }
  13408. }
  13409. this._updateBoundingInfo();
  13410. };
  13411. Mesh.prototype._createGlobalSubMesh = function () {
  13412. var totalVertices = this.getTotalVertices();
  13413. if (!totalVertices || !this.getIndices()) {
  13414. return null;
  13415. }
  13416. this.releaseSubMeshes();
  13417. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  13418. };
  13419. Mesh.prototype.subdivide = function (count) {
  13420. if (count < 1) {
  13421. return;
  13422. }
  13423. var totalIndices = this.getTotalIndices();
  13424. var subdivisionSize = (totalIndices / count) | 0;
  13425. var offset = 0;
  13426. // Ensure that subdivisionSize is a multiple of 3
  13427. while (subdivisionSize % 3 !== 0) {
  13428. subdivisionSize++;
  13429. }
  13430. this.releaseSubMeshes();
  13431. for (var index = 0; index < count; index++) {
  13432. if (offset >= totalIndices) {
  13433. break;
  13434. }
  13435. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  13436. offset += subdivisionSize;
  13437. }
  13438. this.synchronizeInstances();
  13439. };
  13440. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13441. if (kind instanceof Array) {
  13442. var temp = data;
  13443. data = kind;
  13444. kind = temp;
  13445. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  13446. }
  13447. if (!this._geometry) {
  13448. var vertexData = new BABYLON.VertexData();
  13449. vertexData.set(data, kind);
  13450. var scene = this.getScene();
  13451. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  13452. }
  13453. else {
  13454. this._geometry.setVerticesData(kind, data, updatable, stride);
  13455. }
  13456. };
  13457. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13458. if (!this._geometry) {
  13459. return;
  13460. }
  13461. if (!makeItUnique) {
  13462. this._geometry.updateVerticesData(kind, data, updateExtends);
  13463. }
  13464. else {
  13465. this.makeGeometryUnique();
  13466. this.updateVerticesData(kind, data, updateExtends, false);
  13467. }
  13468. };
  13469. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  13470. if (!this._geometry) {
  13471. return;
  13472. }
  13473. if (!makeItUnique) {
  13474. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  13475. }
  13476. else {
  13477. this.makeGeometryUnique();
  13478. this.updateVerticesDataDirectly(kind, data, offset, false);
  13479. }
  13480. };
  13481. // Mesh positions update function :
  13482. // updates the mesh positions according to the positionFunction returned values.
  13483. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  13484. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  13485. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  13486. if (computeNormals === void 0) { computeNormals = true; }
  13487. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13488. positionFunction(positions);
  13489. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  13490. if (computeNormals) {
  13491. var indices = this.getIndices();
  13492. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13493. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  13494. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  13495. }
  13496. };
  13497. Mesh.prototype.makeGeometryUnique = function () {
  13498. if (!this._geometry) {
  13499. return;
  13500. }
  13501. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  13502. geometry.applyToMesh(this);
  13503. };
  13504. Mesh.prototype.setIndices = function (indices, totalVertices) {
  13505. if (!this._geometry) {
  13506. var vertexData = new BABYLON.VertexData();
  13507. vertexData.indices = indices;
  13508. var scene = this.getScene();
  13509. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  13510. }
  13511. else {
  13512. this._geometry.setIndices(indices, totalVertices);
  13513. }
  13514. };
  13515. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  13516. var engine = this.getScene().getEngine();
  13517. // Wireframe
  13518. var indexToBind;
  13519. switch (fillMode) {
  13520. case BABYLON.Material.PointFillMode:
  13521. indexToBind = null;
  13522. break;
  13523. case BABYLON.Material.WireFrameFillMode:
  13524. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  13525. break;
  13526. default:
  13527. case BABYLON.Material.TriangleFillMode:
  13528. indexToBind = this._geometry.getIndexBuffer();
  13529. break;
  13530. }
  13531. // VBOs
  13532. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  13533. };
  13534. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  13535. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13536. return;
  13537. }
  13538. var engine = this.getScene().getEngine();
  13539. // Draw order
  13540. switch (fillMode) {
  13541. case BABYLON.Material.PointFillMode:
  13542. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  13543. break;
  13544. case BABYLON.Material.WireFrameFillMode:
  13545. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  13546. break;
  13547. default:
  13548. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  13549. }
  13550. };
  13551. Mesh.prototype.registerBeforeRender = function (func) {
  13552. this._onBeforeRenderCallbacks.push(func);
  13553. };
  13554. Mesh.prototype.unregisterBeforeRender = function (func) {
  13555. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13556. if (index > -1) {
  13557. this._onBeforeRenderCallbacks.splice(index, 1);
  13558. }
  13559. };
  13560. Mesh.prototype.registerAfterRender = function (func) {
  13561. this._onAfterRenderCallbacks.push(func);
  13562. };
  13563. Mesh.prototype.unregisterAfterRender = function (func) {
  13564. var index = this._onAfterRenderCallbacks.indexOf(func);
  13565. if (index > -1) {
  13566. this._onAfterRenderCallbacks.splice(index, 1);
  13567. }
  13568. };
  13569. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  13570. var scene = this.getScene();
  13571. this._batchCache.mustReturn = false;
  13572. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  13573. this._batchCache.visibleInstances[subMeshId] = null;
  13574. if (this._visibleInstances) {
  13575. var currentRenderId = scene.getRenderId();
  13576. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  13577. var selfRenderId = this._renderId;
  13578. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  13579. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  13580. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  13581. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  13582. }
  13583. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  13584. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  13585. this._batchCache.mustReturn = true;
  13586. return this._batchCache;
  13587. }
  13588. if (currentRenderId !== selfRenderId) {
  13589. this._batchCache.renderSelf[subMeshId] = false;
  13590. }
  13591. }
  13592. this._renderIdForInstances[subMeshId] = currentRenderId;
  13593. }
  13594. return this._batchCache;
  13595. };
  13596. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  13597. var visibleInstances = batch.visibleInstances[subMesh._id];
  13598. var matricesCount = visibleInstances.length + 1;
  13599. var bufferSize = matricesCount * 16 * 4;
  13600. while (this._instancesBufferSize < bufferSize) {
  13601. this._instancesBufferSize *= 2;
  13602. }
  13603. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  13604. if (this._worldMatricesInstancesBuffer) {
  13605. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13606. }
  13607. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  13608. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  13609. }
  13610. var offset = 0;
  13611. var instancesCount = 0;
  13612. var world = this.getWorldMatrix();
  13613. if (batch.renderSelf[subMesh._id]) {
  13614. world.copyToArray(this._worldMatricesInstancesArray, offset);
  13615. offset += 16;
  13616. instancesCount++;
  13617. }
  13618. if (visibleInstances) {
  13619. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  13620. var instance = visibleInstances[instanceIndex];
  13621. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  13622. offset += 16;
  13623. instancesCount++;
  13624. }
  13625. }
  13626. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  13627. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  13628. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  13629. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  13630. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  13631. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  13632. this._draw(subMesh, fillMode, instancesCount);
  13633. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  13634. };
  13635. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  13636. var scene = this.getScene();
  13637. var engine = scene.getEngine();
  13638. if (hardwareInstancedRendering) {
  13639. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  13640. }
  13641. else {
  13642. if (batch.renderSelf[subMesh._id]) {
  13643. // Draw
  13644. if (onBeforeDraw) {
  13645. onBeforeDraw(false, this.getWorldMatrix());
  13646. }
  13647. this._draw(subMesh, fillMode);
  13648. }
  13649. if (batch.visibleInstances[subMesh._id]) {
  13650. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  13651. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  13652. // World
  13653. var world = instance.getWorldMatrix();
  13654. if (onBeforeDraw) {
  13655. onBeforeDraw(true, world);
  13656. }
  13657. // Draw
  13658. this._draw(subMesh, fillMode);
  13659. }
  13660. }
  13661. }
  13662. };
  13663. Mesh.prototype.render = function (subMesh) {
  13664. var scene = this.getScene();
  13665. // Managing instances
  13666. var batch = this._getInstancesRenderList(subMesh._id);
  13667. if (batch.mustReturn) {
  13668. return;
  13669. }
  13670. // Checking geometry state
  13671. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13672. return;
  13673. }
  13674. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13675. this._onBeforeRenderCallbacks[callbackIndex](this);
  13676. }
  13677. var engine = scene.getEngine();
  13678. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  13679. // Material
  13680. var effectiveMaterial = subMesh.getMaterial();
  13681. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  13682. return;
  13683. }
  13684. // Outline - step 1
  13685. var savedDepthWrite = engine.getDepthWrite();
  13686. if (this.renderOutline) {
  13687. engine.setDepthWrite(false);
  13688. scene.getOutlineRenderer().render(subMesh, batch);
  13689. engine.setDepthWrite(savedDepthWrite);
  13690. }
  13691. effectiveMaterial._preBind();
  13692. var effect = effectiveMaterial.getEffect();
  13693. // Bind
  13694. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  13695. this._bind(subMesh, effect, fillMode);
  13696. var world = this.getWorldMatrix();
  13697. effectiveMaterial.bind(world, this);
  13698. // Draw
  13699. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  13700. if (isInstance) {
  13701. effectiveMaterial.bindOnlyWorldMatrix(world);
  13702. }
  13703. });
  13704. // Unbind
  13705. effectiveMaterial.unbind();
  13706. // Outline - step 2
  13707. if (this.renderOutline && savedDepthWrite) {
  13708. engine.setDepthWrite(true);
  13709. engine.setColorWrite(false);
  13710. scene.getOutlineRenderer().render(subMesh, batch);
  13711. engine.setColorWrite(true);
  13712. }
  13713. // Overlay
  13714. if (this.renderOverlay) {
  13715. var currentMode = engine.getAlphaMode();
  13716. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13717. scene.getOutlineRenderer().render(subMesh, batch, true);
  13718. engine.setAlphaMode(currentMode);
  13719. }
  13720. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13721. this._onAfterRenderCallbacks[callbackIndex](this);
  13722. }
  13723. };
  13724. Mesh.prototype.getEmittedParticleSystems = function () {
  13725. var results = new Array();
  13726. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13727. var particleSystem = this.getScene().particleSystems[index];
  13728. if (particleSystem.emitter === this) {
  13729. results.push(particleSystem);
  13730. }
  13731. }
  13732. return results;
  13733. };
  13734. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  13735. var results = new Array();
  13736. var descendants = this.getDescendants();
  13737. descendants.push(this);
  13738. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13739. var particleSystem = this.getScene().particleSystems[index];
  13740. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  13741. results.push(particleSystem);
  13742. }
  13743. }
  13744. return results;
  13745. };
  13746. Mesh.prototype.getChildren = function () {
  13747. var results = [];
  13748. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13749. var mesh = this.getScene().meshes[index];
  13750. if (mesh.parent === this) {
  13751. results.push(mesh);
  13752. }
  13753. }
  13754. return results;
  13755. };
  13756. Mesh.prototype._checkDelayState = function () {
  13757. var _this = this;
  13758. var that = this;
  13759. var scene = this.getScene();
  13760. if (this._geometry) {
  13761. this._geometry.load(scene);
  13762. }
  13763. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13764. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  13765. scene._addPendingData(that);
  13766. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  13767. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  13768. if (data instanceof ArrayBuffer) {
  13769. _this._delayLoadingFunction(data, _this);
  13770. }
  13771. else {
  13772. _this._delayLoadingFunction(JSON.parse(data), _this);
  13773. }
  13774. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13775. scene._removePendingData(_this);
  13776. }, function () { }, scene.database, getBinaryData);
  13777. }
  13778. };
  13779. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  13780. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13781. return false;
  13782. }
  13783. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  13784. return false;
  13785. }
  13786. this._checkDelayState();
  13787. return true;
  13788. };
  13789. Mesh.prototype.setMaterialByID = function (id) {
  13790. var materials = this.getScene().materials;
  13791. for (var index = 0; index < materials.length; index++) {
  13792. if (materials[index].id === id) {
  13793. this.material = materials[index];
  13794. return;
  13795. }
  13796. }
  13797. // Multi
  13798. var multiMaterials = this.getScene().multiMaterials;
  13799. for (index = 0; index < multiMaterials.length; index++) {
  13800. if (multiMaterials[index].id === id) {
  13801. this.material = multiMaterials[index];
  13802. return;
  13803. }
  13804. }
  13805. };
  13806. Mesh.prototype.getAnimatables = function () {
  13807. var results = [];
  13808. if (this.material) {
  13809. results.push(this.material);
  13810. }
  13811. if (this.skeleton) {
  13812. results.push(this.skeleton);
  13813. }
  13814. return results;
  13815. };
  13816. // Geometry
  13817. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  13818. // Position
  13819. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13820. return;
  13821. }
  13822. this._resetPointsArrayCache();
  13823. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13824. var temp = [];
  13825. for (var index = 0; index < data.length; index += 3) {
  13826. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13827. }
  13828. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  13829. // Normals
  13830. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13831. return;
  13832. }
  13833. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13834. temp = [];
  13835. for (index = 0; index < data.length; index += 3) {
  13836. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13837. }
  13838. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  13839. };
  13840. // Cache
  13841. Mesh.prototype._resetPointsArrayCache = function () {
  13842. this._positions = null;
  13843. };
  13844. Mesh.prototype._generatePointsArray = function () {
  13845. if (this._positions)
  13846. return true;
  13847. this._positions = [];
  13848. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13849. if (!data) {
  13850. return false;
  13851. }
  13852. for (var index = 0; index < data.length; index += 3) {
  13853. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  13854. }
  13855. return true;
  13856. };
  13857. // Clone
  13858. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13859. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  13860. };
  13861. // Dispose
  13862. Mesh.prototype.dispose = function (doNotRecurse) {
  13863. if (this._geometry) {
  13864. this._geometry.releaseForMesh(this, true);
  13865. }
  13866. // Instances
  13867. if (this._worldMatricesInstancesBuffer) {
  13868. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13869. this._worldMatricesInstancesBuffer = null;
  13870. }
  13871. while (this.instances.length) {
  13872. this.instances[0].dispose();
  13873. }
  13874. _super.prototype.dispose.call(this, doNotRecurse);
  13875. };
  13876. // Geometric tools
  13877. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  13878. var _this = this;
  13879. var scene = this.getScene();
  13880. var onload = function (img) {
  13881. // Getting height map data
  13882. var canvas = document.createElement("canvas");
  13883. var context = canvas.getContext("2d");
  13884. var heightMapWidth = img.width;
  13885. var heightMapHeight = img.height;
  13886. canvas.width = heightMapWidth;
  13887. canvas.height = heightMapHeight;
  13888. context.drawImage(img, 0, 0);
  13889. // Create VertexData from map data
  13890. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  13891. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  13892. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  13893. //execute success callback, if set
  13894. if (onSuccess) {
  13895. onSuccess(_this);
  13896. }
  13897. };
  13898. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  13899. };
  13900. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  13901. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  13902. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  13903. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13904. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  13905. return;
  13906. }
  13907. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13908. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13909. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13910. var position = BABYLON.Vector3.Zero();
  13911. var normal = BABYLON.Vector3.Zero();
  13912. var uv = BABYLON.Vector2.Zero();
  13913. for (var index = 0; index < positions.length; index += 3) {
  13914. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  13915. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  13916. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  13917. // Compute height
  13918. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  13919. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  13920. var pos = (u + v * heightMapWidth) * 4;
  13921. var r = buffer[pos] / 255.0;
  13922. var g = buffer[pos + 1] / 255.0;
  13923. var b = buffer[pos + 2] / 255.0;
  13924. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  13925. normal.normalize();
  13926. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  13927. position = position.add(normal);
  13928. position.toArray(positions, index);
  13929. }
  13930. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  13931. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  13932. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  13933. };
  13934. Mesh.prototype.convertToFlatShadedMesh = function () {
  13935. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  13936. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  13937. var kinds = this.getVerticesDataKinds();
  13938. var vbs = [];
  13939. var data = [];
  13940. var newdata = [];
  13941. var updatableNormals = false;
  13942. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13943. var kind = kinds[kindIndex];
  13944. var vertexBuffer = this.getVertexBuffer(kind);
  13945. if (kind === BABYLON.VertexBuffer.NormalKind) {
  13946. updatableNormals = vertexBuffer.isUpdatable();
  13947. kinds.splice(kindIndex, 1);
  13948. kindIndex--;
  13949. continue;
  13950. }
  13951. vbs[kind] = vertexBuffer;
  13952. data[kind] = vbs[kind].getData();
  13953. newdata[kind] = [];
  13954. }
  13955. // Save previous submeshes
  13956. var previousSubmeshes = this.subMeshes.slice(0);
  13957. var indices = this.getIndices();
  13958. var totalIndices = this.getTotalIndices();
  13959. // Generating unique vertices per face
  13960. for (var index = 0; index < totalIndices; index++) {
  13961. var vertexIndex = indices[index];
  13962. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13963. kind = kinds[kindIndex];
  13964. var stride = vbs[kind].getStrideSize();
  13965. for (var offset = 0; offset < stride; offset++) {
  13966. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  13967. }
  13968. }
  13969. }
  13970. // Updating faces & normal
  13971. var normals = [];
  13972. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  13973. for (index = 0; index < totalIndices; index += 3) {
  13974. indices[index] = index;
  13975. indices[index + 1] = index + 1;
  13976. indices[index + 2] = index + 2;
  13977. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  13978. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  13979. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  13980. var p1p2 = p1.subtract(p2);
  13981. var p3p2 = p3.subtract(p2);
  13982. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  13983. // Store same normals for every vertex
  13984. for (var localIndex = 0; localIndex < 3; localIndex++) {
  13985. normals.push(normal.x);
  13986. normals.push(normal.y);
  13987. normals.push(normal.z);
  13988. }
  13989. }
  13990. this.setIndices(indices);
  13991. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  13992. // Updating vertex buffers
  13993. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13994. kind = kinds[kindIndex];
  13995. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  13996. }
  13997. // Updating submeshes
  13998. this.releaseSubMeshes();
  13999. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14000. var previousOne = previousSubmeshes[submeshIndex];
  14001. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14002. }
  14003. this.synchronizeInstances();
  14004. };
  14005. // Instances
  14006. Mesh.prototype.createInstance = function (name) {
  14007. return new BABYLON.InstancedMesh(name, this);
  14008. };
  14009. Mesh.prototype.synchronizeInstances = function () {
  14010. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14011. var instance = this.instances[instanceIndex];
  14012. instance._syncSubMeshes();
  14013. }
  14014. };
  14015. /**
  14016. * Simplify the mesh according to the given array of settings.
  14017. * Function will return immediately and will simplify async.
  14018. * @param settings a collection of simplification settings.
  14019. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14020. * @param type the type of simplification to run.
  14021. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14022. */
  14023. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14024. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14025. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14026. this.getScene().simplificationQueue.addTask({
  14027. settings: settings,
  14028. parallelProcessing: parallelProcessing,
  14029. mesh: this,
  14030. simplificationType: simplificationType,
  14031. successCallback: successCallback
  14032. });
  14033. };
  14034. /**
  14035. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14036. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14037. * This should be used together with the simplification to avoid disappearing triangles.
  14038. * @param successCallback an optional success callback to be called after the optimization finished.
  14039. */
  14040. Mesh.prototype.optimizeIndices = function (successCallback) {
  14041. var _this = this;
  14042. var indices = this.getIndices();
  14043. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14044. var vectorPositions = [];
  14045. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14046. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14047. }
  14048. var dupes = [];
  14049. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14050. var realPos = vectorPositions.length - 1 - iteration;
  14051. var testedPosition = vectorPositions[realPos];
  14052. for (var j = 0; j < realPos; ++j) {
  14053. var againstPosition = vectorPositions[j];
  14054. if (testedPosition.equals(againstPosition)) {
  14055. dupes[realPos] = j;
  14056. break;
  14057. }
  14058. }
  14059. }, function () {
  14060. for (var i = 0; i < indices.length; ++i) {
  14061. indices[i] = dupes[indices[i]] || indices[i];
  14062. }
  14063. //indices are now reordered
  14064. var originalSubMeshes = _this.subMeshes.slice(0);
  14065. _this.setIndices(indices);
  14066. _this.subMeshes = originalSubMeshes;
  14067. if (successCallback) {
  14068. successCallback(_this);
  14069. }
  14070. });
  14071. };
  14072. // Statics
  14073. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  14074. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14075. if (ribbonInstance === void 0) { ribbonInstance = null; }
  14076. if (ribbonInstance) {
  14077. // positionFunction : ribbon case
  14078. // only pathArray and sideOrientation parameters are taken into account for positions update
  14079. var positionsOfRibbon = function (pathArray, sideOrientation) {
  14080. var positionFunction = function (positions) {
  14081. var minlg = pathArray[0].length;
  14082. var i = 0;
  14083. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  14084. for (var si = 1; si <= ns; si++) {
  14085. for (var p = 0; p < pathArray.length; p++) {
  14086. var path = pathArray[p];
  14087. var l = path.length;
  14088. minlg = (minlg < l) ? minlg : l;
  14089. var j = 0;
  14090. while (j < minlg) {
  14091. positions[i] = path[j].x;
  14092. positions[i + 1] = path[j].y;
  14093. positions[i + 2] = path[j].z;
  14094. j++;
  14095. i += 3;
  14096. }
  14097. }
  14098. }
  14099. };
  14100. return positionFunction;
  14101. };
  14102. var sideOrientation = ribbonInstance.sideOrientation;
  14103. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  14104. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  14105. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  14106. return ribbonInstance;
  14107. }
  14108. else {
  14109. var ribbon = new Mesh(name, scene);
  14110. ribbon.sideOrientation = sideOrientation;
  14111. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  14112. vertexData.applyToMesh(ribbon, updatable);
  14113. return ribbon;
  14114. }
  14115. };
  14116. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14117. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14118. var disc = new Mesh(name, scene);
  14119. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  14120. vertexData.applyToMesh(disc, updatable);
  14121. return disc;
  14122. };
  14123. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14124. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14125. var box = new Mesh(name, scene);
  14126. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  14127. vertexData.applyToMesh(box, updatable);
  14128. return box;
  14129. };
  14130. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14131. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14132. var sphere = new Mesh(name, scene);
  14133. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  14134. vertexData.applyToMesh(sphere, updatable);
  14135. return sphere;
  14136. };
  14137. // Cylinder and cone (Code inspired by SharpDX.org)
  14138. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14139. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14140. // subdivisions is a new parameter, we need to support old signature
  14141. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  14142. if (scene !== undefined) {
  14143. updatable = scene;
  14144. }
  14145. scene = subdivisions;
  14146. subdivisions = 1;
  14147. }
  14148. var cylinder = new Mesh(name, scene);
  14149. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  14150. vertexData.applyToMesh(cylinder, updatable);
  14151. return cylinder;
  14152. };
  14153. // Torus (Code from SharpDX.org)
  14154. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14155. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14156. var torus = new Mesh(name, scene);
  14157. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  14158. vertexData.applyToMesh(torus, updatable);
  14159. return torus;
  14160. };
  14161. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14162. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14163. var torusKnot = new Mesh(name, scene);
  14164. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  14165. vertexData.applyToMesh(torusKnot, updatable);
  14166. return torusKnot;
  14167. };
  14168. // Lines
  14169. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  14170. if (linesInstance === void 0) { linesInstance = null; }
  14171. if (linesInstance) {
  14172. var positionsOfLines = function (points) {
  14173. var positionFunction = function (positions) {
  14174. var i = 0;
  14175. for (var p = 0; p < points.length; p++) {
  14176. positions[i] = points[p].x;
  14177. positions[i + 1] = points[p].y;
  14178. positions[i + 2] = points[p].z;
  14179. i += 3;
  14180. }
  14181. };
  14182. return positionFunction;
  14183. };
  14184. var positionFunction = positionsOfLines(points);
  14185. linesInstance.updateMeshPositions(positionFunction, false);
  14186. return linesInstance;
  14187. }
  14188. // lines creation
  14189. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  14190. var vertexData = BABYLON.VertexData.CreateLines(points);
  14191. vertexData.applyToMesh(lines, updatable);
  14192. return lines;
  14193. };
  14194. // Extrusion
  14195. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14196. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14197. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14198. scale = scale || 1;
  14199. rotation = rotation || 0;
  14200. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  14201. return extruded;
  14202. };
  14203. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14204. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14205. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14206. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  14207. return extrudedCustom;
  14208. };
  14209. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  14210. // extrusion geometry
  14211. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  14212. var tangents = path3D.getTangents();
  14213. var normals = path3D.getNormals();
  14214. var binormals = path3D.getBinormals();
  14215. var distances = path3D.getDistances();
  14216. var angle = 0;
  14217. var returnScale = function (i, distance) { return scale; };
  14218. var returnRotation = function (i, distance) { return rotation; };
  14219. var rotate = custom ? rotateFunction : returnRotation;
  14220. var scl = custom ? scaleFunction : returnScale;
  14221. var index = 0;
  14222. for (var i = 0; i < curve.length; i++) {
  14223. var shapePath = new Array();
  14224. var angleStep = rotate(i, distances[i]);
  14225. var scaleRatio = scl(i, distances[i]);
  14226. for (var p = 0; p < shape.length; p++) {
  14227. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  14228. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  14229. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  14230. shapePath.push(rotated);
  14231. }
  14232. shapePaths[index] = shapePath;
  14233. angle += angleStep;
  14234. index++;
  14235. }
  14236. // cap
  14237. var capPath = function (shapePath) {
  14238. var pointCap = Array();
  14239. var barycenter = BABYLON.Vector3.Zero();
  14240. var i;
  14241. for (i = 0; i < shapePath.length; i++) {
  14242. barycenter.addInPlace(shapePath[i]);
  14243. }
  14244. barycenter.scaleInPlace(1 / shapePath.length);
  14245. for (i = 0; i < shapePath.length; i++) {
  14246. pointCap.push(barycenter);
  14247. }
  14248. return pointCap;
  14249. };
  14250. switch (cap) {
  14251. case BABYLON.Mesh.NO_CAP:
  14252. break;
  14253. case BABYLON.Mesh.CAP_START:
  14254. shapePaths.unshift(capPath(shapePaths[0]));
  14255. break;
  14256. case BABYLON.Mesh.CAP_END:
  14257. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14258. break;
  14259. case BABYLON.Mesh.CAP_ALL:
  14260. shapePaths.unshift(capPath(shapePaths[0]));
  14261. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14262. break;
  14263. default:
  14264. break;
  14265. }
  14266. return shapePaths;
  14267. };
  14268. if (instance) {
  14269. var path3D = (instance.path3D).update(curve);
  14270. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  14271. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  14272. return instance;
  14273. }
  14274. // extruded shape creation
  14275. var path3D = new BABYLON.Path3D(curve);
  14276. var newShapePaths = new Array();
  14277. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14278. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  14279. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  14280. extrudedGeneric.pathArray = pathArray;
  14281. extrudedGeneric.path3D = path3D;
  14282. extrudedGeneric.cap = cap;
  14283. return extrudedGeneric;
  14284. };
  14285. // Plane & ground
  14286. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14287. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14288. var plane = new Mesh(name, scene);
  14289. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  14290. vertexData.applyToMesh(plane, updatable);
  14291. return plane;
  14292. };
  14293. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14294. var ground = new BABYLON.GroundMesh(name, scene);
  14295. ground._setReady(false);
  14296. ground._subdivisions = subdivisions;
  14297. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  14298. vertexData.applyToMesh(ground, updatable);
  14299. ground._setReady(true);
  14300. return ground;
  14301. };
  14302. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14303. var tiledGround = new Mesh(name, scene);
  14304. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  14305. vertexData.applyToMesh(tiledGround, updatable);
  14306. return tiledGround;
  14307. };
  14308. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  14309. var ground = new BABYLON.GroundMesh(name, scene);
  14310. ground._subdivisions = subdivisions;
  14311. ground._setReady(false);
  14312. var onload = function (img) {
  14313. // Getting height map data
  14314. var canvas = document.createElement("canvas");
  14315. var context = canvas.getContext("2d");
  14316. var heightMapWidth = img.width;
  14317. var heightMapHeight = img.height;
  14318. canvas.width = heightMapWidth;
  14319. canvas.height = heightMapHeight;
  14320. context.drawImage(img, 0, 0);
  14321. // Create VertexData from map data
  14322. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14323. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14324. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  14325. vertexData.applyToMesh(ground, updatable);
  14326. ground._setReady(true);
  14327. //execute ready callback, if set
  14328. if (onReady) {
  14329. onReady(ground);
  14330. }
  14331. };
  14332. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14333. return ground;
  14334. };
  14335. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  14336. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14337. if (tubeInstance === void 0) { tubeInstance = null; }
  14338. // tube geometry
  14339. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  14340. var tangents = path3D.getTangents();
  14341. var normals = path3D.getNormals();
  14342. var distances = path3D.getDistances();
  14343. var pi2 = Math.PI * 2;
  14344. var step = pi2 / tessellation;
  14345. var returnRadius = function (i, distance) { return radius; };
  14346. var radiusFunctionFinal = radiusFunction || returnRadius;
  14347. var circlePath;
  14348. var rad;
  14349. var normal;
  14350. var rotated;
  14351. var rotationMatrix;
  14352. var index = 0;
  14353. for (var i = 0; i < path.length; i++) {
  14354. rad = radiusFunctionFinal(i, distances[i]); // current radius
  14355. circlePath = Array(); // current circle array
  14356. normal = normals[i]; // current normal
  14357. for (var t = 0; t < tessellation; t++) {
  14358. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  14359. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  14360. circlePath.push(rotated);
  14361. }
  14362. circlePath.push(circlePath[0]);
  14363. circlePaths[index] = circlePath;
  14364. index++;
  14365. }
  14366. // cap
  14367. var capPath = function (nbPoints, pathIndex) {
  14368. var pointCap = Array();
  14369. for (var i = 0; i < nbPoints; i++) {
  14370. pointCap.push(path[pathIndex]);
  14371. }
  14372. return pointCap;
  14373. };
  14374. switch (cap) {
  14375. case BABYLON.Mesh.NO_CAP:
  14376. break;
  14377. case BABYLON.Mesh.CAP_START:
  14378. circlePaths.unshift(capPath(tessellation + 1, 0));
  14379. break;
  14380. case BABYLON.Mesh.CAP_END:
  14381. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14382. break;
  14383. case BABYLON.Mesh.CAP_ALL:
  14384. circlePaths.unshift(capPath(tessellation + 1, 0));
  14385. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14386. break;
  14387. default:
  14388. break;
  14389. }
  14390. return circlePaths;
  14391. };
  14392. if (tubeInstance) {
  14393. var path3D = (tubeInstance.path3D).update(path);
  14394. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  14395. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  14396. return tubeInstance;
  14397. }
  14398. // tube creation
  14399. var path3D = new BABYLON.Path3D(path);
  14400. var newPathArray = new Array();
  14401. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14402. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  14403. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  14404. tube.pathArray = pathArray;
  14405. tube.path3D = path3D;
  14406. tube.tessellation = tessellation;
  14407. tube.cap = cap;
  14408. return tube;
  14409. };
  14410. // Decals
  14411. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  14412. if (angle === void 0) { angle = 0; }
  14413. var indices = sourceMesh.getIndices();
  14414. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14415. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14416. // Getting correct rotation
  14417. if (!normal) {
  14418. var target = new BABYLON.Vector3(0, 0, 1);
  14419. var camera = sourceMesh.getScene().activeCamera;
  14420. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  14421. normal = camera.globalPosition.subtract(cameraWorldTarget);
  14422. }
  14423. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  14424. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  14425. var pitch = Math.atan2(normal.y, len);
  14426. // Matrix
  14427. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  14428. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  14429. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  14430. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  14431. var vertexData = new BABYLON.VertexData();
  14432. vertexData.indices = [];
  14433. vertexData.positions = [];
  14434. vertexData.normals = [];
  14435. vertexData.uvs = [];
  14436. var currentVertexDataIndex = 0;
  14437. var extractDecalVector3 = function (indexId) {
  14438. var vertexId = indices[indexId];
  14439. var result = new BABYLON.PositionNormalVertex();
  14440. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  14441. // Send vector to decal local world
  14442. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  14443. // Get normal
  14444. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  14445. return result;
  14446. };
  14447. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  14448. var clip = function (vertices, axis) {
  14449. if (vertices.length === 0) {
  14450. return vertices;
  14451. }
  14452. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  14453. var clipVertices = function (v0, v1) {
  14454. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  14455. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  14456. };
  14457. var result = new Array();
  14458. for (var index = 0; index < vertices.length; index += 3) {
  14459. var v1Out;
  14460. var v2Out;
  14461. var v3Out;
  14462. var total = 0;
  14463. var nV1, nV2, nV3, nV4;
  14464. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  14465. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  14466. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  14467. v1Out = d1 > 0;
  14468. v2Out = d2 > 0;
  14469. v3Out = d3 > 0;
  14470. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  14471. switch (total) {
  14472. case 0:
  14473. result.push(vertices[index]);
  14474. result.push(vertices[index + 1]);
  14475. result.push(vertices[index + 2]);
  14476. break;
  14477. case 1:
  14478. if (v1Out) {
  14479. nV1 = vertices[index + 1];
  14480. nV2 = vertices[index + 2];
  14481. nV3 = clipVertices(vertices[index], nV1);
  14482. nV4 = clipVertices(vertices[index], nV2);
  14483. }
  14484. if (v2Out) {
  14485. nV1 = vertices[index];
  14486. nV2 = vertices[index + 2];
  14487. nV3 = clipVertices(vertices[index + 1], nV1);
  14488. nV4 = clipVertices(vertices[index + 1], nV2);
  14489. result.push(nV3);
  14490. result.push(nV2.clone());
  14491. result.push(nV1.clone());
  14492. result.push(nV2.clone());
  14493. result.push(nV3.clone());
  14494. result.push(nV4);
  14495. break;
  14496. }
  14497. if (v3Out) {
  14498. nV1 = vertices[index];
  14499. nV2 = vertices[index + 1];
  14500. nV3 = clipVertices(vertices[index + 2], nV1);
  14501. nV4 = clipVertices(vertices[index + 2], nV2);
  14502. }
  14503. result.push(nV1.clone());
  14504. result.push(nV2.clone());
  14505. result.push(nV3);
  14506. result.push(nV4);
  14507. result.push(nV3.clone());
  14508. result.push(nV2.clone());
  14509. break;
  14510. case 2:
  14511. if (!v1Out) {
  14512. nV1 = vertices[index].clone();
  14513. nV2 = clipVertices(nV1, vertices[index + 1]);
  14514. nV3 = clipVertices(nV1, vertices[index + 2]);
  14515. result.push(nV1);
  14516. result.push(nV2);
  14517. result.push(nV3);
  14518. }
  14519. if (!v2Out) {
  14520. nV1 = vertices[index + 1].clone();
  14521. nV2 = clipVertices(nV1, vertices[index + 2]);
  14522. nV3 = clipVertices(nV1, vertices[index]);
  14523. result.push(nV1);
  14524. result.push(nV2);
  14525. result.push(nV3);
  14526. }
  14527. if (!v3Out) {
  14528. nV1 = vertices[index + 2].clone();
  14529. nV2 = clipVertices(nV1, vertices[index]);
  14530. nV3 = clipVertices(nV1, vertices[index + 1]);
  14531. result.push(nV1);
  14532. result.push(nV2);
  14533. result.push(nV3);
  14534. }
  14535. break;
  14536. case 3:
  14537. break;
  14538. }
  14539. }
  14540. return result;
  14541. };
  14542. for (var index = 0; index < indices.length; index += 3) {
  14543. var faceVertices = new Array();
  14544. faceVertices.push(extractDecalVector3(index));
  14545. faceVertices.push(extractDecalVector3(index + 1));
  14546. faceVertices.push(extractDecalVector3(index + 2));
  14547. // Clip
  14548. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  14549. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  14550. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  14551. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  14552. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  14553. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  14554. if (faceVertices.length === 0) {
  14555. continue;
  14556. }
  14557. // Add UVs and get back to world
  14558. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  14559. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  14560. var vertex = faceVertices[vIndex];
  14561. vertexData.indices.push(currentVertexDataIndex);
  14562. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  14563. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  14564. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  14565. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  14566. currentVertexDataIndex++;
  14567. }
  14568. }
  14569. // Return mesh
  14570. var decal = new Mesh(name, sourceMesh.getScene());
  14571. vertexData.applyToMesh(decal);
  14572. decal.position = position.clone();
  14573. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  14574. return decal;
  14575. };
  14576. // Tools
  14577. Mesh.MinMax = function (meshes) {
  14578. var minVector = null;
  14579. var maxVector = null;
  14580. for (var i in meshes) {
  14581. var mesh = meshes[i];
  14582. var boundingBox = mesh.getBoundingInfo().boundingBox;
  14583. if (!minVector) {
  14584. minVector = boundingBox.minimumWorld;
  14585. maxVector = boundingBox.maximumWorld;
  14586. continue;
  14587. }
  14588. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  14589. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  14590. }
  14591. return {
  14592. min: minVector,
  14593. max: maxVector
  14594. };
  14595. };
  14596. Mesh.Center = function (meshesOrMinMaxVector) {
  14597. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  14598. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  14599. };
  14600. /**
  14601. * Merge the array of meshes into a single mesh for performance reasons.
  14602. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  14603. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  14604. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  14605. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  14606. */
  14607. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  14608. if (disposeSource === void 0) { disposeSource = true; }
  14609. if (!allow32BitsIndices) {
  14610. var totalVertices = 0;
  14611. // Counting vertices
  14612. for (var index = 0; index < meshes.length; index++) {
  14613. if (meshes[index]) {
  14614. totalVertices += meshes[index].getTotalVertices();
  14615. if (totalVertices > 65536) {
  14616. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  14617. return null;
  14618. }
  14619. }
  14620. }
  14621. }
  14622. // Merge
  14623. var vertexData;
  14624. var otherVertexData;
  14625. var source;
  14626. for (index = 0; index < meshes.length; index++) {
  14627. if (meshes[index]) {
  14628. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  14629. otherVertexData.transform(meshes[index].getWorldMatrix());
  14630. if (vertexData) {
  14631. vertexData.merge(otherVertexData);
  14632. }
  14633. else {
  14634. vertexData = otherVertexData;
  14635. source = meshes[index];
  14636. }
  14637. }
  14638. }
  14639. if (!meshSubclass) {
  14640. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  14641. }
  14642. vertexData.applyToMesh(meshSubclass);
  14643. // Setting properties
  14644. meshSubclass.material = source.material;
  14645. meshSubclass.checkCollisions = source.checkCollisions;
  14646. // Cleaning
  14647. if (disposeSource) {
  14648. for (index = 0; index < meshes.length; index++) {
  14649. if (meshes[index]) {
  14650. meshes[index].dispose();
  14651. }
  14652. }
  14653. }
  14654. return meshSubclass;
  14655. };
  14656. // Consts
  14657. Mesh._FRONTSIDE = 0;
  14658. Mesh._BACKSIDE = 1;
  14659. Mesh._DOUBLESIDE = 2;
  14660. Mesh._DEFAULTSIDE = 0;
  14661. Mesh._NO_CAP = 0;
  14662. Mesh._CAP_START = 1;
  14663. Mesh._CAP_END = 2;
  14664. Mesh._CAP_ALL = 3;
  14665. return Mesh;
  14666. })(BABYLON.AbstractMesh);
  14667. BABYLON.Mesh = Mesh;
  14668. })(BABYLON || (BABYLON = {}));
  14669. //# sourceMappingURL=babylon.mesh.js.map
  14670. var BABYLON;
  14671. (function (BABYLON) {
  14672. var SubMesh = (function () {
  14673. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  14674. if (createBoundingBox === void 0) { createBoundingBox = true; }
  14675. this.materialIndex = materialIndex;
  14676. this.verticesStart = verticesStart;
  14677. this.verticesCount = verticesCount;
  14678. this.indexStart = indexStart;
  14679. this.indexCount = indexCount;
  14680. this._renderId = 0;
  14681. this._mesh = mesh;
  14682. this._renderingMesh = renderingMesh || mesh;
  14683. mesh.subMeshes.push(this);
  14684. this._trianglePlanes = [];
  14685. this._id = mesh.subMeshes.length - 1;
  14686. if (createBoundingBox) {
  14687. this.refreshBoundingInfo();
  14688. mesh.computeWorldMatrix(true);
  14689. }
  14690. }
  14691. SubMesh.prototype.getBoundingInfo = function () {
  14692. return this._boundingInfo;
  14693. };
  14694. SubMesh.prototype.getMesh = function () {
  14695. return this._mesh;
  14696. };
  14697. SubMesh.prototype.getRenderingMesh = function () {
  14698. return this._renderingMesh;
  14699. };
  14700. SubMesh.prototype.getMaterial = function () {
  14701. var rootMaterial = this._renderingMesh.material;
  14702. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  14703. var multiMaterial = rootMaterial;
  14704. return multiMaterial.getSubMaterial(this.materialIndex);
  14705. }
  14706. if (!rootMaterial) {
  14707. return this._mesh.getScene().defaultMaterial;
  14708. }
  14709. return rootMaterial;
  14710. };
  14711. // Methods
  14712. SubMesh.prototype.refreshBoundingInfo = function () {
  14713. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14714. if (!data) {
  14715. this._boundingInfo = this._mesh._boundingInfo;
  14716. return;
  14717. }
  14718. var indices = this._renderingMesh.getIndices();
  14719. var extend;
  14720. if (this.indexStart === 0 && this.indexCount === indices.length) {
  14721. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  14722. }
  14723. else {
  14724. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  14725. }
  14726. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14727. };
  14728. SubMesh.prototype._checkCollision = function (collider) {
  14729. return this._boundingInfo._checkCollision(collider);
  14730. };
  14731. SubMesh.prototype.updateBoundingInfo = function (world) {
  14732. if (!this._boundingInfo) {
  14733. this.refreshBoundingInfo();
  14734. }
  14735. this._boundingInfo._update(world);
  14736. };
  14737. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  14738. return this._boundingInfo.isInFrustum(frustumPlanes);
  14739. };
  14740. SubMesh.prototype.render = function () {
  14741. this._renderingMesh.render(this);
  14742. };
  14743. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  14744. if (!this._linesIndexBuffer) {
  14745. var linesIndices = [];
  14746. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14747. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  14748. }
  14749. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  14750. this.linesIndexCount = linesIndices.length;
  14751. }
  14752. return this._linesIndexBuffer;
  14753. };
  14754. SubMesh.prototype.canIntersects = function (ray) {
  14755. return ray.intersectsBox(this._boundingInfo.boundingBox);
  14756. };
  14757. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  14758. var intersectInfo = null;
  14759. // Triangles test
  14760. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14761. var p0 = positions[indices[index]];
  14762. var p1 = positions[indices[index + 1]];
  14763. var p2 = positions[indices[index + 2]];
  14764. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  14765. if (currentIntersectInfo) {
  14766. if (currentIntersectInfo.distance < 0) {
  14767. continue;
  14768. }
  14769. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14770. intersectInfo = currentIntersectInfo;
  14771. intersectInfo.faceId = index / 3;
  14772. if (fastCheck) {
  14773. break;
  14774. }
  14775. }
  14776. }
  14777. }
  14778. return intersectInfo;
  14779. };
  14780. // Clone
  14781. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  14782. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  14783. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  14784. return result;
  14785. };
  14786. // Dispose
  14787. SubMesh.prototype.dispose = function () {
  14788. if (this._linesIndexBuffer) {
  14789. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  14790. this._linesIndexBuffer = null;
  14791. }
  14792. // Remove from mesh
  14793. var index = this._mesh.subMeshes.indexOf(this);
  14794. this._mesh.subMeshes.splice(index, 1);
  14795. };
  14796. // Statics
  14797. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  14798. var minVertexIndex = Number.MAX_VALUE;
  14799. var maxVertexIndex = -Number.MAX_VALUE;
  14800. renderingMesh = renderingMesh || mesh;
  14801. var indices = renderingMesh.getIndices();
  14802. for (var index = startIndex; index < startIndex + indexCount; index++) {
  14803. var vertexIndex = indices[index];
  14804. if (vertexIndex < minVertexIndex)
  14805. minVertexIndex = vertexIndex;
  14806. if (vertexIndex > maxVertexIndex)
  14807. maxVertexIndex = vertexIndex;
  14808. }
  14809. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  14810. };
  14811. return SubMesh;
  14812. })();
  14813. BABYLON.SubMesh = SubMesh;
  14814. })(BABYLON || (BABYLON = {}));
  14815. //# sourceMappingURL=babylon.subMesh.js.map
  14816. var BABYLON;
  14817. (function (BABYLON) {
  14818. var BaseTexture = (function () {
  14819. function BaseTexture(scene) {
  14820. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14821. this.hasAlpha = false;
  14822. this.getAlphaFromRGB = false;
  14823. this.level = 1;
  14824. this.isCube = false;
  14825. this.isRenderTarget = false;
  14826. this.animations = new Array();
  14827. this.coordinatesIndex = 0;
  14828. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  14829. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14830. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14831. this.anisotropicFilteringLevel = 4;
  14832. this._scene = scene;
  14833. this._scene.textures.push(this);
  14834. }
  14835. BaseTexture.prototype.getScene = function () {
  14836. return this._scene;
  14837. };
  14838. BaseTexture.prototype.getTextureMatrix = function () {
  14839. return null;
  14840. };
  14841. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  14842. return null;
  14843. };
  14844. BaseTexture.prototype.getInternalTexture = function () {
  14845. return this._texture;
  14846. };
  14847. BaseTexture.prototype.isReady = function () {
  14848. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14849. return true;
  14850. }
  14851. if (this._texture) {
  14852. return this._texture.isReady;
  14853. }
  14854. return false;
  14855. };
  14856. BaseTexture.prototype.getSize = function () {
  14857. if (this._texture._width) {
  14858. return { width: this._texture._width, height: this._texture._height };
  14859. }
  14860. if (this._texture._size) {
  14861. return { width: this._texture._size, height: this._texture._size };
  14862. }
  14863. return { width: 0, height: 0 };
  14864. };
  14865. BaseTexture.prototype.getBaseSize = function () {
  14866. if (!this.isReady())
  14867. return { width: 0, height: 0 };
  14868. if (this._texture._size) {
  14869. return { width: this._texture._size, height: this._texture._size };
  14870. }
  14871. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  14872. };
  14873. BaseTexture.prototype.scale = function (ratio) {
  14874. };
  14875. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  14876. get: function () {
  14877. return false;
  14878. },
  14879. enumerable: true,
  14880. configurable: true
  14881. });
  14882. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  14883. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14884. for (var index = 0; index < texturesCache.length; index++) {
  14885. var texturesCacheEntry = texturesCache[index];
  14886. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14887. texturesCache.splice(index, 1);
  14888. return;
  14889. }
  14890. }
  14891. };
  14892. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  14893. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14894. for (var index = 0; index < texturesCache.length; index++) {
  14895. var texturesCacheEntry = texturesCache[index];
  14896. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14897. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  14898. texturesCacheEntry.references++;
  14899. return texturesCacheEntry;
  14900. }
  14901. }
  14902. }
  14903. return null;
  14904. };
  14905. BaseTexture.prototype.delayLoad = function () {
  14906. };
  14907. BaseTexture.prototype.releaseInternalTexture = function () {
  14908. if (!this._texture) {
  14909. return;
  14910. }
  14911. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14912. this._texture.references--;
  14913. // Final reference ?
  14914. if (this._texture.references === 0) {
  14915. var index = texturesCache.indexOf(this._texture);
  14916. texturesCache.splice(index, 1);
  14917. this._scene.getEngine()._releaseTexture(this._texture);
  14918. delete this._texture;
  14919. }
  14920. };
  14921. BaseTexture.prototype.clone = function () {
  14922. return null;
  14923. };
  14924. BaseTexture.prototype.dispose = function () {
  14925. // Remove from scene
  14926. var index = this._scene.textures.indexOf(this);
  14927. if (index >= 0) {
  14928. this._scene.textures.splice(index, 1);
  14929. }
  14930. if (this._texture === undefined) {
  14931. return;
  14932. }
  14933. this.releaseInternalTexture();
  14934. // Callback
  14935. if (this.onDispose) {
  14936. this.onDispose();
  14937. }
  14938. };
  14939. return BaseTexture;
  14940. })();
  14941. BABYLON.BaseTexture = BaseTexture;
  14942. })(BABYLON || (BABYLON = {}));
  14943. //# sourceMappingURL=babylon.baseTexture.js.map
  14944. var __extends = this.__extends || function (d, b) {
  14945. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14946. function __() { this.constructor = d; }
  14947. __.prototype = b.prototype;
  14948. d.prototype = new __();
  14949. };
  14950. var BABYLON;
  14951. (function (BABYLON) {
  14952. var Texture = (function (_super) {
  14953. __extends(Texture, _super);
  14954. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  14955. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  14956. if (onLoad === void 0) { onLoad = null; }
  14957. if (onError === void 0) { onError = null; }
  14958. if (buffer === void 0) { buffer = null; }
  14959. if (deleteBuffer === void 0) { deleteBuffer = false; }
  14960. _super.call(this, scene);
  14961. this.uOffset = 0;
  14962. this.vOffset = 0;
  14963. this.uScale = 1.0;
  14964. this.vScale = 1.0;
  14965. this.uAng = 0;
  14966. this.vAng = 0;
  14967. this.wAng = 0;
  14968. this.name = url;
  14969. this.url = url;
  14970. this._noMipmap = noMipmap;
  14971. this._invertY = invertY;
  14972. this._samplingMode = samplingMode;
  14973. this._buffer = buffer;
  14974. this._deleteBuffer = deleteBuffer;
  14975. if (!url) {
  14976. return;
  14977. }
  14978. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  14979. if (!this._texture) {
  14980. if (!scene.useDelayedTextureLoading) {
  14981. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  14982. if (deleteBuffer) {
  14983. delete this._buffer;
  14984. }
  14985. }
  14986. else {
  14987. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14988. }
  14989. }
  14990. else {
  14991. BABYLON.Tools.SetImmediate(function () {
  14992. if (onLoad) {
  14993. onLoad();
  14994. }
  14995. });
  14996. }
  14997. }
  14998. Texture.prototype.delayLoad = function () {
  14999. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15000. return;
  15001. }
  15002. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15003. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  15004. if (!this._texture) {
  15005. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  15006. if (this._deleteBuffer) {
  15007. delete this._buffer;
  15008. }
  15009. }
  15010. };
  15011. Texture.prototype.updateSamplingMode = function (samplingMode) {
  15012. if (!this._texture) {
  15013. return;
  15014. }
  15015. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  15016. };
  15017. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  15018. x -= this.uOffset + 0.5;
  15019. y -= this.vOffset + 0.5;
  15020. z -= 0.5;
  15021. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  15022. t.x *= this.uScale;
  15023. t.y *= this.vScale;
  15024. t.x += 0.5;
  15025. t.y += 0.5;
  15026. t.z += 0.5;
  15027. };
  15028. Texture.prototype.getTextureMatrix = function () {
  15029. if (this.uOffset === this._cachedUOffset &&
  15030. this.vOffset === this._cachedVOffset &&
  15031. this.uScale === this._cachedUScale &&
  15032. this.vScale === this._cachedVScale &&
  15033. this.uAng === this._cachedUAng &&
  15034. this.vAng === this._cachedVAng &&
  15035. this.wAng === this._cachedWAng) {
  15036. return this._cachedTextureMatrix;
  15037. }
  15038. this._cachedUOffset = this.uOffset;
  15039. this._cachedVOffset = this.vOffset;
  15040. this._cachedUScale = this.uScale;
  15041. this._cachedVScale = this.vScale;
  15042. this._cachedUAng = this.uAng;
  15043. this._cachedVAng = this.vAng;
  15044. this._cachedWAng = this.wAng;
  15045. if (!this._cachedTextureMatrix) {
  15046. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  15047. this._rowGenerationMatrix = new BABYLON.Matrix();
  15048. this._t0 = BABYLON.Vector3.Zero();
  15049. this._t1 = BABYLON.Vector3.Zero();
  15050. this._t2 = BABYLON.Vector3.Zero();
  15051. }
  15052. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  15053. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  15054. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  15055. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  15056. this._t1.subtractInPlace(this._t0);
  15057. this._t2.subtractInPlace(this._t0);
  15058. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15059. this._cachedTextureMatrix.m[0] = this._t1.x;
  15060. this._cachedTextureMatrix.m[1] = this._t1.y;
  15061. this._cachedTextureMatrix.m[2] = this._t1.z;
  15062. this._cachedTextureMatrix.m[4] = this._t2.x;
  15063. this._cachedTextureMatrix.m[5] = this._t2.y;
  15064. this._cachedTextureMatrix.m[6] = this._t2.z;
  15065. this._cachedTextureMatrix.m[8] = this._t0.x;
  15066. this._cachedTextureMatrix.m[9] = this._t0.y;
  15067. this._cachedTextureMatrix.m[10] = this._t0.z;
  15068. return this._cachedTextureMatrix;
  15069. };
  15070. Texture.prototype.getReflectionTextureMatrix = function () {
  15071. if (this.uOffset === this._cachedUOffset &&
  15072. this.vOffset === this._cachedVOffset &&
  15073. this.uScale === this._cachedUScale &&
  15074. this.vScale === this._cachedVScale &&
  15075. this.coordinatesMode === this._cachedCoordinatesMode) {
  15076. return this._cachedTextureMatrix;
  15077. }
  15078. if (!this._cachedTextureMatrix) {
  15079. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  15080. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  15081. }
  15082. this._cachedCoordinatesMode = this.coordinatesMode;
  15083. switch (this.coordinatesMode) {
  15084. case Texture.SPHERICAL_MODE:
  15085. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15086. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  15087. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  15088. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  15089. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  15090. break;
  15091. case Texture.PLANAR_MODE:
  15092. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15093. this._cachedTextureMatrix[0] = this.uScale;
  15094. this._cachedTextureMatrix[5] = this.vScale;
  15095. this._cachedTextureMatrix[12] = this.uOffset;
  15096. this._cachedTextureMatrix[13] = this.vOffset;
  15097. break;
  15098. case Texture.PROJECTION_MODE:
  15099. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  15100. this._projectionModeMatrix.m[0] = 0.5;
  15101. this._projectionModeMatrix.m[5] = -0.5;
  15102. this._projectionModeMatrix.m[10] = 0.0;
  15103. this._projectionModeMatrix.m[12] = 0.5;
  15104. this._projectionModeMatrix.m[13] = 0.5;
  15105. this._projectionModeMatrix.m[14] = 1.0;
  15106. this._projectionModeMatrix.m[15] = 1.0;
  15107. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  15108. break;
  15109. default:
  15110. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15111. break;
  15112. }
  15113. return this._cachedTextureMatrix;
  15114. };
  15115. Texture.prototype.clone = function () {
  15116. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  15117. // Base texture
  15118. newTexture.hasAlpha = this.hasAlpha;
  15119. newTexture.level = this.level;
  15120. newTexture.wrapU = this.wrapU;
  15121. newTexture.wrapV = this.wrapV;
  15122. newTexture.coordinatesIndex = this.coordinatesIndex;
  15123. newTexture.coordinatesMode = this.coordinatesMode;
  15124. // Texture
  15125. newTexture.uOffset = this.uOffset;
  15126. newTexture.vOffset = this.vOffset;
  15127. newTexture.uScale = this.uScale;
  15128. newTexture.vScale = this.vScale;
  15129. newTexture.uAng = this.uAng;
  15130. newTexture.vAng = this.vAng;
  15131. newTexture.wAng = this.wAng;
  15132. return newTexture;
  15133. };
  15134. // Statics
  15135. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  15136. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  15137. if (onLoad === void 0) { onLoad = null; }
  15138. if (onError === void 0) { onError = null; }
  15139. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  15140. };
  15141. // Constants
  15142. Texture.NEAREST_SAMPLINGMODE = 1;
  15143. Texture.BILINEAR_SAMPLINGMODE = 2;
  15144. Texture.TRILINEAR_SAMPLINGMODE = 3;
  15145. Texture.EXPLICIT_MODE = 0;
  15146. Texture.SPHERICAL_MODE = 1;
  15147. Texture.PLANAR_MODE = 2;
  15148. Texture.CUBIC_MODE = 3;
  15149. Texture.PROJECTION_MODE = 4;
  15150. Texture.SKYBOX_MODE = 5;
  15151. Texture.CLAMP_ADDRESSMODE = 0;
  15152. Texture.WRAP_ADDRESSMODE = 1;
  15153. Texture.MIRROR_ADDRESSMODE = 2;
  15154. return Texture;
  15155. })(BABYLON.BaseTexture);
  15156. BABYLON.Texture = Texture;
  15157. })(BABYLON || (BABYLON = {}));
  15158. //# sourceMappingURL=babylon.texture.js.map
  15159. var __extends = this.__extends || function (d, b) {
  15160. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15161. function __() { this.constructor = d; }
  15162. __.prototype = b.prototype;
  15163. d.prototype = new __();
  15164. };
  15165. var BABYLON;
  15166. (function (BABYLON) {
  15167. var CubeTexture = (function (_super) {
  15168. __extends(CubeTexture, _super);
  15169. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  15170. _super.call(this, scene);
  15171. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  15172. this.name = rootUrl;
  15173. this.url = rootUrl;
  15174. this._noMipmap = noMipmap;
  15175. this.hasAlpha = false;
  15176. this._texture = this._getFromCache(rootUrl, noMipmap);
  15177. if (!extensions) {
  15178. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  15179. }
  15180. this._extensions = extensions;
  15181. if (!this._texture) {
  15182. if (!scene.useDelayedTextureLoading) {
  15183. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  15184. }
  15185. else {
  15186. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15187. }
  15188. }
  15189. this.isCube = true;
  15190. this._textureMatrix = BABYLON.Matrix.Identity();
  15191. }
  15192. CubeTexture.prototype.clone = function () {
  15193. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  15194. // Base texture
  15195. newTexture.level = this.level;
  15196. newTexture.wrapU = this.wrapU;
  15197. newTexture.wrapV = this.wrapV;
  15198. newTexture.coordinatesIndex = this.coordinatesIndex;
  15199. newTexture.coordinatesMode = this.coordinatesMode;
  15200. return newTexture;
  15201. };
  15202. // Methods
  15203. CubeTexture.prototype.delayLoad = function () {
  15204. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15205. return;
  15206. }
  15207. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15208. this._texture = this._getFromCache(this.url, this._noMipmap);
  15209. if (!this._texture) {
  15210. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  15211. }
  15212. };
  15213. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  15214. return this._textureMatrix;
  15215. };
  15216. return CubeTexture;
  15217. })(BABYLON.BaseTexture);
  15218. BABYLON.CubeTexture = CubeTexture;
  15219. })(BABYLON || (BABYLON = {}));
  15220. //# sourceMappingURL=babylon.cubeTexture.js.map
  15221. var __extends = this.__extends || function (d, b) {
  15222. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15223. function __() { this.constructor = d; }
  15224. __.prototype = b.prototype;
  15225. d.prototype = new __();
  15226. };
  15227. var BABYLON;
  15228. (function (BABYLON) {
  15229. var RenderTargetTexture = (function (_super) {
  15230. __extends(RenderTargetTexture, _super);
  15231. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  15232. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  15233. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  15234. _super.call(this, null, scene, !generateMipMaps);
  15235. this.renderList = new Array();
  15236. this.renderParticles = true;
  15237. this.renderSprites = false;
  15238. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  15239. this._currentRefreshId = -1;
  15240. this._refreshRate = 1;
  15241. this.name = name;
  15242. this.isRenderTarget = true;
  15243. this._size = size;
  15244. this._generateMipMaps = generateMipMaps;
  15245. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  15246. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  15247. // Rendering groups
  15248. this._renderingManager = new BABYLON.RenderingManager(scene);
  15249. }
  15250. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  15251. this._currentRefreshId = -1;
  15252. };
  15253. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  15254. get: function () {
  15255. return this._refreshRate;
  15256. },
  15257. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15258. set: function (value) {
  15259. this._refreshRate = value;
  15260. this.resetRefreshCounter();
  15261. },
  15262. enumerable: true,
  15263. configurable: true
  15264. });
  15265. RenderTargetTexture.prototype._shouldRender = function () {
  15266. if (this._currentRefreshId === -1) {
  15267. this._currentRefreshId = 1;
  15268. return true;
  15269. }
  15270. if (this.refreshRate === this._currentRefreshId) {
  15271. this._currentRefreshId = 1;
  15272. return true;
  15273. }
  15274. this._currentRefreshId++;
  15275. return false;
  15276. };
  15277. RenderTargetTexture.prototype.isReady = function () {
  15278. if (!this.getScene().renderTargetsEnabled) {
  15279. return false;
  15280. }
  15281. return _super.prototype.isReady.call(this);
  15282. };
  15283. RenderTargetTexture.prototype.getRenderSize = function () {
  15284. return this._size;
  15285. };
  15286. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  15287. get: function () {
  15288. return true;
  15289. },
  15290. enumerable: true,
  15291. configurable: true
  15292. });
  15293. RenderTargetTexture.prototype.scale = function (ratio) {
  15294. var newSize = this._size * ratio;
  15295. this.resize(newSize, this._generateMipMaps);
  15296. };
  15297. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  15298. this.releaseInternalTexture();
  15299. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15300. };
  15301. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  15302. var scene = this.getScene();
  15303. var engine = scene.getEngine();
  15304. if (this._waitingRenderList) {
  15305. this.renderList = [];
  15306. for (var index = 0; index < this._waitingRenderList.length; index++) {
  15307. var id = this._waitingRenderList[index];
  15308. this.renderList.push(scene.getMeshByID(id));
  15309. }
  15310. delete this._waitingRenderList;
  15311. }
  15312. if (this.renderList && this.renderList.length === 0) {
  15313. return;
  15314. }
  15315. // Bind
  15316. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  15317. engine.bindFramebuffer(this._texture);
  15318. }
  15319. this._renderingManager.reset();
  15320. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  15321. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  15322. var mesh = currentRenderList[meshIndex];
  15323. if (mesh) {
  15324. if (!mesh.isReady()) {
  15325. // Reset _currentRefreshId
  15326. this.resetRefreshCounter();
  15327. continue;
  15328. }
  15329. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  15330. mesh._activate(scene.getRenderId());
  15331. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15332. var subMesh = mesh.subMeshes[subIndex];
  15333. scene._activeIndices += subMesh.indexCount;
  15334. this._renderingManager.dispatch(subMesh);
  15335. }
  15336. }
  15337. }
  15338. }
  15339. if (this.onBeforeRender) {
  15340. this.onBeforeRender();
  15341. }
  15342. // Clear
  15343. if (this.onClear) {
  15344. this.onClear(engine);
  15345. }
  15346. else {
  15347. engine.clear(scene.clearColor, true, true);
  15348. }
  15349. if (!this._doNotChangeAspectRatio) {
  15350. scene.updateTransformMatrix(true);
  15351. }
  15352. // Render
  15353. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  15354. if (useCameraPostProcess) {
  15355. scene.postProcessManager._finalizeFrame(false, this._texture);
  15356. }
  15357. if (!this._doNotChangeAspectRatio) {
  15358. scene.updateTransformMatrix(true);
  15359. }
  15360. if (this.onAfterRender) {
  15361. this.onAfterRender();
  15362. }
  15363. // Dump ?
  15364. if (dumpForDebug) {
  15365. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  15366. }
  15367. // Unbind
  15368. engine.unBindFramebuffer(this._texture);
  15369. if (this.onAfterUnbind) {
  15370. this.onAfterUnbind();
  15371. }
  15372. };
  15373. RenderTargetTexture.prototype.clone = function () {
  15374. var textureSize = this.getSize();
  15375. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15376. // Base texture
  15377. newTexture.hasAlpha = this.hasAlpha;
  15378. newTexture.level = this.level;
  15379. // RenderTarget Texture
  15380. newTexture.coordinatesMode = this.coordinatesMode;
  15381. newTexture.renderList = this.renderList.slice(0);
  15382. return newTexture;
  15383. };
  15384. return RenderTargetTexture;
  15385. })(BABYLON.Texture);
  15386. BABYLON.RenderTargetTexture = RenderTargetTexture;
  15387. })(BABYLON || (BABYLON = {}));
  15388. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  15389. var __extends = this.__extends || function (d, b) {
  15390. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15391. function __() { this.constructor = d; }
  15392. __.prototype = b.prototype;
  15393. d.prototype = new __();
  15394. };
  15395. var BABYLON;
  15396. (function (BABYLON) {
  15397. var ProceduralTexture = (function (_super) {
  15398. __extends(ProceduralTexture, _super);
  15399. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  15400. if (generateMipMaps === void 0) { generateMipMaps = true; }
  15401. _super.call(this, null, scene, !generateMipMaps);
  15402. this._currentRefreshId = -1;
  15403. this._refreshRate = 1;
  15404. this._vertexDeclaration = [2];
  15405. this._vertexStrideSize = 2 * 4;
  15406. this._uniforms = new Array();
  15407. this._samplers = new Array();
  15408. this._textures = new Array();
  15409. this._floats = new Array();
  15410. this._floatsArrays = {};
  15411. this._colors3 = new Array();
  15412. this._colors4 = new Array();
  15413. this._vectors2 = new Array();
  15414. this._vectors3 = new Array();
  15415. this._matrices = new Array();
  15416. this._fallbackTextureUsed = false;
  15417. scene._proceduralTextures.push(this);
  15418. this.name = name;
  15419. this.isRenderTarget = true;
  15420. this._size = size;
  15421. this._generateMipMaps = generateMipMaps;
  15422. this.setFragment(fragment);
  15423. this._fallbackTexture = fallbackTexture;
  15424. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  15425. // VBO
  15426. var vertices = [];
  15427. vertices.push(1, 1);
  15428. vertices.push(-1, 1);
  15429. vertices.push(-1, -1);
  15430. vertices.push(1, -1);
  15431. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15432. // Indices
  15433. var indices = [];
  15434. indices.push(0);
  15435. indices.push(1);
  15436. indices.push(2);
  15437. indices.push(0);
  15438. indices.push(2);
  15439. indices.push(3);
  15440. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15441. }
  15442. ProceduralTexture.prototype.reset = function () {
  15443. if (this._effect === undefined) {
  15444. return;
  15445. }
  15446. var engine = this.getScene().getEngine();
  15447. engine._releaseEffect(this._effect);
  15448. };
  15449. ProceduralTexture.prototype.isReady = function () {
  15450. var _this = this;
  15451. var engine = this.getScene().getEngine();
  15452. var shaders;
  15453. if (!this._fragment) {
  15454. return false;
  15455. }
  15456. if (this._fallbackTextureUsed) {
  15457. return true;
  15458. }
  15459. if (this._fragment.fragmentElement !== undefined) {
  15460. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  15461. }
  15462. else {
  15463. shaders = { vertex: "procedural", fragment: this._fragment };
  15464. }
  15465. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  15466. _this.releaseInternalTexture();
  15467. if (_this._fallbackTexture) {
  15468. _this._texture = _this._fallbackTexture._texture;
  15469. _this._texture.references++;
  15470. }
  15471. _this._fallbackTextureUsed = true;
  15472. });
  15473. return this._effect.isReady();
  15474. };
  15475. ProceduralTexture.prototype.resetRefreshCounter = function () {
  15476. this._currentRefreshId = -1;
  15477. };
  15478. ProceduralTexture.prototype.setFragment = function (fragment) {
  15479. this._fragment = fragment;
  15480. };
  15481. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  15482. get: function () {
  15483. return this._refreshRate;
  15484. },
  15485. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15486. set: function (value) {
  15487. this._refreshRate = value;
  15488. this.resetRefreshCounter();
  15489. },
  15490. enumerable: true,
  15491. configurable: true
  15492. });
  15493. ProceduralTexture.prototype._shouldRender = function () {
  15494. if (!this.isReady() || !this._texture) {
  15495. return false;
  15496. }
  15497. if (this._fallbackTextureUsed) {
  15498. return false;
  15499. }
  15500. if (this._currentRefreshId === -1) {
  15501. this._currentRefreshId = 1;
  15502. return true;
  15503. }
  15504. if (this.refreshRate === this._currentRefreshId) {
  15505. this._currentRefreshId = 1;
  15506. return true;
  15507. }
  15508. this._currentRefreshId++;
  15509. return false;
  15510. };
  15511. ProceduralTexture.prototype.getRenderSize = function () {
  15512. return this._size;
  15513. };
  15514. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  15515. if (this._fallbackTextureUsed) {
  15516. return;
  15517. }
  15518. this.releaseInternalTexture();
  15519. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15520. };
  15521. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  15522. if (this._uniforms.indexOf(uniformName) === -1) {
  15523. this._uniforms.push(uniformName);
  15524. }
  15525. };
  15526. ProceduralTexture.prototype.setTexture = function (name, texture) {
  15527. if (this._samplers.indexOf(name) === -1) {
  15528. this._samplers.push(name);
  15529. }
  15530. this._textures[name] = texture;
  15531. return this;
  15532. };
  15533. ProceduralTexture.prototype.setFloat = function (name, value) {
  15534. this._checkUniform(name);
  15535. this._floats[name] = value;
  15536. return this;
  15537. };
  15538. ProceduralTexture.prototype.setFloats = function (name, value) {
  15539. this._checkUniform(name);
  15540. this._floatsArrays[name] = value;
  15541. return this;
  15542. };
  15543. ProceduralTexture.prototype.setColor3 = function (name, value) {
  15544. this._checkUniform(name);
  15545. this._colors3[name] = value;
  15546. return this;
  15547. };
  15548. ProceduralTexture.prototype.setColor4 = function (name, value) {
  15549. this._checkUniform(name);
  15550. this._colors4[name] = value;
  15551. return this;
  15552. };
  15553. ProceduralTexture.prototype.setVector2 = function (name, value) {
  15554. this._checkUniform(name);
  15555. this._vectors2[name] = value;
  15556. return this;
  15557. };
  15558. ProceduralTexture.prototype.setVector3 = function (name, value) {
  15559. this._checkUniform(name);
  15560. this._vectors3[name] = value;
  15561. return this;
  15562. };
  15563. ProceduralTexture.prototype.setMatrix = function (name, value) {
  15564. this._checkUniform(name);
  15565. this._matrices[name] = value;
  15566. return this;
  15567. };
  15568. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15569. var scene = this.getScene();
  15570. var engine = scene.getEngine();
  15571. engine.bindFramebuffer(this._texture);
  15572. // Clear
  15573. engine.clear(scene.clearColor, true, true);
  15574. // Render
  15575. engine.enableEffect(this._effect);
  15576. engine.setState(false);
  15577. // Texture
  15578. for (var name in this._textures) {
  15579. this._effect.setTexture(name, this._textures[name]);
  15580. }
  15581. // Float
  15582. for (name in this._floats) {
  15583. this._effect.setFloat(name, this._floats[name]);
  15584. }
  15585. // Floats
  15586. for (name in this._floatsArrays) {
  15587. this._effect.setArray(name, this._floatsArrays[name]);
  15588. }
  15589. // Color3
  15590. for (name in this._colors3) {
  15591. this._effect.setColor3(name, this._colors3[name]);
  15592. }
  15593. // Color4
  15594. for (name in this._colors4) {
  15595. var color = this._colors4[name];
  15596. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15597. }
  15598. // Vector2
  15599. for (name in this._vectors2) {
  15600. this._effect.setVector2(name, this._vectors2[name]);
  15601. }
  15602. // Vector3
  15603. for (name in this._vectors3) {
  15604. this._effect.setVector3(name, this._vectors3[name]);
  15605. }
  15606. // Matrix
  15607. for (name in this._matrices) {
  15608. this._effect.setMatrix(name, this._matrices[name]);
  15609. }
  15610. // VBOs
  15611. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15612. // Draw order
  15613. engine.draw(true, 0, 6);
  15614. // Unbind
  15615. engine.unBindFramebuffer(this._texture);
  15616. };
  15617. ProceduralTexture.prototype.clone = function () {
  15618. var textureSize = this.getSize();
  15619. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  15620. // Base texture
  15621. newTexture.hasAlpha = this.hasAlpha;
  15622. newTexture.level = this.level;
  15623. // RenderTarget Texture
  15624. newTexture.coordinatesMode = this.coordinatesMode;
  15625. return newTexture;
  15626. };
  15627. ProceduralTexture.prototype.dispose = function () {
  15628. var index = this.getScene()._proceduralTextures.indexOf(this);
  15629. if (index >= 0) {
  15630. this.getScene()._proceduralTextures.splice(index, 1);
  15631. }
  15632. _super.prototype.dispose.call(this);
  15633. };
  15634. return ProceduralTexture;
  15635. })(BABYLON.Texture);
  15636. BABYLON.ProceduralTexture = ProceduralTexture;
  15637. })(BABYLON || (BABYLON = {}));
  15638. //# sourceMappingURL=babylon.proceduralTexture.js.map
  15639. var __extends = this.__extends || function (d, b) {
  15640. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15641. function __() { this.constructor = d; }
  15642. __.prototype = b.prototype;
  15643. d.prototype = new __();
  15644. };
  15645. var BABYLON;
  15646. (function (BABYLON) {
  15647. var MirrorTexture = (function (_super) {
  15648. __extends(MirrorTexture, _super);
  15649. function MirrorTexture(name, size, scene, generateMipMaps) {
  15650. var _this = this;
  15651. _super.call(this, name, size, scene, generateMipMaps, true);
  15652. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  15653. this._transformMatrix = BABYLON.Matrix.Zero();
  15654. this._mirrorMatrix = BABYLON.Matrix.Zero();
  15655. this.onBeforeRender = function () {
  15656. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  15657. _this._savedViewMatrix = scene.getViewMatrix();
  15658. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  15659. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  15660. scene.clipPlane = _this.mirrorPlane;
  15661. scene.getEngine().cullBackFaces = false;
  15662. };
  15663. this.onAfterRender = function () {
  15664. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  15665. scene.getEngine().cullBackFaces = true;
  15666. delete scene.clipPlane;
  15667. };
  15668. }
  15669. MirrorTexture.prototype.clone = function () {
  15670. var textureSize = this.getSize();
  15671. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15672. // Base texture
  15673. newTexture.hasAlpha = this.hasAlpha;
  15674. newTexture.level = this.level;
  15675. // Mirror Texture
  15676. newTexture.mirrorPlane = this.mirrorPlane.clone();
  15677. newTexture.renderList = this.renderList.slice(0);
  15678. return newTexture;
  15679. };
  15680. return MirrorTexture;
  15681. })(BABYLON.RenderTargetTexture);
  15682. BABYLON.MirrorTexture = MirrorTexture;
  15683. })(BABYLON || (BABYLON = {}));
  15684. //# sourceMappingURL=babylon.mirrorTexture.js.map
  15685. var __extends = this.__extends || function (d, b) {
  15686. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15687. function __() { this.constructor = d; }
  15688. __.prototype = b.prototype;
  15689. d.prototype = new __();
  15690. };
  15691. var BABYLON;
  15692. (function (BABYLON) {
  15693. var DynamicTexture = (function (_super) {
  15694. __extends(DynamicTexture, _super);
  15695. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  15696. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15697. _super.call(this, null, scene, !generateMipMaps);
  15698. this.name = name;
  15699. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15700. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15701. this._generateMipMaps = generateMipMaps;
  15702. if (options.getContext) {
  15703. this._canvas = options;
  15704. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15705. }
  15706. else {
  15707. this._canvas = document.createElement("canvas");
  15708. if (options.width) {
  15709. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15710. }
  15711. else {
  15712. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  15713. }
  15714. }
  15715. var textureSize = this.getSize();
  15716. this._canvas.width = textureSize.width;
  15717. this._canvas.height = textureSize.height;
  15718. this._context = this._canvas.getContext("2d");
  15719. }
  15720. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  15721. get: function () {
  15722. return true;
  15723. },
  15724. enumerable: true,
  15725. configurable: true
  15726. });
  15727. DynamicTexture.prototype.scale = function (ratio) {
  15728. var textureSize = this.getSize();
  15729. textureSize.width *= ratio;
  15730. textureSize.height *= ratio;
  15731. this._canvas.width = textureSize.width;
  15732. this._canvas.height = textureSize.height;
  15733. this.releaseInternalTexture();
  15734. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  15735. };
  15736. DynamicTexture.prototype.getContext = function () {
  15737. return this._context;
  15738. };
  15739. DynamicTexture.prototype.clear = function () {
  15740. var size = this.getSize();
  15741. this._context.fillRect(0, 0, size.width, size.height);
  15742. };
  15743. DynamicTexture.prototype.update = function (invertY) {
  15744. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  15745. };
  15746. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  15747. if (update === void 0) { update = true; }
  15748. var size = this.getSize();
  15749. if (clearColor) {
  15750. this._context.fillStyle = clearColor;
  15751. this._context.fillRect(0, 0, size.width, size.height);
  15752. }
  15753. this._context.font = font;
  15754. if (x === null) {
  15755. var textSize = this._context.measureText(text);
  15756. x = (size.width - textSize.width) / 2;
  15757. }
  15758. this._context.fillStyle = color;
  15759. this._context.fillText(text, x, y);
  15760. if (update) {
  15761. this.update(invertY);
  15762. }
  15763. };
  15764. DynamicTexture.prototype.clone = function () {
  15765. var textureSize = this.getSize();
  15766. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15767. // Base texture
  15768. newTexture.hasAlpha = this.hasAlpha;
  15769. newTexture.level = this.level;
  15770. // Dynamic Texture
  15771. newTexture.wrapU = this.wrapU;
  15772. newTexture.wrapV = this.wrapV;
  15773. return newTexture;
  15774. };
  15775. return DynamicTexture;
  15776. })(BABYLON.Texture);
  15777. BABYLON.DynamicTexture = DynamicTexture;
  15778. })(BABYLON || (BABYLON = {}));
  15779. //# sourceMappingURL=babylon.dynamicTexture.js.map
  15780. var __extends = this.__extends || function (d, b) {
  15781. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15782. function __() { this.constructor = d; }
  15783. __.prototype = b.prototype;
  15784. d.prototype = new __();
  15785. };
  15786. var BABYLON;
  15787. (function (BABYLON) {
  15788. var VideoTexture = (function (_super) {
  15789. __extends(VideoTexture, _super);
  15790. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  15791. var _this = this;
  15792. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15793. _super.call(this, null, scene, !generateMipMaps, invertY);
  15794. this._autoLaunch = true;
  15795. this.name = name;
  15796. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15797. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15798. var requiredWidth = size.width || size;
  15799. var requiredHeight = size.height || size;
  15800. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  15801. var textureSize = this.getSize();
  15802. this.video = document.createElement("video");
  15803. this.video.width = textureSize.width;
  15804. this.video.height = textureSize.height;
  15805. this.video.autoplay = false;
  15806. this.video.loop = true;
  15807. this.video.addEventListener("canplaythrough", function () {
  15808. if (_this._texture) {
  15809. _this._texture.isReady = true;
  15810. }
  15811. });
  15812. urls.forEach(function (url) {
  15813. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  15814. var source = document.createElement("source");
  15815. source.src = url;
  15816. _this.video.appendChild(source);
  15817. });
  15818. this._lastUpdate = BABYLON.Tools.Now;
  15819. }
  15820. VideoTexture.prototype.update = function () {
  15821. if (this._autoLaunch) {
  15822. this._autoLaunch = false;
  15823. this.video.play();
  15824. }
  15825. var now = BABYLON.Tools.Now;
  15826. if (now - this._lastUpdate < 15) {
  15827. return false;
  15828. }
  15829. this._lastUpdate = now;
  15830. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  15831. return true;
  15832. };
  15833. return VideoTexture;
  15834. })(BABYLON.Texture);
  15835. BABYLON.VideoTexture = VideoTexture;
  15836. })(BABYLON || (BABYLON = {}));
  15837. //# sourceMappingURL=babylon.videoTexture.js.map
  15838. var __extends = this.__extends || function (d, b) {
  15839. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15840. function __() { this.constructor = d; }
  15841. __.prototype = b.prototype;
  15842. d.prototype = new __();
  15843. };
  15844. var BABYLON;
  15845. (function (BABYLON) {
  15846. var CustomProceduralTexture = (function (_super) {
  15847. __extends(CustomProceduralTexture, _super);
  15848. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  15849. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  15850. this._animate = true;
  15851. this._time = 0;
  15852. this._texturePath = texturePath;
  15853. //Try to load json
  15854. this.loadJson(texturePath);
  15855. this.refreshRate = 1;
  15856. }
  15857. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  15858. var _this = this;
  15859. var that = this;
  15860. function noConfigFile() {
  15861. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  15862. try {
  15863. that.setFragment(that._texturePath);
  15864. }
  15865. catch (ex) {
  15866. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  15867. }
  15868. }
  15869. var configFileUrl = jsonUrl + "/config.json";
  15870. var xhr = new XMLHttpRequest();
  15871. xhr.open("GET", configFileUrl, true);
  15872. xhr.addEventListener("load", function () {
  15873. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15874. try {
  15875. _this._config = JSON.parse(xhr.response);
  15876. _this.updateShaderUniforms();
  15877. _this.updateTextures();
  15878. _this.setFragment(_this._texturePath + "/custom");
  15879. _this._animate = _this._config.animate;
  15880. _this.refreshRate = _this._config.refreshrate;
  15881. }
  15882. catch (ex) {
  15883. noConfigFile();
  15884. }
  15885. }
  15886. else {
  15887. noConfigFile();
  15888. }
  15889. }, false);
  15890. xhr.addEventListener("error", function () {
  15891. noConfigFile();
  15892. }, false);
  15893. try {
  15894. xhr.send();
  15895. }
  15896. catch (ex) {
  15897. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  15898. }
  15899. };
  15900. CustomProceduralTexture.prototype.isReady = function () {
  15901. if (!_super.prototype.isReady.call(this)) {
  15902. return false;
  15903. }
  15904. for (var name in this._textures) {
  15905. var texture = this._textures[name];
  15906. if (!texture.isReady()) {
  15907. return false;
  15908. }
  15909. }
  15910. return true;
  15911. };
  15912. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15913. if (this._animate) {
  15914. this._time += this.getScene().getAnimationRatio() * 0.03;
  15915. this.updateShaderUniforms();
  15916. }
  15917. _super.prototype.render.call(this, useCameraPostProcess);
  15918. };
  15919. CustomProceduralTexture.prototype.updateTextures = function () {
  15920. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  15921. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  15922. }
  15923. };
  15924. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  15925. if (this._config) {
  15926. for (var j = 0; j < this._config.uniforms.length; j++) {
  15927. var uniform = this._config.uniforms[j];
  15928. switch (uniform.type) {
  15929. case "float":
  15930. this.setFloat(uniform.name, uniform.value);
  15931. break;
  15932. case "color3":
  15933. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  15934. break;
  15935. case "color4":
  15936. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  15937. break;
  15938. case "vector2":
  15939. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  15940. break;
  15941. case "vector3":
  15942. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  15943. break;
  15944. }
  15945. }
  15946. }
  15947. this.setFloat("time", this._time);
  15948. };
  15949. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  15950. get: function () {
  15951. return this._animate;
  15952. },
  15953. set: function (value) {
  15954. this._animate = value;
  15955. },
  15956. enumerable: true,
  15957. configurable: true
  15958. });
  15959. return CustomProceduralTexture;
  15960. })(BABYLON.ProceduralTexture);
  15961. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  15962. })(BABYLON || (BABYLON = {}));
  15963. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  15964. var __extends = this.__extends || function (d, b) {
  15965. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15966. function __() { this.constructor = d; }
  15967. __.prototype = b.prototype;
  15968. d.prototype = new __();
  15969. };
  15970. var BABYLON;
  15971. (function (BABYLON) {
  15972. var WoodProceduralTexture = (function (_super) {
  15973. __extends(WoodProceduralTexture, _super);
  15974. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  15975. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  15976. this._ampScale = 100.0;
  15977. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  15978. this.updateShaderUniforms();
  15979. this.refreshRate = 0;
  15980. }
  15981. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  15982. this.setFloat("ampScale", this._ampScale);
  15983. this.setColor3("woodColor", this._woodColor);
  15984. };
  15985. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  15986. get: function () {
  15987. return this._ampScale;
  15988. },
  15989. set: function (value) {
  15990. this._ampScale = value;
  15991. this.updateShaderUniforms();
  15992. },
  15993. enumerable: true,
  15994. configurable: true
  15995. });
  15996. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  15997. get: function () {
  15998. return this._woodColor;
  15999. },
  16000. set: function (value) {
  16001. this._woodColor = value;
  16002. this.updateShaderUniforms();
  16003. },
  16004. enumerable: true,
  16005. configurable: true
  16006. });
  16007. return WoodProceduralTexture;
  16008. })(BABYLON.ProceduralTexture);
  16009. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  16010. var FireProceduralTexture = (function (_super) {
  16011. __extends(FireProceduralTexture, _super);
  16012. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16013. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  16014. this._time = 0.0;
  16015. this._speed = new BABYLON.Vector2(0.5, 0.3);
  16016. this._autoGenerateTime = true;
  16017. this._alphaThreshold = 0.5;
  16018. this._fireColors = FireProceduralTexture.RedFireColors;
  16019. this.updateShaderUniforms();
  16020. this.refreshRate = 1;
  16021. }
  16022. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  16023. this.setFloat("time", this._time);
  16024. this.setVector2("speed", this._speed);
  16025. this.setColor3("c1", this._fireColors[0]);
  16026. this.setColor3("c2", this._fireColors[1]);
  16027. this.setColor3("c3", this._fireColors[2]);
  16028. this.setColor3("c4", this._fireColors[3]);
  16029. this.setColor3("c5", this._fireColors[4]);
  16030. this.setColor3("c6", this._fireColors[5]);
  16031. this.setFloat("alphaThreshold", this._alphaThreshold);
  16032. };
  16033. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16034. if (this._autoGenerateTime) {
  16035. this._time += this.getScene().getAnimationRatio() * 0.03;
  16036. this.updateShaderUniforms();
  16037. }
  16038. _super.prototype.render.call(this, useCameraPostProcess);
  16039. };
  16040. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  16041. get: function () {
  16042. return [
  16043. new BABYLON.Color3(0.5, 0.0, 1.0),
  16044. new BABYLON.Color3(0.9, 0.0, 1.0),
  16045. new BABYLON.Color3(0.2, 0.0, 1.0),
  16046. new BABYLON.Color3(1.0, 0.9, 1.0),
  16047. new BABYLON.Color3(0.1, 0.1, 1.0),
  16048. new BABYLON.Color3(0.9, 0.9, 1.0)
  16049. ];
  16050. },
  16051. enumerable: true,
  16052. configurable: true
  16053. });
  16054. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  16055. get: function () {
  16056. return [
  16057. new BABYLON.Color3(0.5, 1.0, 0.0),
  16058. new BABYLON.Color3(0.5, 1.0, 0.0),
  16059. new BABYLON.Color3(0.3, 0.4, 0.0),
  16060. new BABYLON.Color3(0.5, 1.0, 0.0),
  16061. new BABYLON.Color3(0.2, 0.0, 0.0),
  16062. new BABYLON.Color3(0.5, 1.0, 0.0)
  16063. ];
  16064. },
  16065. enumerable: true,
  16066. configurable: true
  16067. });
  16068. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  16069. get: function () {
  16070. return [
  16071. new BABYLON.Color3(0.5, 0.0, 0.1),
  16072. new BABYLON.Color3(0.9, 0.0, 0.0),
  16073. new BABYLON.Color3(0.2, 0.0, 0.0),
  16074. new BABYLON.Color3(1.0, 0.9, 0.0),
  16075. new BABYLON.Color3(0.1, 0.1, 0.1),
  16076. new BABYLON.Color3(0.9, 0.9, 0.9)
  16077. ];
  16078. },
  16079. enumerable: true,
  16080. configurable: true
  16081. });
  16082. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  16083. get: function () {
  16084. return [
  16085. new BABYLON.Color3(0.1, 0.0, 0.5),
  16086. new BABYLON.Color3(0.0, 0.0, 0.5),
  16087. new BABYLON.Color3(0.1, 0.0, 0.2),
  16088. new BABYLON.Color3(0.0, 0.0, 1.0),
  16089. new BABYLON.Color3(0.1, 0.2, 0.3),
  16090. new BABYLON.Color3(0.0, 0.2, 0.9)
  16091. ];
  16092. },
  16093. enumerable: true,
  16094. configurable: true
  16095. });
  16096. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  16097. get: function () {
  16098. return this._fireColors;
  16099. },
  16100. set: function (value) {
  16101. this._fireColors = value;
  16102. this.updateShaderUniforms();
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  16108. get: function () {
  16109. return this._time;
  16110. },
  16111. set: function (value) {
  16112. this._time = value;
  16113. this.updateShaderUniforms();
  16114. },
  16115. enumerable: true,
  16116. configurable: true
  16117. });
  16118. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  16119. get: function () {
  16120. return this._speed;
  16121. },
  16122. set: function (value) {
  16123. this._speed = value;
  16124. this.updateShaderUniforms();
  16125. },
  16126. enumerable: true,
  16127. configurable: true
  16128. });
  16129. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  16130. get: function () {
  16131. return this._alphaThreshold;
  16132. },
  16133. set: function (value) {
  16134. this._alphaThreshold = value;
  16135. this.updateShaderUniforms();
  16136. },
  16137. enumerable: true,
  16138. configurable: true
  16139. });
  16140. return FireProceduralTexture;
  16141. })(BABYLON.ProceduralTexture);
  16142. BABYLON.FireProceduralTexture = FireProceduralTexture;
  16143. var CloudProceduralTexture = (function (_super) {
  16144. __extends(CloudProceduralTexture, _super);
  16145. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16146. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  16147. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  16148. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  16149. this.updateShaderUniforms();
  16150. this.refreshRate = 0;
  16151. }
  16152. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  16153. this.setColor3("skyColor", this._skyColor);
  16154. this.setColor3("cloudColor", this._cloudColor);
  16155. };
  16156. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  16157. get: function () {
  16158. return this._skyColor;
  16159. },
  16160. set: function (value) {
  16161. this._skyColor = value;
  16162. this.updateShaderUniforms();
  16163. },
  16164. enumerable: true,
  16165. configurable: true
  16166. });
  16167. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  16168. get: function () {
  16169. return this._cloudColor;
  16170. },
  16171. set: function (value) {
  16172. this._cloudColor = value;
  16173. this.updateShaderUniforms();
  16174. },
  16175. enumerable: true,
  16176. configurable: true
  16177. });
  16178. return CloudProceduralTexture;
  16179. })(BABYLON.ProceduralTexture);
  16180. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  16181. var GrassProceduralTexture = (function (_super) {
  16182. __extends(GrassProceduralTexture, _super);
  16183. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16184. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  16185. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  16186. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  16187. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  16188. this._groundColor = new BABYLON.Color3(1, 1, 1);
  16189. this._grassColors = [
  16190. new BABYLON.Color3(0.29, 0.38, 0.02),
  16191. new BABYLON.Color3(0.36, 0.49, 0.09),
  16192. new BABYLON.Color3(0.51, 0.6, 0.28)
  16193. ];
  16194. this.updateShaderUniforms();
  16195. this.refreshRate = 0;
  16196. }
  16197. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  16198. this.setColor3("herb1Color", this._grassColors[0]);
  16199. this.setColor3("herb2Color", this._grassColors[1]);
  16200. this.setColor3("herb3Color", this._grassColors[2]);
  16201. this.setColor3("groundColor", this._groundColor);
  16202. };
  16203. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  16204. get: function () {
  16205. return this._grassColors;
  16206. },
  16207. set: function (value) {
  16208. this._grassColors = value;
  16209. this.updateShaderUniforms();
  16210. },
  16211. enumerable: true,
  16212. configurable: true
  16213. });
  16214. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  16215. get: function () {
  16216. return this._groundColor;
  16217. },
  16218. set: function (value) {
  16219. this.groundColor = value;
  16220. this.updateShaderUniforms();
  16221. },
  16222. enumerable: true,
  16223. configurable: true
  16224. });
  16225. return GrassProceduralTexture;
  16226. })(BABYLON.ProceduralTexture);
  16227. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  16228. var RoadProceduralTexture = (function (_super) {
  16229. __extends(RoadProceduralTexture, _super);
  16230. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16231. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  16232. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  16233. this.updateShaderUniforms();
  16234. this.refreshRate = 0;
  16235. }
  16236. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  16237. this.setColor3("roadColor", this._roadColor);
  16238. };
  16239. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  16240. get: function () {
  16241. return this._roadColor;
  16242. },
  16243. set: function (value) {
  16244. this._roadColor = value;
  16245. this.updateShaderUniforms();
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. return RoadProceduralTexture;
  16251. })(BABYLON.ProceduralTexture);
  16252. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  16253. var BrickProceduralTexture = (function (_super) {
  16254. __extends(BrickProceduralTexture, _super);
  16255. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16256. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  16257. this._numberOfBricksHeight = 15;
  16258. this._numberOfBricksWidth = 5;
  16259. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16260. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16261. this.updateShaderUniforms();
  16262. this.refreshRate = 0;
  16263. }
  16264. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  16265. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  16266. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  16267. this.setColor3("brickColor", this._brickColor);
  16268. this.setColor3("jointColor", this._jointColor);
  16269. };
  16270. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  16271. get: function () {
  16272. return this._numberOfBricksHeight;
  16273. },
  16274. set: function (value) {
  16275. this._numberOfBricksHeight = value;
  16276. this.updateShaderUniforms();
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  16282. get: function () {
  16283. return this._numberOfBricksWidth;
  16284. },
  16285. set: function (value) {
  16286. this._numberOfBricksHeight = value;
  16287. this.updateShaderUniforms();
  16288. },
  16289. enumerable: true,
  16290. configurable: true
  16291. });
  16292. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  16293. get: function () {
  16294. return this._jointColor;
  16295. },
  16296. set: function (value) {
  16297. this._jointColor = value;
  16298. this.updateShaderUniforms();
  16299. },
  16300. enumerable: true,
  16301. configurable: true
  16302. });
  16303. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  16304. get: function () {
  16305. return this._brickColor;
  16306. },
  16307. set: function (value) {
  16308. this._brickColor = value;
  16309. this.updateShaderUniforms();
  16310. },
  16311. enumerable: true,
  16312. configurable: true
  16313. });
  16314. return BrickProceduralTexture;
  16315. })(BABYLON.ProceduralTexture);
  16316. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  16317. var MarbleProceduralTexture = (function (_super) {
  16318. __extends(MarbleProceduralTexture, _super);
  16319. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16320. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  16321. this._numberOfTilesHeight = 3;
  16322. this._numberOfTilesWidth = 3;
  16323. this._amplitude = 9.0;
  16324. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16325. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16326. this.updateShaderUniforms();
  16327. this.refreshRate = 0;
  16328. }
  16329. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  16330. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  16331. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  16332. this.setFloat("amplitude", this._amplitude);
  16333. this.setColor3("marbleColor", this._marbleColor);
  16334. this.setColor3("jointColor", this._jointColor);
  16335. };
  16336. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  16337. get: function () {
  16338. return this._numberOfTilesHeight;
  16339. },
  16340. set: function (value) {
  16341. this._numberOfTilesHeight = value;
  16342. this.updateShaderUniforms();
  16343. },
  16344. enumerable: true,
  16345. configurable: true
  16346. });
  16347. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  16348. get: function () {
  16349. return this._numberOfTilesWidth;
  16350. },
  16351. set: function (value) {
  16352. this._numberOfTilesWidth = value;
  16353. this.updateShaderUniforms();
  16354. },
  16355. enumerable: true,
  16356. configurable: true
  16357. });
  16358. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  16359. get: function () {
  16360. return this._jointColor;
  16361. },
  16362. set: function (value) {
  16363. this._jointColor = value;
  16364. this.updateShaderUniforms();
  16365. },
  16366. enumerable: true,
  16367. configurable: true
  16368. });
  16369. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  16370. get: function () {
  16371. return this._marbleColor;
  16372. },
  16373. set: function (value) {
  16374. this._marbleColor = value;
  16375. this.updateShaderUniforms();
  16376. },
  16377. enumerable: true,
  16378. configurable: true
  16379. });
  16380. return MarbleProceduralTexture;
  16381. })(BABYLON.ProceduralTexture);
  16382. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  16383. })(BABYLON || (BABYLON = {}));
  16384. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  16385. var BABYLON;
  16386. (function (BABYLON) {
  16387. var EffectFallbacks = (function () {
  16388. function EffectFallbacks() {
  16389. this._defines = {};
  16390. this._currentRank = 32;
  16391. this._maxRank = -1;
  16392. }
  16393. EffectFallbacks.prototype.addFallback = function (rank, define) {
  16394. if (!this._defines[rank]) {
  16395. if (rank < this._currentRank) {
  16396. this._currentRank = rank;
  16397. }
  16398. if (rank > this._maxRank) {
  16399. this._maxRank = rank;
  16400. }
  16401. this._defines[rank] = new Array();
  16402. }
  16403. this._defines[rank].push(define);
  16404. };
  16405. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  16406. get: function () {
  16407. return this._currentRank <= this._maxRank;
  16408. },
  16409. enumerable: true,
  16410. configurable: true
  16411. });
  16412. EffectFallbacks.prototype.reduce = function (currentDefines) {
  16413. var currentFallbacks = this._defines[this._currentRank];
  16414. for (var index = 0; index < currentFallbacks.length; index++) {
  16415. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  16416. }
  16417. this._currentRank++;
  16418. return currentDefines;
  16419. };
  16420. return EffectFallbacks;
  16421. })();
  16422. BABYLON.EffectFallbacks = EffectFallbacks;
  16423. var Effect = (function () {
  16424. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  16425. var _this = this;
  16426. this._isReady = false;
  16427. this._compilationError = "";
  16428. this._valueCache = [];
  16429. this._engine = engine;
  16430. this.name = baseName;
  16431. this.defines = defines;
  16432. this._uniformsNames = uniformsNames.concat(samplers);
  16433. this._samplers = samplers;
  16434. this._attributesNames = attributesNames;
  16435. this.onError = onError;
  16436. this.onCompiled = onCompiled;
  16437. var vertexSource;
  16438. var fragmentSource;
  16439. if (baseName.vertexElement) {
  16440. vertexSource = document.getElementById(baseName.vertexElement);
  16441. if (!vertexSource) {
  16442. vertexSource = baseName.vertexElement;
  16443. }
  16444. }
  16445. else {
  16446. vertexSource = baseName.vertex || baseName;
  16447. }
  16448. if (baseName.fragmentElement) {
  16449. fragmentSource = document.getElementById(baseName.fragmentElement);
  16450. if (!fragmentSource) {
  16451. fragmentSource = baseName.fragmentElement;
  16452. }
  16453. }
  16454. else {
  16455. fragmentSource = baseName.fragment || baseName;
  16456. }
  16457. this._loadVertexShader(vertexSource, function (vertexCode) {
  16458. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  16459. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  16460. });
  16461. });
  16462. }
  16463. // Properties
  16464. Effect.prototype.isReady = function () {
  16465. return this._isReady;
  16466. };
  16467. Effect.prototype.getProgram = function () {
  16468. return this._program;
  16469. };
  16470. Effect.prototype.getAttributesNames = function () {
  16471. return this._attributesNames;
  16472. };
  16473. Effect.prototype.getAttributeLocation = function (index) {
  16474. return this._attributes[index];
  16475. };
  16476. Effect.prototype.getAttributeLocationByName = function (name) {
  16477. var index = this._attributesNames.indexOf(name);
  16478. return this._attributes[index];
  16479. };
  16480. Effect.prototype.getAttributesCount = function () {
  16481. return this._attributes.length;
  16482. };
  16483. Effect.prototype.getUniformIndex = function (uniformName) {
  16484. return this._uniformsNames.indexOf(uniformName);
  16485. };
  16486. Effect.prototype.getUniform = function (uniformName) {
  16487. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  16488. };
  16489. Effect.prototype.getSamplers = function () {
  16490. return this._samplers;
  16491. };
  16492. Effect.prototype.getCompilationError = function () {
  16493. return this._compilationError;
  16494. };
  16495. // Methods
  16496. Effect.prototype._loadVertexShader = function (vertex, callback) {
  16497. // DOM element ?
  16498. if (vertex instanceof HTMLElement) {
  16499. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  16500. callback(vertexCode);
  16501. return;
  16502. }
  16503. // Is in local store ?
  16504. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  16505. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  16506. return;
  16507. }
  16508. var vertexShaderUrl;
  16509. if (vertex[0] === ".") {
  16510. vertexShaderUrl = vertex;
  16511. }
  16512. else {
  16513. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  16514. }
  16515. // Vertex shader
  16516. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  16517. };
  16518. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  16519. // DOM element ?
  16520. if (fragment instanceof HTMLElement) {
  16521. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  16522. callback(fragmentCode);
  16523. return;
  16524. }
  16525. // Is in local store ?
  16526. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  16527. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  16528. return;
  16529. }
  16530. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  16531. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  16532. return;
  16533. }
  16534. var fragmentShaderUrl;
  16535. if (fragment[0] === ".") {
  16536. fragmentShaderUrl = fragment;
  16537. }
  16538. else {
  16539. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  16540. }
  16541. // Fragment shader
  16542. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  16543. };
  16544. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  16545. try {
  16546. var engine = this._engine;
  16547. if (!engine.getCaps().highPrecisionShaderSupported) {
  16548. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16549. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16550. }
  16551. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  16552. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  16553. this._attributes = engine.getAttributes(this._program, attributesNames);
  16554. for (var index = 0; index < this._samplers.length; index++) {
  16555. var sampler = this.getUniform(this._samplers[index]);
  16556. if (sampler == null) {
  16557. this._samplers.splice(index, 1);
  16558. index--;
  16559. }
  16560. }
  16561. engine.bindSamplers(this);
  16562. this._isReady = true;
  16563. if (this.onCompiled) {
  16564. this.onCompiled(this);
  16565. }
  16566. }
  16567. catch (e) {
  16568. // Is it a problem with precision?
  16569. if (e.message.indexOf("highp") !== -1) {
  16570. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16571. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16572. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16573. return;
  16574. }
  16575. // Let's go through fallbacks then
  16576. if (fallbacks && fallbacks.isMoreFallbacks) {
  16577. defines = fallbacks.reduce(defines);
  16578. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16579. }
  16580. else {
  16581. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  16582. BABYLON.Tools.Error("Defines: " + defines);
  16583. BABYLON.Tools.Error("Error: " + e.message);
  16584. this._compilationError = e.message;
  16585. if (this.onError) {
  16586. this.onError(this, this._compilationError);
  16587. }
  16588. }
  16589. }
  16590. };
  16591. Effect.prototype._bindTexture = function (channel, texture) {
  16592. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  16593. };
  16594. Effect.prototype.setTexture = function (channel, texture) {
  16595. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  16596. };
  16597. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16598. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  16599. };
  16600. //public _cacheMatrix(uniformName, matrix) {
  16601. // if (!this._valueCache[uniformName]) {
  16602. // this._valueCache[uniformName] = new BABYLON.Matrix();
  16603. // }
  16604. // for (var index = 0; index < 16; index++) {
  16605. // this._valueCache[uniformName].m[index] = matrix.m[index];
  16606. // }
  16607. //};
  16608. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  16609. if (!this._valueCache[uniformName]) {
  16610. this._valueCache[uniformName] = [x, y];
  16611. return;
  16612. }
  16613. this._valueCache[uniformName][0] = x;
  16614. this._valueCache[uniformName][1] = y;
  16615. };
  16616. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  16617. if (!this._valueCache[uniformName]) {
  16618. this._valueCache[uniformName] = [x, y, z];
  16619. return;
  16620. }
  16621. this._valueCache[uniformName][0] = x;
  16622. this._valueCache[uniformName][1] = y;
  16623. this._valueCache[uniformName][2] = z;
  16624. };
  16625. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  16626. if (!this._valueCache[uniformName]) {
  16627. this._valueCache[uniformName] = [x, y, z, w];
  16628. return;
  16629. }
  16630. this._valueCache[uniformName][0] = x;
  16631. this._valueCache[uniformName][1] = y;
  16632. this._valueCache[uniformName][2] = z;
  16633. this._valueCache[uniformName][3] = w;
  16634. };
  16635. Effect.prototype.setArray = function (uniformName, array) {
  16636. this._engine.setArray(this.getUniform(uniformName), array);
  16637. return this;
  16638. };
  16639. Effect.prototype.setArray2 = function (uniformName, array) {
  16640. this._engine.setArray2(this.getUniform(uniformName), array);
  16641. return this;
  16642. };
  16643. Effect.prototype.setArray3 = function (uniformName, array) {
  16644. this._engine.setArray3(this.getUniform(uniformName), array);
  16645. return this;
  16646. };
  16647. Effect.prototype.setArray4 = function (uniformName, array) {
  16648. this._engine.setArray4(this.getUniform(uniformName), array);
  16649. return this;
  16650. };
  16651. Effect.prototype.setMatrices = function (uniformName, matrices) {
  16652. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  16653. return this;
  16654. };
  16655. Effect.prototype.setMatrix = function (uniformName, matrix) {
  16656. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  16657. // return;
  16658. //this._cacheMatrix(uniformName, matrix);
  16659. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  16660. return this;
  16661. };
  16662. Effect.prototype.setFloat = function (uniformName, value) {
  16663. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  16664. return this;
  16665. this._valueCache[uniformName] = value;
  16666. this._engine.setFloat(this.getUniform(uniformName), value);
  16667. return this;
  16668. };
  16669. Effect.prototype.setBool = function (uniformName, bool) {
  16670. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  16671. return this;
  16672. this._valueCache[uniformName] = bool;
  16673. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  16674. return this;
  16675. };
  16676. Effect.prototype.setVector2 = function (uniformName, vector2) {
  16677. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  16678. return this;
  16679. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  16680. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  16681. return this;
  16682. };
  16683. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  16684. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  16685. return this;
  16686. this._cacheFloat2(uniformName, x, y);
  16687. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  16688. return this;
  16689. };
  16690. Effect.prototype.setVector3 = function (uniformName, vector3) {
  16691. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  16692. return this;
  16693. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  16694. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  16695. return this;
  16696. };
  16697. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  16698. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  16699. return this;
  16700. this._cacheFloat3(uniformName, x, y, z);
  16701. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  16702. return this;
  16703. };
  16704. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  16705. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  16706. return this;
  16707. this._cacheFloat4(uniformName, x, y, z, w);
  16708. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  16709. return this;
  16710. };
  16711. Effect.prototype.setColor3 = function (uniformName, color3) {
  16712. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  16713. return this;
  16714. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  16715. this._engine.setColor3(this.getUniform(uniformName), color3);
  16716. return this;
  16717. };
  16718. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  16719. 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)
  16720. return this;
  16721. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  16722. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  16723. return this;
  16724. };
  16725. // Statics
  16726. Effect.ShadersStore = {};
  16727. return Effect;
  16728. })();
  16729. BABYLON.Effect = Effect;
  16730. })(BABYLON || (BABYLON = {}));
  16731. //# sourceMappingURL=babylon.effect.js.map
  16732. var BABYLON;
  16733. (function (BABYLON) {
  16734. var Material = (function () {
  16735. function Material(name, scene, doNotAdd) {
  16736. this.name = name;
  16737. this.checkReadyOnEveryCall = true;
  16738. this.checkReadyOnlyOnce = false;
  16739. this.state = "";
  16740. this.alpha = 1.0;
  16741. this.backFaceCulling = true;
  16742. this._wasPreviouslyReady = false;
  16743. this._fillMode = Material.TriangleFillMode;
  16744. this.pointSize = 1.0;
  16745. this.zOffset = 0;
  16746. this.id = name;
  16747. this._scene = scene;
  16748. if (!doNotAdd) {
  16749. scene.materials.push(this);
  16750. }
  16751. }
  16752. Object.defineProperty(Material, "TriangleFillMode", {
  16753. get: function () {
  16754. return Material._TriangleFillMode;
  16755. },
  16756. enumerable: true,
  16757. configurable: true
  16758. });
  16759. Object.defineProperty(Material, "WireFrameFillMode", {
  16760. get: function () {
  16761. return Material._WireFrameFillMode;
  16762. },
  16763. enumerable: true,
  16764. configurable: true
  16765. });
  16766. Object.defineProperty(Material, "PointFillMode", {
  16767. get: function () {
  16768. return Material._PointFillMode;
  16769. },
  16770. enumerable: true,
  16771. configurable: true
  16772. });
  16773. Object.defineProperty(Material.prototype, "wireframe", {
  16774. get: function () {
  16775. return this._fillMode === Material.WireFrameFillMode;
  16776. },
  16777. set: function (value) {
  16778. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  16779. },
  16780. enumerable: true,
  16781. configurable: true
  16782. });
  16783. Object.defineProperty(Material.prototype, "pointsCloud", {
  16784. get: function () {
  16785. return this._fillMode === Material.PointFillMode;
  16786. },
  16787. set: function (value) {
  16788. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  16789. },
  16790. enumerable: true,
  16791. configurable: true
  16792. });
  16793. Object.defineProperty(Material.prototype, "fillMode", {
  16794. get: function () {
  16795. return this._fillMode;
  16796. },
  16797. set: function (value) {
  16798. this._fillMode = value;
  16799. },
  16800. enumerable: true,
  16801. configurable: true
  16802. });
  16803. Material.prototype.isReady = function (mesh, useInstances) {
  16804. return true;
  16805. };
  16806. Material.prototype.getEffect = function () {
  16807. return this._effect;
  16808. };
  16809. Material.prototype.getScene = function () {
  16810. return this._scene;
  16811. };
  16812. Material.prototype.needAlphaBlending = function () {
  16813. return (this.alpha < 1.0);
  16814. };
  16815. Material.prototype.needAlphaTesting = function () {
  16816. return false;
  16817. };
  16818. Material.prototype.getAlphaTestTexture = function () {
  16819. return null;
  16820. };
  16821. Material.prototype.trackCreation = function (onCompiled, onError) {
  16822. };
  16823. Material.prototype._preBind = function () {
  16824. var engine = this._scene.getEngine();
  16825. engine.enableEffect(this._effect);
  16826. engine.setState(this.backFaceCulling, this.zOffset);
  16827. };
  16828. Material.prototype.bind = function (world, mesh) {
  16829. this._scene._cachedMaterial = this;
  16830. if (this.onBind) {
  16831. this.onBind(this, mesh);
  16832. }
  16833. };
  16834. Material.prototype.bindOnlyWorldMatrix = function (world) {
  16835. };
  16836. Material.prototype.unbind = function () {
  16837. };
  16838. Material.prototype.dispose = function (forceDisposeEffect) {
  16839. // Remove from scene
  16840. var index = this._scene.materials.indexOf(this);
  16841. this._scene.materials.splice(index, 1);
  16842. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  16843. if (forceDisposeEffect && this._effect) {
  16844. this._scene.getEngine()._releaseEffect(this._effect);
  16845. this._effect = null;
  16846. }
  16847. // Callback
  16848. if (this.onDispose) {
  16849. this.onDispose();
  16850. }
  16851. };
  16852. Material._TriangleFillMode = 0;
  16853. Material._WireFrameFillMode = 1;
  16854. Material._PointFillMode = 2;
  16855. return Material;
  16856. })();
  16857. BABYLON.Material = Material;
  16858. })(BABYLON || (BABYLON = {}));
  16859. //# sourceMappingURL=babylon.material.js.map
  16860. var __extends = this.__extends || function (d, b) {
  16861. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16862. function __() { this.constructor = d; }
  16863. __.prototype = b.prototype;
  16864. d.prototype = new __();
  16865. };
  16866. var BABYLON;
  16867. (function (BABYLON) {
  16868. var maxSimultaneousLights = 4;
  16869. var FresnelParameters = (function () {
  16870. function FresnelParameters() {
  16871. this.isEnabled = true;
  16872. this.leftColor = BABYLON.Color3.White();
  16873. this.rightColor = BABYLON.Color3.Black();
  16874. this.bias = 0;
  16875. this.power = 1;
  16876. }
  16877. return FresnelParameters;
  16878. })();
  16879. BABYLON.FresnelParameters = FresnelParameters;
  16880. var StandardMaterial = (function (_super) {
  16881. __extends(StandardMaterial, _super);
  16882. function StandardMaterial(name, scene) {
  16883. var _this = this;
  16884. _super.call(this, name, scene);
  16885. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16886. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  16887. this.specularColor = new BABYLON.Color3(1, 1, 1);
  16888. this.specularPower = 64;
  16889. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  16890. this.useAlphaFromDiffuseTexture = false;
  16891. this.useSpecularOverAlpha = true;
  16892. this.fogEnabled = true;
  16893. this._cachedDefines = null;
  16894. this._renderTargets = new BABYLON.SmartArray(16);
  16895. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  16896. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  16897. this._scaledDiffuse = new BABYLON.Color3();
  16898. this._scaledSpecular = new BABYLON.Color3();
  16899. this.getRenderTargetTextures = function () {
  16900. _this._renderTargets.reset();
  16901. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  16902. _this._renderTargets.push(_this.reflectionTexture);
  16903. }
  16904. return _this._renderTargets;
  16905. };
  16906. }
  16907. StandardMaterial.prototype.needAlphaBlending = function () {
  16908. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  16909. };
  16910. StandardMaterial.prototype.needAlphaTesting = function () {
  16911. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  16912. };
  16913. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  16914. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  16915. };
  16916. StandardMaterial.prototype.getAlphaTestTexture = function () {
  16917. return this.diffuseTexture;
  16918. };
  16919. // Methods
  16920. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  16921. if (this.checkReadyOnlyOnce) {
  16922. if (this._wasPreviouslyReady) {
  16923. return true;
  16924. }
  16925. }
  16926. var scene = this.getScene();
  16927. if (!this.checkReadyOnEveryCall) {
  16928. if (this._renderId === scene.getRenderId()) {
  16929. return true;
  16930. }
  16931. }
  16932. var engine = scene.getEngine();
  16933. var defines = [];
  16934. var fallbacks = new BABYLON.EffectFallbacks();
  16935. var needNormals = false;
  16936. var needUVs = false;
  16937. // Textures
  16938. if (scene.texturesEnabled) {
  16939. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  16940. if (!this.diffuseTexture.isReady()) {
  16941. return false;
  16942. }
  16943. else {
  16944. needUVs = true;
  16945. defines.push("#define DIFFUSE");
  16946. }
  16947. }
  16948. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  16949. if (!this.ambientTexture.isReady()) {
  16950. return false;
  16951. }
  16952. else {
  16953. needUVs = true;
  16954. defines.push("#define AMBIENT");
  16955. }
  16956. }
  16957. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  16958. if (!this.opacityTexture.isReady()) {
  16959. return false;
  16960. }
  16961. else {
  16962. needUVs = true;
  16963. defines.push("#define OPACITY");
  16964. if (this.opacityTexture.getAlphaFromRGB) {
  16965. defines.push("#define OPACITYRGB");
  16966. }
  16967. }
  16968. }
  16969. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  16970. if (!this.reflectionTexture.isReady()) {
  16971. return false;
  16972. }
  16973. else {
  16974. needNormals = true;
  16975. needUVs = true;
  16976. defines.push("#define REFLECTION");
  16977. fallbacks.addFallback(0, "REFLECTION");
  16978. }
  16979. }
  16980. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  16981. if (!this.emissiveTexture.isReady()) {
  16982. return false;
  16983. }
  16984. else {
  16985. needUVs = true;
  16986. defines.push("#define EMISSIVE");
  16987. }
  16988. }
  16989. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  16990. if (!this.specularTexture.isReady()) {
  16991. return false;
  16992. }
  16993. else {
  16994. needUVs = true;
  16995. defines.push("#define SPECULAR");
  16996. fallbacks.addFallback(0, "SPECULAR");
  16997. }
  16998. }
  16999. }
  17000. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  17001. if (!this.bumpTexture.isReady()) {
  17002. return false;
  17003. }
  17004. else {
  17005. needUVs = true;
  17006. defines.push("#define BUMP");
  17007. fallbacks.addFallback(0, "BUMP");
  17008. }
  17009. }
  17010. // Effect
  17011. if (this.useSpecularOverAlpha) {
  17012. defines.push("#define SPECULAROVERALPHA");
  17013. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  17014. }
  17015. if (scene.clipPlane) {
  17016. defines.push("#define CLIPPLANE");
  17017. }
  17018. if (engine.getAlphaTesting()) {
  17019. defines.push("#define ALPHATEST");
  17020. }
  17021. if (this._shouldUseAlphaFromDiffuseTexture()) {
  17022. defines.push("#define ALPHAFROMDIFFUSE");
  17023. }
  17024. // Point size
  17025. if (this.pointsCloud || scene.forcePointsCloud) {
  17026. defines.push("#define POINTSIZE");
  17027. }
  17028. // Fog
  17029. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  17030. defines.push("#define FOG");
  17031. fallbacks.addFallback(1, "FOG");
  17032. }
  17033. var shadowsActivated = false;
  17034. var lightIndex = 0;
  17035. if (scene.lightsEnabled) {
  17036. for (var index = 0; index < scene.lights.length; index++) {
  17037. var light = scene.lights[index];
  17038. if (!light.isEnabled()) {
  17039. continue;
  17040. }
  17041. // Excluded check
  17042. if (light._excludedMeshesIds.length > 0) {
  17043. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  17044. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  17045. if (excludedMesh) {
  17046. light.excludedMeshes.push(excludedMesh);
  17047. }
  17048. }
  17049. light._excludedMeshesIds = [];
  17050. }
  17051. // Included check
  17052. if (light._includedOnlyMeshesIds.length > 0) {
  17053. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  17054. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  17055. if (includedOnlyMesh) {
  17056. light.includedOnlyMeshes.push(includedOnlyMesh);
  17057. }
  17058. }
  17059. light._includedOnlyMeshesIds = [];
  17060. }
  17061. if (!light.canAffectMesh(mesh)) {
  17062. continue;
  17063. }
  17064. needNormals = true;
  17065. defines.push("#define LIGHT" + lightIndex);
  17066. if (lightIndex > 0) {
  17067. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  17068. }
  17069. var type;
  17070. if (light instanceof BABYLON.SpotLight) {
  17071. type = "#define SPOTLIGHT" + lightIndex;
  17072. }
  17073. else if (light instanceof BABYLON.HemisphericLight) {
  17074. type = "#define HEMILIGHT" + lightIndex;
  17075. }
  17076. else {
  17077. type = "#define POINTDIRLIGHT" + lightIndex;
  17078. }
  17079. defines.push(type);
  17080. if (lightIndex > 0) {
  17081. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  17082. }
  17083. // Shadows
  17084. if (scene.shadowsEnabled) {
  17085. var shadowGenerator = light.getShadowGenerator();
  17086. if (mesh && mesh.receiveShadows && shadowGenerator) {
  17087. defines.push("#define SHADOW" + lightIndex);
  17088. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  17089. if (!shadowsActivated) {
  17090. defines.push("#define SHADOWS");
  17091. shadowsActivated = true;
  17092. }
  17093. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  17094. defines.push("#define SHADOWVSM" + lightIndex);
  17095. if (lightIndex > 0) {
  17096. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  17097. }
  17098. }
  17099. if (shadowGenerator.usePoissonSampling) {
  17100. defines.push("#define SHADOWPCF" + lightIndex);
  17101. if (lightIndex > 0) {
  17102. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  17103. }
  17104. }
  17105. }
  17106. }
  17107. lightIndex++;
  17108. if (lightIndex === maxSimultaneousLights)
  17109. break;
  17110. }
  17111. }
  17112. if (StandardMaterial.FresnelEnabled) {
  17113. // Fresnel
  17114. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  17115. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  17116. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  17117. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17118. var fresnelRank = 1;
  17119. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17120. defines.push("#define DIFFUSEFRESNEL");
  17121. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  17122. fresnelRank++;
  17123. }
  17124. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17125. defines.push("#define OPACITYFRESNEL");
  17126. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  17127. fresnelRank++;
  17128. }
  17129. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17130. defines.push("#define REFLECTIONFRESNEL");
  17131. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  17132. fresnelRank++;
  17133. }
  17134. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17135. defines.push("#define EMISSIVEFRESNEL");
  17136. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  17137. fresnelRank++;
  17138. }
  17139. needNormals = true;
  17140. defines.push("#define FRESNEL");
  17141. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  17142. }
  17143. }
  17144. // Attribs
  17145. var attribs = [BABYLON.VertexBuffer.PositionKind];
  17146. if (mesh) {
  17147. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17148. attribs.push(BABYLON.VertexBuffer.NormalKind);
  17149. defines.push("#define NORMAL");
  17150. }
  17151. if (needUVs) {
  17152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17153. attribs.push(BABYLON.VertexBuffer.UVKind);
  17154. defines.push("#define UV1");
  17155. }
  17156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17157. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  17158. defines.push("#define UV2");
  17159. }
  17160. }
  17161. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17162. attribs.push(BABYLON.VertexBuffer.ColorKind);
  17163. defines.push("#define VERTEXCOLOR");
  17164. if (mesh.hasVertexAlpha) {
  17165. defines.push("#define VERTEXALPHA");
  17166. }
  17167. }
  17168. if (mesh.useBones) {
  17169. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17170. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17171. defines.push("#define BONES");
  17172. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  17173. defines.push("#define BONES4");
  17174. fallbacks.addFallback(0, "BONES4");
  17175. }
  17176. // Instances
  17177. if (useInstances) {
  17178. defines.push("#define INSTANCES");
  17179. attribs.push("world0");
  17180. attribs.push("world1");
  17181. attribs.push("world2");
  17182. attribs.push("world3");
  17183. }
  17184. }
  17185. // Get correct effect
  17186. var join = defines.join("\n");
  17187. if (this._cachedDefines !== join) {
  17188. this._cachedDefines = join;
  17189. scene.resetCachedMaterial();
  17190. // Legacy browser patch
  17191. var shaderName = "default";
  17192. if (!scene.getEngine().getCaps().standardDerivatives) {
  17193. shaderName = "legacydefault";
  17194. }
  17195. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  17196. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  17197. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  17198. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  17199. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  17200. "vFogInfos", "vFogColor", "pointSize",
  17201. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  17202. "mBones",
  17203. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  17204. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  17205. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  17206. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  17207. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  17208. ], join, fallbacks, this.onCompiled, this.onError);
  17209. }
  17210. if (!this._effect.isReady()) {
  17211. return false;
  17212. }
  17213. this._renderId = scene.getRenderId();
  17214. this._wasPreviouslyReady = true;
  17215. return true;
  17216. };
  17217. StandardMaterial.prototype.unbind = function () {
  17218. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  17219. this._effect.setTexture("reflection2DSampler", null);
  17220. }
  17221. };
  17222. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  17223. this._effect.setMatrix("world", world);
  17224. };
  17225. StandardMaterial.prototype.bind = function (world, mesh) {
  17226. var scene = this.getScene();
  17227. // Matrices
  17228. this.bindOnlyWorldMatrix(world);
  17229. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  17230. // Bones
  17231. if (mesh && mesh.useBones) {
  17232. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  17233. }
  17234. if (scene.getCachedMaterial() !== this) {
  17235. if (StandardMaterial.FresnelEnabled) {
  17236. // Fresnel
  17237. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17238. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  17239. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  17240. }
  17241. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17242. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  17243. }
  17244. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17245. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  17246. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  17247. }
  17248. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17249. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  17250. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  17251. }
  17252. }
  17253. // Textures
  17254. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17255. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  17256. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  17257. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  17258. }
  17259. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17260. this._effect.setTexture("ambientSampler", this.ambientTexture);
  17261. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  17262. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  17263. }
  17264. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17265. this._effect.setTexture("opacitySampler", this.opacityTexture);
  17266. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  17267. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  17268. }
  17269. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17270. if (this.reflectionTexture.isCube) {
  17271. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  17272. }
  17273. else {
  17274. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  17275. }
  17276. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  17277. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  17278. }
  17279. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17280. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  17281. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  17282. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  17283. }
  17284. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  17285. this._effect.setTexture("specularSampler", this.specularTexture);
  17286. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  17287. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  17288. }
  17289. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  17290. this._effect.setTexture("bumpSampler", this.bumpTexture);
  17291. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  17292. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  17293. }
  17294. // Clip plane
  17295. if (scene.clipPlane) {
  17296. var clipPlane = scene.clipPlane;
  17297. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  17298. }
  17299. // Point size
  17300. if (this.pointsCloud) {
  17301. this._effect.setFloat("pointSize", this.pointSize);
  17302. }
  17303. // Colors
  17304. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  17305. // Scaling down color according to emissive
  17306. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17307. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17308. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17309. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  17310. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  17311. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  17312. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  17313. }
  17314. // Scaling down color according to emissive
  17315. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17316. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17317. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17318. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  17319. if (scene.lightsEnabled) {
  17320. var lightIndex = 0;
  17321. for (var index = 0; index < scene.lights.length; index++) {
  17322. var light = scene.lights[index];
  17323. if (!light.isEnabled()) {
  17324. continue;
  17325. }
  17326. if (!light.canAffectMesh(mesh)) {
  17327. continue;
  17328. }
  17329. if (light instanceof BABYLON.PointLight) {
  17330. // Point Light
  17331. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17332. }
  17333. else if (light instanceof BABYLON.DirectionalLight) {
  17334. // Directional Light
  17335. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17336. }
  17337. else if (light instanceof BABYLON.SpotLight) {
  17338. // Spot Light
  17339. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  17340. }
  17341. else if (light instanceof BABYLON.HemisphericLight) {
  17342. // Hemispheric Light
  17343. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  17344. }
  17345. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  17346. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  17347. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  17348. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  17349. // Shadows
  17350. if (scene.shadowsEnabled) {
  17351. var shadowGenerator = light.getShadowGenerator();
  17352. if (mesh.receiveShadows && shadowGenerator) {
  17353. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  17354. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  17355. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  17356. }
  17357. }
  17358. lightIndex++;
  17359. if (lightIndex === maxSimultaneousLights)
  17360. break;
  17361. }
  17362. }
  17363. // View
  17364. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  17365. this._effect.setMatrix("view", scene.getViewMatrix());
  17366. }
  17367. // Fog
  17368. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  17369. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  17370. this._effect.setColor3("vFogColor", scene.fogColor);
  17371. }
  17372. _super.prototype.bind.call(this, world, mesh);
  17373. };
  17374. StandardMaterial.prototype.getAnimatables = function () {
  17375. var results = [];
  17376. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  17377. results.push(this.diffuseTexture);
  17378. }
  17379. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  17380. results.push(this.ambientTexture);
  17381. }
  17382. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  17383. results.push(this.opacityTexture);
  17384. }
  17385. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  17386. results.push(this.reflectionTexture);
  17387. }
  17388. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  17389. results.push(this.emissiveTexture);
  17390. }
  17391. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  17392. results.push(this.specularTexture);
  17393. }
  17394. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  17395. results.push(this.bumpTexture);
  17396. }
  17397. return results;
  17398. };
  17399. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  17400. if (this.diffuseTexture) {
  17401. this.diffuseTexture.dispose();
  17402. }
  17403. if (this.ambientTexture) {
  17404. this.ambientTexture.dispose();
  17405. }
  17406. if (this.opacityTexture) {
  17407. this.opacityTexture.dispose();
  17408. }
  17409. if (this.reflectionTexture) {
  17410. this.reflectionTexture.dispose();
  17411. }
  17412. if (this.emissiveTexture) {
  17413. this.emissiveTexture.dispose();
  17414. }
  17415. if (this.specularTexture) {
  17416. this.specularTexture.dispose();
  17417. }
  17418. if (this.bumpTexture) {
  17419. this.bumpTexture.dispose();
  17420. }
  17421. _super.prototype.dispose.call(this, forceDisposeEffect);
  17422. };
  17423. StandardMaterial.prototype.clone = function (name) {
  17424. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  17425. // Base material
  17426. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  17427. newStandardMaterial.alpha = this.alpha;
  17428. newStandardMaterial.fillMode = this.fillMode;
  17429. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  17430. // Standard material
  17431. if (this.diffuseTexture && this.diffuseTexture.clone) {
  17432. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  17433. }
  17434. if (this.ambientTexture && this.ambientTexture.clone) {
  17435. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  17436. }
  17437. if (this.opacityTexture && this.opacityTexture.clone) {
  17438. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  17439. }
  17440. if (this.reflectionTexture && this.reflectionTexture.clone) {
  17441. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  17442. }
  17443. if (this.emissiveTexture && this.emissiveTexture.clone) {
  17444. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  17445. }
  17446. if (this.specularTexture && this.specularTexture.clone) {
  17447. newStandardMaterial.specularTexture = this.specularTexture.clone();
  17448. }
  17449. if (this.bumpTexture && this.bumpTexture.clone) {
  17450. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  17451. }
  17452. newStandardMaterial.ambientColor = this.ambientColor.clone();
  17453. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  17454. newStandardMaterial.specularColor = this.specularColor.clone();
  17455. newStandardMaterial.specularPower = this.specularPower;
  17456. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  17457. return newStandardMaterial;
  17458. };
  17459. // Statics
  17460. // Flags used to enable or disable a type of texture for all Standard Materials
  17461. StandardMaterial.DiffuseTextureEnabled = true;
  17462. StandardMaterial.AmbientTextureEnabled = true;
  17463. StandardMaterial.OpacityTextureEnabled = true;
  17464. StandardMaterial.ReflectionTextureEnabled = true;
  17465. StandardMaterial.EmissiveTextureEnabled = true;
  17466. StandardMaterial.SpecularTextureEnabled = true;
  17467. StandardMaterial.BumpTextureEnabled = true;
  17468. StandardMaterial.FresnelEnabled = true;
  17469. return StandardMaterial;
  17470. })(BABYLON.Material);
  17471. BABYLON.StandardMaterial = StandardMaterial;
  17472. })(BABYLON || (BABYLON = {}));
  17473. //# sourceMappingURL=babylon.standardMaterial.js.map
  17474. var __extends = this.__extends || function (d, b) {
  17475. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17476. function __() { this.constructor = d; }
  17477. __.prototype = b.prototype;
  17478. d.prototype = new __();
  17479. };
  17480. var BABYLON;
  17481. (function (BABYLON) {
  17482. var MultiMaterial = (function (_super) {
  17483. __extends(MultiMaterial, _super);
  17484. function MultiMaterial(name, scene) {
  17485. _super.call(this, name, scene, true);
  17486. this.subMaterials = new Array();
  17487. scene.multiMaterials.push(this);
  17488. }
  17489. // Properties
  17490. MultiMaterial.prototype.getSubMaterial = function (index) {
  17491. if (index < 0 || index >= this.subMaterials.length) {
  17492. return this.getScene().defaultMaterial;
  17493. }
  17494. return this.subMaterials[index];
  17495. };
  17496. // Methods
  17497. MultiMaterial.prototype.isReady = function (mesh) {
  17498. for (var index = 0; index < this.subMaterials.length; index++) {
  17499. var subMaterial = this.subMaterials[index];
  17500. if (subMaterial) {
  17501. if (!this.subMaterials[index].isReady(mesh)) {
  17502. return false;
  17503. }
  17504. }
  17505. }
  17506. return true;
  17507. };
  17508. MultiMaterial.prototype.clone = function (name) {
  17509. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  17510. for (var index = 0; index < this.subMaterials.length; index++) {
  17511. var subMaterial = this.subMaterials[index];
  17512. newMultiMaterial.subMaterials.push(subMaterial);
  17513. }
  17514. return newMultiMaterial;
  17515. };
  17516. return MultiMaterial;
  17517. })(BABYLON.Material);
  17518. BABYLON.MultiMaterial = MultiMaterial;
  17519. })(BABYLON || (BABYLON = {}));
  17520. //# sourceMappingURL=babylon.multiMaterial.js.map
  17521. var BABYLON;
  17522. (function (BABYLON) {
  17523. var SceneLoader = (function () {
  17524. function SceneLoader() {
  17525. }
  17526. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17527. get: function () {
  17528. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17529. },
  17530. set: function (value) {
  17531. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17532. },
  17533. enumerable: true,
  17534. configurable: true
  17535. });
  17536. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17537. get: function () {
  17538. return SceneLoader._ShowLoadingScreen;
  17539. },
  17540. set: function (value) {
  17541. SceneLoader._ShowLoadingScreen = value;
  17542. },
  17543. enumerable: true,
  17544. configurable: true
  17545. });
  17546. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17547. var dotPosition = sceneFilename.lastIndexOf(".");
  17548. var queryStringPosition = sceneFilename.indexOf("?");
  17549. if (queryStringPosition === -1) {
  17550. queryStringPosition = sceneFilename.length;
  17551. }
  17552. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17553. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17554. var plugin = this._registeredPlugins[index];
  17555. if (plugin.extensions.indexOf(extension) !== -1) {
  17556. return plugin;
  17557. }
  17558. }
  17559. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17560. };
  17561. // Public functions
  17562. SceneLoader.RegisterPlugin = function (plugin) {
  17563. plugin.extensions = plugin.extensions.toLowerCase();
  17564. SceneLoader._registeredPlugins.push(plugin);
  17565. };
  17566. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17567. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17568. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17569. return;
  17570. }
  17571. var manifestChecked = function (success) {
  17572. scene.database = database;
  17573. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17574. var importMeshFromData = function (data) {
  17575. var meshes = [];
  17576. var particleSystems = [];
  17577. var skeletons = [];
  17578. try {
  17579. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17580. if (onerror) {
  17581. onerror(scene, 'unable to load the scene');
  17582. }
  17583. return;
  17584. }
  17585. }
  17586. catch (e) {
  17587. if (onerror) {
  17588. onerror(scene, e);
  17589. }
  17590. return;
  17591. }
  17592. if (onsuccess) {
  17593. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17594. onsuccess(meshes, particleSystems, skeletons);
  17595. }
  17596. };
  17597. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17598. // Direct load
  17599. importMeshFromData(sceneFilename.substr(5));
  17600. return;
  17601. }
  17602. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17603. importMeshFromData(data);
  17604. }, progressCallBack, database);
  17605. };
  17606. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17607. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17608. };
  17609. /**
  17610. * Load a scene
  17611. * @param rootUrl a string that defines the root url for scene and resources
  17612. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17613. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17614. */
  17615. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17616. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17617. };
  17618. /**
  17619. * Append a scene
  17620. * @param rootUrl a string that defines the root url for scene and resources
  17621. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17622. * @param scene is the instance of BABYLON.Scene to append to
  17623. */
  17624. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17625. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17626. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17627. return;
  17628. }
  17629. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17630. var database;
  17631. if (SceneLoader.ShowLoadingScreen) {
  17632. scene.getEngine().displayLoadingUI();
  17633. }
  17634. var loadSceneFromData = function (data) {
  17635. scene.database = database;
  17636. if (!plugin.load(scene, data, rootUrl)) {
  17637. if (onerror) {
  17638. onerror(scene);
  17639. }
  17640. scene.getEngine().hideLoadingUI();
  17641. return;
  17642. }
  17643. if (onsuccess) {
  17644. onsuccess(scene);
  17645. }
  17646. if (SceneLoader.ShowLoadingScreen) {
  17647. scene.executeWhenReady(function () {
  17648. scene.getEngine().hideLoadingUI();
  17649. });
  17650. }
  17651. };
  17652. var manifestChecked = function (success) {
  17653. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17654. };
  17655. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17656. // Direct load
  17657. loadSceneFromData(sceneFilename.substr(5));
  17658. return;
  17659. }
  17660. if (rootUrl.indexOf("file:") === -1) {
  17661. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17662. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17663. }
  17664. else {
  17665. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17666. }
  17667. };
  17668. // Flags
  17669. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17670. SceneLoader._ShowLoadingScreen = true;
  17671. // Members
  17672. SceneLoader._registeredPlugins = new Array();
  17673. return SceneLoader;
  17674. })();
  17675. BABYLON.SceneLoader = SceneLoader;
  17676. ;
  17677. })(BABYLON || (BABYLON = {}));
  17678. //# sourceMappingURL=babylon.sceneLoader.js.map
  17679. var BABYLON;
  17680. (function (BABYLON) {
  17681. var Internals;
  17682. (function (Internals) {
  17683. var checkColors4 = function (colors, count) {
  17684. // Check if color3 was used
  17685. if (colors.length === count * 3) {
  17686. var colors4 = [];
  17687. for (var index = 0; index < colors.length; index += 3) {
  17688. var newIndex = (index / 3) * 4;
  17689. colors4[newIndex] = colors[index];
  17690. colors4[newIndex + 1] = colors[index + 1];
  17691. colors4[newIndex + 2] = colors[index + 2];
  17692. colors4[newIndex + 3] = 1.0;
  17693. }
  17694. return colors4;
  17695. }
  17696. return colors;
  17697. };
  17698. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17699. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17700. texture.name = parsedTexture.name;
  17701. texture.hasAlpha = parsedTexture.hasAlpha;
  17702. texture.level = parsedTexture.level;
  17703. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17704. return texture;
  17705. };
  17706. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17707. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17708. return null;
  17709. }
  17710. if (parsedTexture.isCube) {
  17711. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17712. }
  17713. var texture;
  17714. if (parsedTexture.mirrorPlane) {
  17715. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17716. texture._waitingRenderList = parsedTexture.renderList;
  17717. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17718. }
  17719. else if (parsedTexture.isRenderTarget) {
  17720. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17721. texture._waitingRenderList = parsedTexture.renderList;
  17722. }
  17723. else {
  17724. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17725. }
  17726. texture.name = parsedTexture.name;
  17727. texture.hasAlpha = parsedTexture.hasAlpha;
  17728. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17729. texture.level = parsedTexture.level;
  17730. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17731. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17732. texture.uOffset = parsedTexture.uOffset;
  17733. texture.vOffset = parsedTexture.vOffset;
  17734. texture.uScale = parsedTexture.uScale;
  17735. texture.vScale = parsedTexture.vScale;
  17736. texture.uAng = parsedTexture.uAng;
  17737. texture.vAng = parsedTexture.vAng;
  17738. texture.wAng = parsedTexture.wAng;
  17739. texture.wrapU = parsedTexture.wrapU;
  17740. texture.wrapV = parsedTexture.wrapV;
  17741. // Animations
  17742. if (parsedTexture.animations) {
  17743. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17744. var parsedAnimation = parsedTexture.animations[animationIndex];
  17745. texture.animations.push(parseAnimation(parsedAnimation));
  17746. }
  17747. }
  17748. return texture;
  17749. };
  17750. var parseSkeleton = function (parsedSkeleton, scene) {
  17751. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17752. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17753. var parsedBone = parsedSkeleton.bones[index];
  17754. var parentBone = null;
  17755. if (parsedBone.parentBoneIndex > -1) {
  17756. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17757. }
  17758. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17759. if (parsedBone.animation) {
  17760. bone.animations.push(parseAnimation(parsedBone.animation));
  17761. }
  17762. }
  17763. return skeleton;
  17764. };
  17765. var parseFresnelParameters = function (parsedFresnelParameters) {
  17766. var fresnelParameters = new BABYLON.FresnelParameters();
  17767. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17768. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17769. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17770. fresnelParameters.bias = parsedFresnelParameters.bias;
  17771. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17772. return fresnelParameters;
  17773. };
  17774. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17775. var material;
  17776. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17777. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17778. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17779. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17780. material.specularPower = parsedMaterial.specularPower;
  17781. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17782. material.alpha = parsedMaterial.alpha;
  17783. material.id = parsedMaterial.id;
  17784. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17785. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17786. material.wireframe = parsedMaterial.wireframe;
  17787. if (parsedMaterial.diffuseTexture) {
  17788. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17789. }
  17790. if (parsedMaterial.diffuseFresnelParameters) {
  17791. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17792. }
  17793. if (parsedMaterial.ambientTexture) {
  17794. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17795. }
  17796. if (parsedMaterial.opacityTexture) {
  17797. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17798. }
  17799. if (parsedMaterial.opacityFresnelParameters) {
  17800. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17801. }
  17802. if (parsedMaterial.reflectionTexture) {
  17803. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17804. }
  17805. if (parsedMaterial.reflectionFresnelParameters) {
  17806. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17807. }
  17808. if (parsedMaterial.emissiveTexture) {
  17809. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17810. }
  17811. if (parsedMaterial.emissiveFresnelParameters) {
  17812. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17813. }
  17814. if (parsedMaterial.specularTexture) {
  17815. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17816. }
  17817. if (parsedMaterial.bumpTexture) {
  17818. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17819. }
  17820. return material;
  17821. };
  17822. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17823. for (var index = 0; index < parsedData.materials.length; index++) {
  17824. var parsedMaterial = parsedData.materials[index];
  17825. if (parsedMaterial.id === id) {
  17826. return parseMaterial(parsedMaterial, scene, rootUrl);
  17827. }
  17828. }
  17829. return null;
  17830. };
  17831. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17832. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17833. multiMaterial.id = parsedMultiMaterial.id;
  17834. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17835. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17836. var subMatId = parsedMultiMaterial.materials[matIndex];
  17837. if (subMatId) {
  17838. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17839. }
  17840. else {
  17841. multiMaterial.subMaterials.push(null);
  17842. }
  17843. }
  17844. return multiMaterial;
  17845. };
  17846. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17847. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17848. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17849. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17850. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17851. var parsedFlare = parsedLensFlareSystem.flares[index];
  17852. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17853. }
  17854. return lensFlareSystem;
  17855. };
  17856. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17857. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17858. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17859. if (parsedParticleSystem.textureName) {
  17860. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17861. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17862. }
  17863. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17864. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17865. particleSystem.minSize = parsedParticleSystem.minSize;
  17866. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17867. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17868. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17869. particleSystem.emitter = emitter;
  17870. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17871. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17872. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17873. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17874. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17875. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17876. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17877. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17878. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17879. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17880. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17881. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17882. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17883. particleSystem.start();
  17884. return particleSystem;
  17885. };
  17886. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17887. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17888. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17889. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17890. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17891. shadowGenerator.getShadowMap().renderList.push(mesh);
  17892. }
  17893. if (parsedShadowGenerator.usePoissonSampling) {
  17894. shadowGenerator.usePoissonSampling = true;
  17895. }
  17896. else if (parsedShadowGenerator.useVarianceShadowMap) {
  17897. shadowGenerator.useVarianceShadowMap = true;
  17898. }
  17899. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  17900. shadowGenerator.useBlurVarianceShadowMap = true;
  17901. if (parsedShadowGenerator.blurScale) {
  17902. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  17903. }
  17904. if (parsedShadowGenerator.blurBoxOffset) {
  17905. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  17906. }
  17907. }
  17908. if (parsedShadowGenerator.bias !== undefined) {
  17909. shadowGenerator.bias = parsedShadowGenerator.bias;
  17910. }
  17911. return shadowGenerator;
  17912. };
  17913. var parseAnimation = function (parsedAnimation) {
  17914. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17915. var dataType = parsedAnimation.dataType;
  17916. var keys = [];
  17917. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17918. var key = parsedAnimation.keys[index];
  17919. var data;
  17920. switch (dataType) {
  17921. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17922. data = key.values[0];
  17923. break;
  17924. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17925. data = BABYLON.Quaternion.FromArray(key.values);
  17926. break;
  17927. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17928. data = BABYLON.Matrix.FromArray(key.values);
  17929. break;
  17930. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17931. default:
  17932. data = BABYLON.Vector3.FromArray(key.values);
  17933. break;
  17934. }
  17935. keys.push({
  17936. frame: key.frame,
  17937. value: data
  17938. });
  17939. }
  17940. animation.setKeys(keys);
  17941. return animation;
  17942. };
  17943. var parseLight = function (parsedLight, scene) {
  17944. var light;
  17945. switch (parsedLight.type) {
  17946. case 0:
  17947. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17948. break;
  17949. case 1:
  17950. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17951. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17952. break;
  17953. case 2:
  17954. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17955. break;
  17956. case 3:
  17957. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17958. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17959. break;
  17960. }
  17961. light.id = parsedLight.id;
  17962. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17963. if (parsedLight.intensity !== undefined) {
  17964. light.intensity = parsedLight.intensity;
  17965. }
  17966. if (parsedLight.range) {
  17967. light.range = parsedLight.range;
  17968. }
  17969. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17970. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17971. if (parsedLight.excludedMeshesIds) {
  17972. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17973. }
  17974. // Parent
  17975. if (parsedLight.parentId) {
  17976. light._waitingParentId = parsedLight.parentId;
  17977. }
  17978. if (parsedLight.includedOnlyMeshesIds) {
  17979. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17980. }
  17981. // Animations
  17982. if (parsedLight.animations) {
  17983. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17984. var parsedAnimation = parsedLight.animations[animationIndex];
  17985. light.animations.push(parseAnimation(parsedAnimation));
  17986. }
  17987. }
  17988. if (parsedLight.autoAnimate) {
  17989. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17990. }
  17991. };
  17992. var parseCamera = function (parsedCamera, scene) {
  17993. var camera;
  17994. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17995. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17996. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17997. var alpha = parsedCamera.alpha;
  17998. var beta = parsedCamera.beta;
  17999. var radius = parsedCamera.radius;
  18000. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18001. var eye_space = parsedCamera.eye_space;
  18002. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18003. }
  18004. else {
  18005. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18006. }
  18007. }
  18008. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18009. eye_space = parsedCamera.eye_space;
  18010. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18011. }
  18012. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18013. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18014. }
  18015. else if (parsedCamera.type === "FollowCamera") {
  18016. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18017. camera.heightOffset = parsedCamera.heightOffset;
  18018. camera.radius = parsedCamera.radius;
  18019. camera.rotationOffset = parsedCamera.rotationOffset;
  18020. if (lockedTargetMesh)
  18021. camera.target = lockedTargetMesh;
  18022. }
  18023. else if (parsedCamera.type === "GamepadCamera") {
  18024. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18025. }
  18026. else if (parsedCamera.type === "TouchCamera") {
  18027. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18028. }
  18029. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18030. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18031. }
  18032. else if (parsedCamera.type === "WebVRCamera") {
  18033. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18034. }
  18035. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18036. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18037. }
  18038. else {
  18039. // Free Camera is the default value
  18040. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18041. }
  18042. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18043. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18044. camera.lockedTarget = lockedTargetMesh;
  18045. }
  18046. camera.id = parsedCamera.id;
  18047. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18048. // Parent
  18049. if (parsedCamera.parentId) {
  18050. camera._waitingParentId = parsedCamera.parentId;
  18051. }
  18052. // Target
  18053. if (parsedCamera.target) {
  18054. if (camera.setTarget) {
  18055. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18056. }
  18057. else {
  18058. //For ArcRotate
  18059. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  18060. }
  18061. }
  18062. else {
  18063. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18064. }
  18065. camera.fov = parsedCamera.fov;
  18066. camera.minZ = parsedCamera.minZ;
  18067. camera.maxZ = parsedCamera.maxZ;
  18068. camera.speed = parsedCamera.speed;
  18069. camera.inertia = parsedCamera.inertia;
  18070. camera.checkCollisions = parsedCamera.checkCollisions;
  18071. camera.applyGravity = parsedCamera.applyGravity;
  18072. if (parsedCamera.ellipsoid) {
  18073. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18074. }
  18075. // Animations
  18076. if (parsedCamera.animations) {
  18077. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18078. var parsedAnimation = parsedCamera.animations[animationIndex];
  18079. camera.animations.push(parseAnimation(parsedAnimation));
  18080. }
  18081. }
  18082. if (parsedCamera.autoAnimate) {
  18083. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18084. }
  18085. // Layer Mask
  18086. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18087. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18088. }
  18089. else {
  18090. camera.layerMask = 0xFFFFFFFF;
  18091. }
  18092. return camera;
  18093. };
  18094. var parseGeometry = function (parsedGeometry, scene) {
  18095. var id = parsedGeometry.id;
  18096. return scene.getGeometryByID(id);
  18097. };
  18098. var parseBox = function (parsedBox, scene) {
  18099. if (parseGeometry(parsedBox, scene)) {
  18100. return null; // null since geometry could be something else than a box...
  18101. }
  18102. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18103. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18104. scene.pushGeometry(box, true);
  18105. return box;
  18106. };
  18107. var parseSphere = function (parsedSphere, scene) {
  18108. if (parseGeometry(parsedSphere, scene)) {
  18109. return null; // null since geometry could be something else than a sphere...
  18110. }
  18111. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18112. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18113. scene.pushGeometry(sphere, true);
  18114. return sphere;
  18115. };
  18116. var parseCylinder = function (parsedCylinder, scene) {
  18117. if (parseGeometry(parsedCylinder, scene)) {
  18118. return null; // null since geometry could be something else than a cylinder...
  18119. }
  18120. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18121. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18122. scene.pushGeometry(cylinder, true);
  18123. return cylinder;
  18124. };
  18125. var parseTorus = function (parsedTorus, scene) {
  18126. if (parseGeometry(parsedTorus, scene)) {
  18127. return null; // null since geometry could be something else than a torus...
  18128. }
  18129. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18130. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18131. scene.pushGeometry(torus, true);
  18132. return torus;
  18133. };
  18134. var parseGround = function (parsedGround, scene) {
  18135. if (parseGeometry(parsedGround, scene)) {
  18136. return null; // null since geometry could be something else than a ground...
  18137. }
  18138. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18139. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18140. scene.pushGeometry(ground, true);
  18141. return ground;
  18142. };
  18143. var parsePlane = function (parsedPlane, scene) {
  18144. if (parseGeometry(parsedPlane, scene)) {
  18145. return null; // null since geometry could be something else than a plane...
  18146. }
  18147. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18148. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18149. scene.pushGeometry(plane, true);
  18150. return plane;
  18151. };
  18152. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18153. if (parseGeometry(parsedTorusKnot, scene)) {
  18154. return null; // null since geometry could be something else than a torusKnot...
  18155. }
  18156. 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);
  18157. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18158. scene.pushGeometry(torusKnot, true);
  18159. return torusKnot;
  18160. };
  18161. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18162. if (parseGeometry(parsedVertexData, scene)) {
  18163. return null; // null since geometry could be a primitive
  18164. }
  18165. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18166. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18167. if (parsedVertexData.delayLoadingFile) {
  18168. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18169. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18170. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18171. geometry._delayInfo = [];
  18172. if (parsedVertexData.hasUVs) {
  18173. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18174. }
  18175. if (parsedVertexData.hasUVs2) {
  18176. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18177. }
  18178. if (parsedVertexData.hasColors) {
  18179. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18180. }
  18181. if (parsedVertexData.hasMatricesIndices) {
  18182. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18183. }
  18184. if (parsedVertexData.hasMatricesWeights) {
  18185. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18186. }
  18187. geometry._delayLoadingFunction = importVertexData;
  18188. }
  18189. else {
  18190. importVertexData(parsedVertexData, geometry);
  18191. }
  18192. scene.pushGeometry(geometry, true);
  18193. return geometry;
  18194. };
  18195. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18196. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18197. mesh.id = parsedMesh.id;
  18198. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18199. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18200. if (parsedMesh.rotationQuaternion) {
  18201. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18202. }
  18203. else if (parsedMesh.rotation) {
  18204. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18205. }
  18206. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18207. if (parsedMesh.localMatrix) {
  18208. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18209. }
  18210. else if (parsedMesh.pivotMatrix) {
  18211. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18212. }
  18213. mesh.setEnabled(parsedMesh.isEnabled);
  18214. mesh.isVisible = parsedMesh.isVisible;
  18215. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18216. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18217. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18218. if (parsedMesh.applyFog !== undefined) {
  18219. mesh.applyFog = parsedMesh.applyFog;
  18220. }
  18221. if (parsedMesh.pickable !== undefined) {
  18222. mesh.isPickable = parsedMesh.pickable;
  18223. }
  18224. if (parsedMesh.alphaIndex !== undefined) {
  18225. mesh.alphaIndex = parsedMesh.alphaIndex;
  18226. }
  18227. mesh.receiveShadows = parsedMesh.receiveShadows;
  18228. mesh.billboardMode = parsedMesh.billboardMode;
  18229. if (parsedMesh.visibility !== undefined) {
  18230. mesh.visibility = parsedMesh.visibility;
  18231. }
  18232. mesh.checkCollisions = parsedMesh.checkCollisions;
  18233. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18234. // Parent
  18235. if (parsedMesh.parentId) {
  18236. mesh._waitingParentId = parsedMesh.parentId;
  18237. }
  18238. // Actions
  18239. if (parsedMesh.actions !== undefined) {
  18240. mesh._waitingActions = parsedMesh.actions;
  18241. }
  18242. // Geometry
  18243. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18244. if (parsedMesh.delayLoadingFile) {
  18245. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18246. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18247. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18248. if (parsedMesh._binaryInfo) {
  18249. mesh._binaryInfo = parsedMesh._binaryInfo;
  18250. }
  18251. mesh._delayInfo = [];
  18252. if (parsedMesh.hasUVs) {
  18253. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18254. }
  18255. if (parsedMesh.hasUVs2) {
  18256. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18257. }
  18258. if (parsedMesh.hasColors) {
  18259. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18260. }
  18261. if (parsedMesh.hasMatricesIndices) {
  18262. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18263. }
  18264. if (parsedMesh.hasMatricesWeights) {
  18265. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18266. }
  18267. mesh._delayLoadingFunction = importGeometry;
  18268. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18269. mesh._checkDelayState();
  18270. }
  18271. }
  18272. else {
  18273. importGeometry(parsedMesh, mesh);
  18274. }
  18275. // Material
  18276. if (parsedMesh.materialId) {
  18277. mesh.setMaterialByID(parsedMesh.materialId);
  18278. }
  18279. else {
  18280. mesh.material = null;
  18281. }
  18282. // Skeleton
  18283. if (parsedMesh.skeletonId > -1) {
  18284. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18285. }
  18286. // Physics
  18287. if (parsedMesh.physicsImpostor) {
  18288. if (!scene.isPhysicsEnabled()) {
  18289. scene.enablePhysics();
  18290. }
  18291. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18292. }
  18293. // Animations
  18294. if (parsedMesh.animations) {
  18295. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18296. var parsedAnimation = parsedMesh.animations[animationIndex];
  18297. mesh.animations.push(parseAnimation(parsedAnimation));
  18298. }
  18299. }
  18300. if (parsedMesh.autoAnimate) {
  18301. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18302. }
  18303. // Layer Mask
  18304. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18305. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18306. }
  18307. else {
  18308. mesh.layerMask = 0xFFFFFFFF;
  18309. }
  18310. // Instances
  18311. if (parsedMesh.instances) {
  18312. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18313. var parsedInstance = parsedMesh.instances[index];
  18314. var instance = mesh.createInstance(parsedInstance.name);
  18315. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18316. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18317. if (parsedInstance.rotationQuaternion) {
  18318. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18319. }
  18320. else if (parsedInstance.rotation) {
  18321. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18322. }
  18323. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18324. instance.checkCollisions = mesh.checkCollisions;
  18325. if (parsedMesh.animations) {
  18326. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18327. parsedAnimation = parsedMesh.animations[animationIndex];
  18328. instance.animations.push(parseAnimation(parsedAnimation));
  18329. }
  18330. }
  18331. }
  18332. }
  18333. return mesh;
  18334. };
  18335. var parseActions = function (parsedActions, object, scene) {
  18336. var actionManager = new BABYLON.ActionManager(scene);
  18337. if (object === null)
  18338. scene.actionManager = actionManager;
  18339. else
  18340. object.actionManager = actionManager;
  18341. // instanciate a new object
  18342. var instanciate = function (name, params) {
  18343. var newInstance = Object.create(BABYLON[name].prototype);
  18344. newInstance.constructor.apply(newInstance, params);
  18345. return newInstance;
  18346. };
  18347. var parseParameter = function (name, value, target, propertyPath) {
  18348. if (propertyPath === null) {
  18349. // String, boolean or float
  18350. var floatValue = parseFloat(value);
  18351. if (value === "true" || value === "false")
  18352. return value === "true";
  18353. else
  18354. return isNaN(floatValue) ? value : floatValue;
  18355. }
  18356. var effectiveTarget = propertyPath.split(".");
  18357. var values = value.split(",");
  18358. // Get effective Target
  18359. for (var i = 0; i < effectiveTarget.length; i++) {
  18360. target = target[effectiveTarget[i]];
  18361. }
  18362. // Return appropriate value with its type
  18363. if (typeof (target) === "boolean")
  18364. return values[0] === "true";
  18365. if (typeof (target) === "string")
  18366. return values[0];
  18367. // Parameters with multiple values such as Vector3 etc.
  18368. var split = new Array();
  18369. for (var i = 0; i < values.length; i++)
  18370. split.push(parseFloat(values[i]));
  18371. if (target instanceof BABYLON.Vector3)
  18372. return BABYLON.Vector3.FromArray(split);
  18373. if (target instanceof BABYLON.Vector4)
  18374. return BABYLON.Vector4.FromArray(split);
  18375. if (target instanceof BABYLON.Color3)
  18376. return BABYLON.Color3.FromArray(split);
  18377. if (target instanceof BABYLON.Color4)
  18378. return BABYLON.Color4.FromArray(split);
  18379. return parseFloat(values[0]);
  18380. };
  18381. // traverse graph per trigger
  18382. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  18383. if (combineArray === void 0) { combineArray = null; }
  18384. if (parsedAction.detached)
  18385. return;
  18386. var parameters = new Array();
  18387. var target = null;
  18388. var propertyPath = null;
  18389. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  18390. // Parameters
  18391. if (parsedAction.type === 2)
  18392. parameters.push(actionManager);
  18393. else
  18394. parameters.push(trigger);
  18395. if (combine) {
  18396. var actions = new Array();
  18397. for (var j = 0; j < parsedAction.combine.length; j++) {
  18398. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  18399. }
  18400. parameters.push(actions);
  18401. }
  18402. else {
  18403. for (var i = 0; i < parsedAction.properties.length; i++) {
  18404. var value = parsedAction.properties[i].value;
  18405. var name = parsedAction.properties[i].name;
  18406. var targetType = parsedAction.properties[i].targetType;
  18407. if (name === "target")
  18408. if (targetType !== null && targetType === "SceneProperties")
  18409. value = target = scene;
  18410. else
  18411. value = target = scene.getNodeByName(value);
  18412. else if (name === "parent")
  18413. value = scene.getNodeByName(value);
  18414. else if (name === "sound")
  18415. value = scene.getSoundByName(value);
  18416. else if (name !== "propertyPath") {
  18417. if (parsedAction.type === 2 && name === "operator")
  18418. value = BABYLON.ValueCondition[value];
  18419. else
  18420. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18421. }
  18422. else {
  18423. propertyPath = value;
  18424. }
  18425. parameters.push(value);
  18426. }
  18427. }
  18428. if (combineArray === null) {
  18429. parameters.push(condition);
  18430. }
  18431. else {
  18432. parameters.push(null);
  18433. }
  18434. // If interpolate value action
  18435. if (parsedAction.name === "InterpolateValueAction") {
  18436. var param = parameters[parameters.length - 2];
  18437. parameters[parameters.length - 1] = param;
  18438. parameters[parameters.length - 2] = condition;
  18439. }
  18440. // Action or condition(s) and not CombineAction
  18441. var newAction = instanciate(parsedAction.name, parameters);
  18442. if (combineArray === null) {
  18443. if (newAction instanceof BABYLON.Condition) {
  18444. condition = newAction;
  18445. newAction = action;
  18446. }
  18447. else {
  18448. condition = null;
  18449. if (action)
  18450. action.then(newAction);
  18451. else
  18452. actionManager.registerAction(newAction);
  18453. }
  18454. }
  18455. else {
  18456. combineArray.push(newAction);
  18457. }
  18458. for (var i = 0; i < parsedAction.children.length; i++)
  18459. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  18460. };
  18461. // triggers
  18462. for (var i = 0; i < parsedActions.children.length; i++) {
  18463. var triggerParams;
  18464. var trigger = parsedActions.children[i];
  18465. if (trigger.properties.length > 0) {
  18466. var param = trigger.properties[0].value;
  18467. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  18468. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  18469. }
  18470. else
  18471. triggerParams = BABYLON.ActionManager[trigger.name];
  18472. for (var j = 0; j < trigger.children.length; j++) {
  18473. if (!trigger.detached)
  18474. traverse(trigger.children[j], triggerParams, null, null);
  18475. }
  18476. }
  18477. };
  18478. var parseSound = function (parsedSound, scene, rootUrl) {
  18479. var soundName = parsedSound.name;
  18480. var soundUrl = rootUrl + soundName;
  18481. var options = {
  18482. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  18483. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  18484. rolloffFactor: parsedSound.rolloffFactor,
  18485. refDistance: parsedSound.refDistance,
  18486. distanceModel: parsedSound.distanceModel,
  18487. playbackRate: parsedSound.playbackRate
  18488. };
  18489. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  18490. scene._addPendingData(newSound);
  18491. if (parsedSound.position) {
  18492. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18493. newSound.setPosition(soundPosition);
  18494. }
  18495. if (parsedSound.isDirectional) {
  18496. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18497. if (parsedSound.localDirectionToMesh) {
  18498. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18499. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18500. }
  18501. }
  18502. if (parsedSound.connectedMeshId) {
  18503. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18504. if (connectedMesh) {
  18505. newSound.attachToMesh(connectedMesh);
  18506. }
  18507. }
  18508. };
  18509. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18510. names = (names instanceof Array) ? names : [names];
  18511. for (var i in names) {
  18512. if (mesh.name === names[i]) {
  18513. hierarchyIds.push(mesh.id);
  18514. return true;
  18515. }
  18516. }
  18517. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18518. hierarchyIds.push(mesh.id);
  18519. return true;
  18520. }
  18521. return false;
  18522. };
  18523. var importVertexData = function (parsedVertexData, geometry) {
  18524. var vertexData = new BABYLON.VertexData();
  18525. // positions
  18526. var positions = parsedVertexData.positions;
  18527. if (positions) {
  18528. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18529. }
  18530. // normals
  18531. var normals = parsedVertexData.normals;
  18532. if (normals) {
  18533. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18534. }
  18535. // uvs
  18536. var uvs = parsedVertexData.uvs;
  18537. if (uvs) {
  18538. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18539. }
  18540. // uv2s
  18541. var uv2s = parsedVertexData.uv2s;
  18542. if (uv2s) {
  18543. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18544. }
  18545. // colors
  18546. var colors = parsedVertexData.colors;
  18547. if (colors) {
  18548. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18549. }
  18550. // matricesIndices
  18551. var matricesIndices = parsedVertexData.matricesIndices;
  18552. if (matricesIndices) {
  18553. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18554. }
  18555. // matricesWeights
  18556. var matricesWeights = parsedVertexData.matricesWeights;
  18557. if (matricesWeights) {
  18558. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18559. }
  18560. // indices
  18561. var indices = parsedVertexData.indices;
  18562. if (indices) {
  18563. vertexData.indices = indices;
  18564. }
  18565. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18566. };
  18567. var importGeometry = function (parsedGeometry, mesh) {
  18568. var scene = mesh.getScene();
  18569. // Geometry
  18570. var geometryId = parsedGeometry.geometryId;
  18571. if (geometryId) {
  18572. var geometry = scene.getGeometryByID(geometryId);
  18573. if (geometry) {
  18574. geometry.applyToMesh(mesh);
  18575. }
  18576. }
  18577. else if (parsedGeometry instanceof ArrayBuffer) {
  18578. var binaryInfo = mesh._binaryInfo;
  18579. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18580. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18581. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18582. }
  18583. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18584. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18585. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18586. }
  18587. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18588. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18589. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18590. }
  18591. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18592. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18593. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18594. }
  18595. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18596. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18597. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18598. }
  18599. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18600. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18601. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18602. }
  18603. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18604. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18605. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18606. }
  18607. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18608. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18609. mesh.setIndices(indicesData);
  18610. }
  18611. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18612. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18613. mesh.subMeshes = [];
  18614. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18615. var materialIndex = subMeshesData[(i * 5) + 0];
  18616. var verticesStart = subMeshesData[(i * 5) + 1];
  18617. var verticesCount = subMeshesData[(i * 5) + 2];
  18618. var indexStart = subMeshesData[(i * 5) + 3];
  18619. var indexCount = subMeshesData[(i * 5) + 4];
  18620. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18621. }
  18622. }
  18623. }
  18624. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18625. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18626. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18627. if (parsedGeometry.uvs) {
  18628. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18629. }
  18630. if (parsedGeometry.uvs2) {
  18631. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18632. }
  18633. if (parsedGeometry.colors) {
  18634. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18635. }
  18636. if (parsedGeometry.matricesIndices) {
  18637. if (!parsedGeometry.matricesIndices._isExpanded) {
  18638. var floatIndices = [];
  18639. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18640. var matricesIndex = parsedGeometry.matricesIndices[i];
  18641. floatIndices.push(matricesIndex & 0x000000FF);
  18642. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18643. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18644. floatIndices.push(matricesIndex >> 24);
  18645. }
  18646. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18647. }
  18648. else {
  18649. delete parsedGeometry.matricesIndices._isExpanded;
  18650. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18651. }
  18652. }
  18653. if (parsedGeometry.matricesWeights) {
  18654. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18655. }
  18656. mesh.setIndices(parsedGeometry.indices);
  18657. // SubMeshes
  18658. if (parsedGeometry.subMeshes) {
  18659. mesh.subMeshes = [];
  18660. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18661. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18662. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18663. }
  18664. }
  18665. }
  18666. // Flat shading
  18667. if (mesh._shouldGenerateFlatShading) {
  18668. mesh.convertToFlatShadedMesh();
  18669. delete mesh._shouldGenerateFlatShading;
  18670. }
  18671. // Update
  18672. mesh.computeWorldMatrix(true);
  18673. // Octree
  18674. if (scene._selectionOctree) {
  18675. scene._selectionOctree.addMesh(mesh);
  18676. }
  18677. };
  18678. BABYLON.SceneLoader.RegisterPlugin({
  18679. extensions: ".babylon",
  18680. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18681. var parsedData = JSON.parse(data);
  18682. var loadedSkeletonsIds = [];
  18683. var loadedMaterialsIds = [];
  18684. var hierarchyIds = [];
  18685. for (var index = 0; index < parsedData.meshes.length; index++) {
  18686. var parsedMesh = parsedData.meshes[index];
  18687. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18688. if (meshesNames instanceof Array) {
  18689. // Remove found mesh name from list.
  18690. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18691. }
  18692. // Material ?
  18693. if (parsedMesh.materialId) {
  18694. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18695. if (!materialFound) {
  18696. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18697. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18698. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18699. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18700. var subMatId = parsedMultiMaterial.materials[matIndex];
  18701. loadedMaterialsIds.push(subMatId);
  18702. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18703. }
  18704. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18705. parseMultiMaterial(parsedMultiMaterial, scene);
  18706. materialFound = true;
  18707. break;
  18708. }
  18709. }
  18710. }
  18711. if (!materialFound) {
  18712. loadedMaterialsIds.push(parsedMesh.materialId);
  18713. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18714. }
  18715. }
  18716. // Skeleton ?
  18717. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18718. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18719. if (!skeletonAlreadyLoaded) {
  18720. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18721. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18722. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18723. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18724. loadedSkeletonsIds.push(parsedSkeleton.id);
  18725. }
  18726. }
  18727. }
  18728. }
  18729. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18730. meshes.push(mesh);
  18731. }
  18732. }
  18733. // Connecting parents
  18734. for (index = 0; index < scene.meshes.length; index++) {
  18735. var currentMesh = scene.meshes[index];
  18736. if (currentMesh._waitingParentId) {
  18737. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18738. currentMesh._waitingParentId = undefined;
  18739. }
  18740. }
  18741. // Particles
  18742. if (parsedData.particleSystems) {
  18743. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18744. var parsedParticleSystem = parsedData.particleSystems[index];
  18745. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18746. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18747. }
  18748. }
  18749. }
  18750. return true;
  18751. },
  18752. load: function (scene, data, rootUrl) {
  18753. var parsedData = JSON.parse(data);
  18754. // Scene
  18755. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18756. scene.autoClear = parsedData.autoClear;
  18757. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18758. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18759. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18760. // Fog
  18761. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18762. scene.fogMode = parsedData.fogMode;
  18763. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18764. scene.fogStart = parsedData.fogStart;
  18765. scene.fogEnd = parsedData.fogEnd;
  18766. scene.fogDensity = parsedData.fogDensity;
  18767. }
  18768. // Lights
  18769. for (var index = 0; index < parsedData.lights.length; index++) {
  18770. var parsedLight = parsedData.lights[index];
  18771. parseLight(parsedLight, scene);
  18772. }
  18773. // Materials
  18774. if (parsedData.materials) {
  18775. for (index = 0; index < parsedData.materials.length; index++) {
  18776. var parsedMaterial = parsedData.materials[index];
  18777. parseMaterial(parsedMaterial, scene, rootUrl);
  18778. }
  18779. }
  18780. if (parsedData.multiMaterials) {
  18781. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18782. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18783. parseMultiMaterial(parsedMultiMaterial, scene);
  18784. }
  18785. }
  18786. // Skeletons
  18787. if (parsedData.skeletons) {
  18788. for (index = 0; index < parsedData.skeletons.length; index++) {
  18789. var parsedSkeleton = parsedData.skeletons[index];
  18790. parseSkeleton(parsedSkeleton, scene);
  18791. }
  18792. }
  18793. // Geometries
  18794. var geometries = parsedData.geometries;
  18795. if (geometries) {
  18796. // Boxes
  18797. var boxes = geometries.boxes;
  18798. if (boxes) {
  18799. for (index = 0; index < boxes.length; index++) {
  18800. var parsedBox = boxes[index];
  18801. parseBox(parsedBox, scene);
  18802. }
  18803. }
  18804. // Spheres
  18805. var spheres = geometries.spheres;
  18806. if (spheres) {
  18807. for (index = 0; index < spheres.length; index++) {
  18808. var parsedSphere = spheres[index];
  18809. parseSphere(parsedSphere, scene);
  18810. }
  18811. }
  18812. // Cylinders
  18813. var cylinders = geometries.cylinders;
  18814. if (cylinders) {
  18815. for (index = 0; index < cylinders.length; index++) {
  18816. var parsedCylinder = cylinders[index];
  18817. parseCylinder(parsedCylinder, scene);
  18818. }
  18819. }
  18820. // Toruses
  18821. var toruses = geometries.toruses;
  18822. if (toruses) {
  18823. for (index = 0; index < toruses.length; index++) {
  18824. var parsedTorus = toruses[index];
  18825. parseTorus(parsedTorus, scene);
  18826. }
  18827. }
  18828. // Grounds
  18829. var grounds = geometries.grounds;
  18830. if (grounds) {
  18831. for (index = 0; index < grounds.length; index++) {
  18832. var parsedGround = grounds[index];
  18833. parseGround(parsedGround, scene);
  18834. }
  18835. }
  18836. // Planes
  18837. var planes = geometries.planes;
  18838. if (planes) {
  18839. for (index = 0; index < planes.length; index++) {
  18840. var parsedPlane = planes[index];
  18841. parsePlane(parsedPlane, scene);
  18842. }
  18843. }
  18844. // TorusKnots
  18845. var torusKnots = geometries.torusKnots;
  18846. if (torusKnots) {
  18847. for (index = 0; index < torusKnots.length; index++) {
  18848. var parsedTorusKnot = torusKnots[index];
  18849. parseTorusKnot(parsedTorusKnot, scene);
  18850. }
  18851. }
  18852. // VertexData
  18853. var vertexData = geometries.vertexData;
  18854. if (vertexData) {
  18855. for (index = 0; index < vertexData.length; index++) {
  18856. var parsedVertexData = vertexData[index];
  18857. parseVertexData(parsedVertexData, scene, rootUrl);
  18858. }
  18859. }
  18860. }
  18861. // Meshes
  18862. for (index = 0; index < parsedData.meshes.length; index++) {
  18863. var parsedMesh = parsedData.meshes[index];
  18864. parseMesh(parsedMesh, scene, rootUrl);
  18865. }
  18866. // Cameras
  18867. for (index = 0; index < parsedData.cameras.length; index++) {
  18868. var parsedCamera = parsedData.cameras[index];
  18869. parseCamera(parsedCamera, scene);
  18870. }
  18871. if (parsedData.activeCameraID) {
  18872. scene.setActiveCameraByID(parsedData.activeCameraID);
  18873. }
  18874. // Browsing all the graph to connect the dots
  18875. for (index = 0; index < scene.cameras.length; index++) {
  18876. var camera = scene.cameras[index];
  18877. if (camera._waitingParentId) {
  18878. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18879. camera._waitingParentId = undefined;
  18880. }
  18881. }
  18882. for (index = 0; index < scene.lights.length; index++) {
  18883. var light = scene.lights[index];
  18884. if (light._waitingParentId) {
  18885. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18886. light._waitingParentId = undefined;
  18887. }
  18888. }
  18889. // Sounds
  18890. if (parsedData.sounds) {
  18891. for (index = 0; index < parsedData.sounds.length; index++) {
  18892. var parsedSound = parsedData.sounds[index];
  18893. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  18894. parseSound(parsedSound, scene, rootUrl);
  18895. }
  18896. else {
  18897. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  18898. }
  18899. }
  18900. }
  18901. // Connect parents & children and parse actions
  18902. for (index = 0; index < scene.meshes.length; index++) {
  18903. var mesh = scene.meshes[index];
  18904. if (mesh._waitingParentId) {
  18905. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18906. mesh._waitingParentId = undefined;
  18907. }
  18908. if (mesh._waitingActions) {
  18909. parseActions(mesh._waitingActions, mesh, scene);
  18910. mesh._waitingActions = undefined;
  18911. }
  18912. }
  18913. // Particles Systems
  18914. if (parsedData.particleSystems) {
  18915. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18916. var parsedParticleSystem = parsedData.particleSystems[index];
  18917. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18918. }
  18919. }
  18920. // Lens flares
  18921. if (parsedData.lensFlareSystems) {
  18922. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18923. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18924. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18925. }
  18926. }
  18927. // Shadows
  18928. if (parsedData.shadowGenerators) {
  18929. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18930. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18931. parseShadowGenerator(parsedShadowGenerator, scene);
  18932. }
  18933. }
  18934. // Actions (scene)
  18935. if (parsedData.actions) {
  18936. parseActions(parsedData.actions, null, scene);
  18937. }
  18938. // Finish
  18939. return true;
  18940. }
  18941. });
  18942. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  18943. })(BABYLON || (BABYLON = {}));
  18944. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18945. var BABYLON;
  18946. (function (BABYLON) {
  18947. var SpriteManager = (function () {
  18948. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  18949. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18950. this.name = name;
  18951. this.cellSize = cellSize;
  18952. this.sprites = new Array();
  18953. this.renderingGroupId = 0;
  18954. this.fogEnabled = true;
  18955. this._vertexDeclaration = [4, 4, 4, 4];
  18956. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  18957. this._capacity = capacity;
  18958. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  18959. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18960. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18961. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  18962. this._scene = scene;
  18963. this._scene.spriteManagers.push(this);
  18964. // VBO
  18965. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  18966. var indices = [];
  18967. var index = 0;
  18968. for (var count = 0; count < capacity; count++) {
  18969. indices.push(index);
  18970. indices.push(index + 1);
  18971. indices.push(index + 2);
  18972. indices.push(index);
  18973. indices.push(index + 2);
  18974. indices.push(index + 3);
  18975. index += 4;
  18976. }
  18977. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18978. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  18979. // Effects
  18980. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  18981. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  18982. }
  18983. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  18984. var arrayOffset = index * 16;
  18985. if (offsetX === 0)
  18986. offsetX = this._epsilon;
  18987. else if (offsetX === 1)
  18988. offsetX = 1 - this._epsilon;
  18989. if (offsetY === 0)
  18990. offsetY = this._epsilon;
  18991. else if (offsetY === 1)
  18992. offsetY = 1 - this._epsilon;
  18993. this._vertices[arrayOffset] = sprite.position.x;
  18994. this._vertices[arrayOffset + 1] = sprite.position.y;
  18995. this._vertices[arrayOffset + 2] = sprite.position.z;
  18996. this._vertices[arrayOffset + 3] = sprite.angle;
  18997. this._vertices[arrayOffset + 4] = sprite.width;
  18998. this._vertices[arrayOffset + 5] = sprite.height;
  18999. this._vertices[arrayOffset + 6] = offsetX;
  19000. this._vertices[arrayOffset + 7] = offsetY;
  19001. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  19002. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  19003. var offset = (sprite.cellIndex / rowSize) >> 0;
  19004. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  19005. this._vertices[arrayOffset + 11] = offset;
  19006. // Color
  19007. this._vertices[arrayOffset + 12] = sprite.color.r;
  19008. this._vertices[arrayOffset + 13] = sprite.color.g;
  19009. this._vertices[arrayOffset + 14] = sprite.color.b;
  19010. this._vertices[arrayOffset + 15] = sprite.color.a;
  19011. };
  19012. SpriteManager.prototype.render = function () {
  19013. // Check
  19014. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  19015. return;
  19016. var engine = this._scene.getEngine();
  19017. var baseSize = this._spriteTexture.getBaseSize();
  19018. // Sprites
  19019. var deltaTime = engine.getDeltaTime();
  19020. var max = Math.min(this._capacity, this.sprites.length);
  19021. var rowSize = baseSize.width / this.cellSize;
  19022. var offset = 0;
  19023. for (var index = 0; index < max; index++) {
  19024. var sprite = this.sprites[index];
  19025. if (!sprite) {
  19026. continue;
  19027. }
  19028. sprite._animate(deltaTime);
  19029. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  19030. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  19031. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  19032. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  19033. }
  19034. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  19035. // Render
  19036. var effect = this._effectBase;
  19037. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19038. effect = this._effectFog;
  19039. }
  19040. engine.enableEffect(effect);
  19041. var viewMatrix = this._scene.getViewMatrix();
  19042. effect.setTexture("diffuseSampler", this._spriteTexture);
  19043. effect.setMatrix("view", viewMatrix);
  19044. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  19045. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  19046. // Fog
  19047. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19048. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  19049. effect.setColor3("vFogColor", this._scene.fogColor);
  19050. }
  19051. // VBOs
  19052. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  19053. // Draw order
  19054. engine.setDepthFunctionToLessOrEqual();
  19055. effect.setBool("alphaTest", true);
  19056. engine.setColorWrite(false);
  19057. engine.draw(true, 0, max * 6);
  19058. engine.setColorWrite(true);
  19059. effect.setBool("alphaTest", false);
  19060. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19061. engine.draw(true, 0, max * 6);
  19062. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19063. };
  19064. SpriteManager.prototype.dispose = function () {
  19065. if (this._vertexBuffer) {
  19066. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19067. this._vertexBuffer = null;
  19068. }
  19069. if (this._indexBuffer) {
  19070. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19071. this._indexBuffer = null;
  19072. }
  19073. if (this._spriteTexture) {
  19074. this._spriteTexture.dispose();
  19075. this._spriteTexture = null;
  19076. }
  19077. // Remove from scene
  19078. var index = this._scene.spriteManagers.indexOf(this);
  19079. this._scene.spriteManagers.splice(index, 1);
  19080. // Callback
  19081. if (this.onDispose) {
  19082. this.onDispose();
  19083. }
  19084. };
  19085. return SpriteManager;
  19086. })();
  19087. BABYLON.SpriteManager = SpriteManager;
  19088. })(BABYLON || (BABYLON = {}));
  19089. //# sourceMappingURL=babylon.spriteManager.js.map
  19090. var BABYLON;
  19091. (function (BABYLON) {
  19092. var Sprite = (function () {
  19093. function Sprite(name, manager) {
  19094. this.name = name;
  19095. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19096. this.width = 1.0;
  19097. this.height = 1.0;
  19098. this.angle = 0;
  19099. this.cellIndex = 0;
  19100. this.invertU = 0;
  19101. this.invertV = 0;
  19102. this.animations = new Array();
  19103. this._animationStarted = false;
  19104. this._loopAnimation = false;
  19105. this._fromIndex = 0;
  19106. this._toIndex = 0;
  19107. this._delay = 0;
  19108. this._direction = 1;
  19109. this._frameCount = 0;
  19110. this._time = 0;
  19111. this._manager = manager;
  19112. this._manager.sprites.push(this);
  19113. this.position = BABYLON.Vector3.Zero();
  19114. }
  19115. Object.defineProperty(Sprite.prototype, "size", {
  19116. get: function () {
  19117. return this.width;
  19118. },
  19119. set: function (value) {
  19120. this.width = value;
  19121. this.height = value;
  19122. },
  19123. enumerable: true,
  19124. configurable: true
  19125. });
  19126. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  19127. this._fromIndex = from;
  19128. this._toIndex = to;
  19129. this._loopAnimation = loop;
  19130. this._delay = delay;
  19131. this._animationStarted = true;
  19132. this._direction = from < to ? 1 : -1;
  19133. this.cellIndex = from;
  19134. this._time = 0;
  19135. };
  19136. Sprite.prototype.stopAnimation = function () {
  19137. this._animationStarted = false;
  19138. };
  19139. Sprite.prototype._animate = function (deltaTime) {
  19140. if (!this._animationStarted)
  19141. return;
  19142. this._time += deltaTime;
  19143. if (this._time > this._delay) {
  19144. this._time = this._time % this._delay;
  19145. this.cellIndex += this._direction;
  19146. if (this.cellIndex == this._toIndex) {
  19147. if (this._loopAnimation) {
  19148. this.cellIndex = this._fromIndex;
  19149. }
  19150. else {
  19151. this._animationStarted = false;
  19152. if (this.disposeWhenFinishedAnimating) {
  19153. this.dispose();
  19154. }
  19155. }
  19156. }
  19157. }
  19158. };
  19159. Sprite.prototype.dispose = function () {
  19160. for (var i = 0; i < this._manager.sprites.length; i++) {
  19161. if (this._manager.sprites[i] == this) {
  19162. this._manager.sprites.splice(i, 1);
  19163. }
  19164. }
  19165. };
  19166. return Sprite;
  19167. })();
  19168. BABYLON.Sprite = Sprite;
  19169. })(BABYLON || (BABYLON = {}));
  19170. //# sourceMappingURL=babylon.sprite.js.map
  19171. var BABYLON;
  19172. (function (BABYLON) {
  19173. var Layer = (function () {
  19174. function Layer(name, imgUrl, scene, isBackground, color) {
  19175. this.name = name;
  19176. this._vertexDeclaration = [2];
  19177. this._vertexStrideSize = 2 * 4;
  19178. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  19179. this.isBackground = isBackground === undefined ? true : isBackground;
  19180. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  19181. this._scene = scene;
  19182. this._scene.layers.push(this);
  19183. // VBO
  19184. var vertices = [];
  19185. vertices.push(1, 1);
  19186. vertices.push(-1, 1);
  19187. vertices.push(-1, -1);
  19188. vertices.push(1, -1);
  19189. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19190. // Indices
  19191. var indices = [];
  19192. indices.push(0);
  19193. indices.push(1);
  19194. indices.push(2);
  19195. indices.push(0);
  19196. indices.push(2);
  19197. indices.push(3);
  19198. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19199. // Effects
  19200. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  19201. }
  19202. Layer.prototype.render = function () {
  19203. // Check
  19204. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  19205. return;
  19206. var engine = this._scene.getEngine();
  19207. // Render
  19208. engine.enableEffect(this._effect);
  19209. engine.setState(false);
  19210. // Texture
  19211. this._effect.setTexture("textureSampler", this.texture);
  19212. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  19213. // Color
  19214. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  19215. // VBOs
  19216. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19217. // Draw order
  19218. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19219. engine.draw(true, 0, 6);
  19220. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19221. };
  19222. Layer.prototype.dispose = function () {
  19223. if (this._vertexBuffer) {
  19224. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19225. this._vertexBuffer = null;
  19226. }
  19227. if (this._indexBuffer) {
  19228. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19229. this._indexBuffer = null;
  19230. }
  19231. if (this.texture) {
  19232. this.texture.dispose();
  19233. this.texture = null;
  19234. }
  19235. // Remove from scene
  19236. var index = this._scene.layers.indexOf(this);
  19237. this._scene.layers.splice(index, 1);
  19238. // Callback
  19239. if (this.onDispose) {
  19240. this.onDispose();
  19241. }
  19242. };
  19243. return Layer;
  19244. })();
  19245. BABYLON.Layer = Layer;
  19246. })(BABYLON || (BABYLON = {}));
  19247. //# sourceMappingURL=babylon.layer.js.map
  19248. var BABYLON;
  19249. (function (BABYLON) {
  19250. var Particle = (function () {
  19251. function Particle() {
  19252. this.position = BABYLON.Vector3.Zero();
  19253. this.direction = BABYLON.Vector3.Zero();
  19254. this.color = new BABYLON.Color4(0, 0, 0, 0);
  19255. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  19256. this.lifeTime = 1.0;
  19257. this.age = 0;
  19258. this.size = 0;
  19259. this.angle = 0;
  19260. this.angularSpeed = 0;
  19261. }
  19262. Particle.prototype.copyTo = function (other) {
  19263. other.position.copyFrom(this.position);
  19264. other.direction.copyFrom(this.direction);
  19265. other.color.copyFrom(this.color);
  19266. other.colorStep.copyFrom(this.colorStep);
  19267. other.lifeTime = this.lifeTime;
  19268. other.age = this.age;
  19269. other.size = this.size;
  19270. other.angle = this.angle;
  19271. other.angularSpeed = this.angularSpeed;
  19272. };
  19273. return Particle;
  19274. })();
  19275. BABYLON.Particle = Particle;
  19276. })(BABYLON || (BABYLON = {}));
  19277. //# sourceMappingURL=babylon.particle.js.map
  19278. var BABYLON;
  19279. (function (BABYLON) {
  19280. var randomNumber = function (min, max) {
  19281. if (min === max) {
  19282. return (min);
  19283. }
  19284. var random = Math.random();
  19285. return ((random * (max - min)) + min);
  19286. };
  19287. var ParticleSystem = (function () {
  19288. function ParticleSystem(name, capacity, scene, customEffect) {
  19289. var _this = this;
  19290. this.name = name;
  19291. this.renderingGroupId = 0;
  19292. this.emitter = null;
  19293. this.emitRate = 10;
  19294. this.manualEmitCount = -1;
  19295. this.updateSpeed = 0.01;
  19296. this.targetStopDuration = 0;
  19297. this.disposeOnStop = false;
  19298. this.minEmitPower = 1;
  19299. this.maxEmitPower = 1;
  19300. this.minLifeTime = 1;
  19301. this.maxLifeTime = 1;
  19302. this.minSize = 1;
  19303. this.maxSize = 1;
  19304. this.minAngularSpeed = 0;
  19305. this.maxAngularSpeed = 0;
  19306. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  19307. this.forceDepthWrite = false;
  19308. this.gravity = BABYLON.Vector3.Zero();
  19309. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  19310. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  19311. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  19312. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  19313. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19314. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19315. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  19316. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19317. this.particles = new Array();
  19318. this._vertexDeclaration = [3, 4, 4];
  19319. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  19320. this._stockParticles = new Array();
  19321. this._newPartsExcess = 0;
  19322. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  19323. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  19324. this._scaledDirection = BABYLON.Vector3.Zero();
  19325. this._scaledGravity = BABYLON.Vector3.Zero();
  19326. this._currentRenderId = -1;
  19327. this._started = false;
  19328. this._stopped = false;
  19329. this._actualFrame = 0;
  19330. this.id = name;
  19331. this._capacity = capacity;
  19332. this._scene = scene;
  19333. this._customEffect = customEffect;
  19334. scene.particleSystems.push(this);
  19335. // VBO
  19336. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  19337. var indices = [];
  19338. var index = 0;
  19339. for (var count = 0; count < capacity; count++) {
  19340. indices.push(index);
  19341. indices.push(index + 1);
  19342. indices.push(index + 2);
  19343. indices.push(index);
  19344. indices.push(index + 2);
  19345. indices.push(index + 3);
  19346. index += 4;
  19347. }
  19348. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19349. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  19350. // Default behaviors
  19351. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  19352. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  19353. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  19354. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  19355. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  19356. };
  19357. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  19358. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  19359. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  19360. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  19361. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  19362. };
  19363. this.updateFunction = function (particles) {
  19364. for (var index = 0; index < particles.length; index++) {
  19365. var particle = particles[index];
  19366. particle.age += _this._scaledUpdateSpeed;
  19367. if (particle.age >= particle.lifeTime) {
  19368. _this.recycleParticle(particle);
  19369. index--;
  19370. continue;
  19371. }
  19372. else {
  19373. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  19374. particle.color.addInPlace(_this._scaledColorStep);
  19375. if (particle.color.a < 0)
  19376. particle.color.a = 0;
  19377. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  19378. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  19379. particle.position.addInPlace(_this._scaledDirection);
  19380. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  19381. particle.direction.addInPlace(_this._scaledGravity);
  19382. }
  19383. }
  19384. };
  19385. }
  19386. ParticleSystem.prototype.recycleParticle = function (particle) {
  19387. var lastParticle = this.particles.pop();
  19388. if (lastParticle !== particle) {
  19389. lastParticle.copyTo(particle);
  19390. this._stockParticles.push(lastParticle);
  19391. }
  19392. };
  19393. ParticleSystem.prototype.getCapacity = function () {
  19394. return this._capacity;
  19395. };
  19396. ParticleSystem.prototype.isAlive = function () {
  19397. return this._alive;
  19398. };
  19399. ParticleSystem.prototype.isStarted = function () {
  19400. return this._started;
  19401. };
  19402. ParticleSystem.prototype.start = function () {
  19403. this._started = true;
  19404. this._stopped = false;
  19405. this._actualFrame = 0;
  19406. };
  19407. ParticleSystem.prototype.stop = function () {
  19408. this._stopped = true;
  19409. };
  19410. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  19411. var offset = index * 11;
  19412. this._vertices[offset] = particle.position.x;
  19413. this._vertices[offset + 1] = particle.position.y;
  19414. this._vertices[offset + 2] = particle.position.z;
  19415. this._vertices[offset + 3] = particle.color.r;
  19416. this._vertices[offset + 4] = particle.color.g;
  19417. this._vertices[offset + 5] = particle.color.b;
  19418. this._vertices[offset + 6] = particle.color.a;
  19419. this._vertices[offset + 7] = particle.angle;
  19420. this._vertices[offset + 8] = particle.size;
  19421. this._vertices[offset + 9] = offsetX;
  19422. this._vertices[offset + 10] = offsetY;
  19423. };
  19424. ParticleSystem.prototype._update = function (newParticles) {
  19425. // Update current
  19426. this._alive = this.particles.length > 0;
  19427. this.updateFunction(this.particles);
  19428. // Add new ones
  19429. var worldMatrix;
  19430. if (this.emitter.position) {
  19431. worldMatrix = this.emitter.getWorldMatrix();
  19432. }
  19433. else {
  19434. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  19435. }
  19436. for (var index = 0; index < newParticles; index++) {
  19437. if (this.particles.length === this._capacity) {
  19438. break;
  19439. }
  19440. if (this._stockParticles.length !== 0) {
  19441. var particle = this._stockParticles.pop();
  19442. particle.age = 0;
  19443. }
  19444. else {
  19445. particle = new BABYLON.Particle();
  19446. }
  19447. this.particles.push(particle);
  19448. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  19449. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  19450. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  19451. particle.size = randomNumber(this.minSize, this.maxSize);
  19452. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  19453. this.startPositionFunction(worldMatrix, particle.position);
  19454. var step = randomNumber(0, 1.0);
  19455. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  19456. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  19457. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  19458. }
  19459. };
  19460. ParticleSystem.prototype._getEffect = function () {
  19461. if (this._customEffect) {
  19462. return this._customEffect;
  19463. }
  19464. ;
  19465. var defines = [];
  19466. if (this._scene.clipPlane) {
  19467. defines.push("#define CLIPPLANE");
  19468. }
  19469. // Effect
  19470. var join = defines.join("\n");
  19471. if (this._cachedDefines !== join) {
  19472. this._cachedDefines = join;
  19473. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  19474. }
  19475. return this._effect;
  19476. };
  19477. ParticleSystem.prototype.animate = function () {
  19478. if (!this._started)
  19479. return;
  19480. var effect = this._getEffect();
  19481. // Check
  19482. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  19483. return;
  19484. if (this._currentRenderId === this._scene.getRenderId()) {
  19485. return;
  19486. }
  19487. this._currentRenderId = this._scene.getRenderId();
  19488. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  19489. // determine the number of particles we need to create
  19490. var emitCout;
  19491. if (this.manualEmitCount > -1) {
  19492. emitCout = this.manualEmitCount;
  19493. this.manualEmitCount = 0;
  19494. }
  19495. else {
  19496. emitCout = this.emitRate;
  19497. }
  19498. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  19499. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  19500. if (this._newPartsExcess > 1.0) {
  19501. newParticles += this._newPartsExcess >> 0;
  19502. this._newPartsExcess -= this._newPartsExcess >> 0;
  19503. }
  19504. this._alive = false;
  19505. if (!this._stopped) {
  19506. this._actualFrame += this._scaledUpdateSpeed;
  19507. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  19508. this.stop();
  19509. }
  19510. else {
  19511. newParticles = 0;
  19512. }
  19513. this._update(newParticles);
  19514. // Stopped?
  19515. if (this._stopped) {
  19516. if (!this._alive) {
  19517. this._started = false;
  19518. if (this.disposeOnStop) {
  19519. this._scene._toBeDisposed.push(this);
  19520. }
  19521. }
  19522. }
  19523. // Update VBO
  19524. var offset = 0;
  19525. for (var index = 0; index < this.particles.length; index++) {
  19526. var particle = this.particles[index];
  19527. this._appendParticleVertex(offset++, particle, 0, 0);
  19528. this._appendParticleVertex(offset++, particle, 1, 0);
  19529. this._appendParticleVertex(offset++, particle, 1, 1);
  19530. this._appendParticleVertex(offset++, particle, 0, 1);
  19531. }
  19532. var engine = this._scene.getEngine();
  19533. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  19534. };
  19535. ParticleSystem.prototype.render = function () {
  19536. var effect = this._getEffect();
  19537. // Check
  19538. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  19539. return 0;
  19540. var engine = this._scene.getEngine();
  19541. // Render
  19542. engine.enableEffect(effect);
  19543. engine.setState(false);
  19544. var viewMatrix = this._scene.getViewMatrix();
  19545. effect.setTexture("diffuseSampler", this.particleTexture);
  19546. effect.setMatrix("view", viewMatrix);
  19547. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  19548. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  19549. if (this._scene.clipPlane) {
  19550. var clipPlane = this._scene.clipPlane;
  19551. var invView = viewMatrix.clone();
  19552. invView.invert();
  19553. effect.setMatrix("invView", invView);
  19554. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19555. }
  19556. // VBOs
  19557. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  19558. // Draw order
  19559. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  19560. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  19561. }
  19562. else {
  19563. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19564. }
  19565. if (this.forceDepthWrite) {
  19566. engine.setDepthWrite(true);
  19567. }
  19568. engine.draw(true, 0, this.particles.length * 6);
  19569. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19570. return this.particles.length;
  19571. };
  19572. ParticleSystem.prototype.dispose = function () {
  19573. if (this._vertexBuffer) {
  19574. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19575. this._vertexBuffer = null;
  19576. }
  19577. if (this._indexBuffer) {
  19578. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19579. this._indexBuffer = null;
  19580. }
  19581. if (this.particleTexture) {
  19582. this.particleTexture.dispose();
  19583. this.particleTexture = null;
  19584. }
  19585. // Remove from scene
  19586. var index = this._scene.particleSystems.indexOf(this);
  19587. this._scene.particleSystems.splice(index, 1);
  19588. // Callback
  19589. if (this.onDispose) {
  19590. this.onDispose();
  19591. }
  19592. };
  19593. // Clone
  19594. ParticleSystem.prototype.clone = function (name, newEmitter) {
  19595. var result = new ParticleSystem(name, this._capacity, this._scene);
  19596. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  19597. if (newEmitter === undefined) {
  19598. newEmitter = this.emitter;
  19599. }
  19600. result.emitter = newEmitter;
  19601. if (this.particleTexture) {
  19602. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  19603. }
  19604. result.start();
  19605. return result;
  19606. };
  19607. // Statics
  19608. ParticleSystem.BLENDMODE_ONEONE = 0;
  19609. ParticleSystem.BLENDMODE_STANDARD = 1;
  19610. return ParticleSystem;
  19611. })();
  19612. BABYLON.ParticleSystem = ParticleSystem;
  19613. })(BABYLON || (BABYLON = {}));
  19614. //# sourceMappingURL=babylon.particleSystem.js.map
  19615. var BABYLON;
  19616. (function (BABYLON) {
  19617. var Animation = (function () {
  19618. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  19619. this.name = name;
  19620. this.targetProperty = targetProperty;
  19621. this.framePerSecond = framePerSecond;
  19622. this.dataType = dataType;
  19623. this.loopMode = loopMode;
  19624. this._offsetsCache = {};
  19625. this._highLimitsCache = {};
  19626. this._stopped = false;
  19627. this.targetPropertyPath = targetProperty.split(".");
  19628. this.dataType = dataType;
  19629. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  19630. }
  19631. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  19632. var dataType = undefined;
  19633. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  19634. dataType = Animation.ANIMATIONTYPE_FLOAT;
  19635. }
  19636. else if (from instanceof BABYLON.Quaternion) {
  19637. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  19638. }
  19639. else if (from instanceof BABYLON.Vector3) {
  19640. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  19641. }
  19642. else if (from instanceof BABYLON.Vector2) {
  19643. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  19644. }
  19645. else if (from instanceof BABYLON.Color3) {
  19646. dataType = Animation.ANIMATIONTYPE_COLOR3;
  19647. }
  19648. if (dataType == undefined) {
  19649. return null;
  19650. }
  19651. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  19652. var keys = [];
  19653. keys.push({ frame: 0, value: from });
  19654. keys.push({ frame: totalFrame, value: to });
  19655. animation.setKeys(keys);
  19656. mesh.animations.push(animation);
  19657. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  19658. };
  19659. // Methods
  19660. Animation.prototype.isStopped = function () {
  19661. return this._stopped;
  19662. };
  19663. Animation.prototype.getKeys = function () {
  19664. return this._keys;
  19665. };
  19666. Animation.prototype.getEasingFunction = function () {
  19667. return this._easingFunction;
  19668. };
  19669. Animation.prototype.setEasingFunction = function (easingFunction) {
  19670. this._easingFunction = easingFunction;
  19671. };
  19672. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  19673. return startValue + (endValue - startValue) * gradient;
  19674. };
  19675. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  19676. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  19677. };
  19678. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  19679. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  19680. };
  19681. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  19682. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  19683. };
  19684. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  19685. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  19686. };
  19687. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  19688. var startScale = new BABYLON.Vector3(0, 0, 0);
  19689. var startRotation = new BABYLON.Quaternion();
  19690. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  19691. startValue.decompose(startScale, startRotation, startTranslation);
  19692. var endScale = new BABYLON.Vector3(0, 0, 0);
  19693. var endRotation = new BABYLON.Quaternion();
  19694. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  19695. endValue.decompose(endScale, endRotation, endTranslation);
  19696. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  19697. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  19698. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  19699. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  19700. return result;
  19701. };
  19702. Animation.prototype.clone = function () {
  19703. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  19704. clone.setKeys(this._keys);
  19705. return clone;
  19706. };
  19707. Animation.prototype.setKeys = function (values) {
  19708. this._keys = values.slice(0);
  19709. this._offsetsCache = {};
  19710. this._highLimitsCache = {};
  19711. };
  19712. Animation.prototype._getKeyValue = function (value) {
  19713. if (typeof value === "function") {
  19714. return value();
  19715. }
  19716. return value;
  19717. };
  19718. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  19719. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  19720. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  19721. }
  19722. this.currentFrame = currentFrame;
  19723. // Try to get a hash to find the right key
  19724. 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));
  19725. if (this._keys[startKey].frame >= currentFrame) {
  19726. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  19727. startKey--;
  19728. }
  19729. }
  19730. for (var key = startKey; key < this._keys.length; key++) {
  19731. if (this._keys[key + 1].frame >= currentFrame) {
  19732. var startValue = this._getKeyValue(this._keys[key].value);
  19733. var endValue = this._getKeyValue(this._keys[key + 1].value);
  19734. // gradient : percent of currentFrame between the frame inf and the frame sup
  19735. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  19736. // check for easingFunction and correction of gradient
  19737. if (this._easingFunction != null) {
  19738. gradient = this._easingFunction.ease(gradient);
  19739. }
  19740. switch (this.dataType) {
  19741. // Float
  19742. case Animation.ANIMATIONTYPE_FLOAT:
  19743. switch (loopMode) {
  19744. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19745. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19746. return this.floatInterpolateFunction(startValue, endValue, gradient);
  19747. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19748. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  19749. }
  19750. break;
  19751. // Quaternion
  19752. case Animation.ANIMATIONTYPE_QUATERNION:
  19753. var quaternion = null;
  19754. switch (loopMode) {
  19755. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19756. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19757. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  19758. break;
  19759. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19760. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19761. break;
  19762. }
  19763. return quaternion;
  19764. // Vector3
  19765. case Animation.ANIMATIONTYPE_VECTOR3:
  19766. switch (loopMode) {
  19767. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19768. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19769. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  19770. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19771. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19772. }
  19773. // Vector2
  19774. case Animation.ANIMATIONTYPE_VECTOR2:
  19775. switch (loopMode) {
  19776. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19777. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19778. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  19779. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19780. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19781. }
  19782. // Color3
  19783. case Animation.ANIMATIONTYPE_COLOR3:
  19784. switch (loopMode) {
  19785. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19786. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19787. return this.color3InterpolateFunction(startValue, endValue, gradient);
  19788. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19789. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19790. }
  19791. // Matrix
  19792. case Animation.ANIMATIONTYPE_MATRIX:
  19793. switch (loopMode) {
  19794. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19795. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19796. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  19797. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19798. return startValue;
  19799. }
  19800. default:
  19801. break;
  19802. }
  19803. break;
  19804. }
  19805. }
  19806. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  19807. };
  19808. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  19809. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  19810. this._stopped = true;
  19811. return false;
  19812. }
  19813. var returnValue = true;
  19814. // Adding a start key at frame 0 if missing
  19815. if (this._keys[0].frame !== 0) {
  19816. var newKey = { frame: 0, value: this._keys[0].value };
  19817. this._keys.splice(0, 0, newKey);
  19818. }
  19819. // Check limits
  19820. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  19821. from = this._keys[0].frame;
  19822. }
  19823. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  19824. to = this._keys[this._keys.length - 1].frame;
  19825. }
  19826. // Compute ratio
  19827. var range = to - from;
  19828. var offsetValue;
  19829. // ratio represents the frame delta between from and to
  19830. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  19831. var highLimitValue = 0;
  19832. if (ratio > range && !loop) {
  19833. returnValue = false;
  19834. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  19835. }
  19836. else {
  19837. // Get max value if required
  19838. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  19839. var keyOffset = to.toString() + from.toString();
  19840. if (!this._offsetsCache[keyOffset]) {
  19841. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19842. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19843. switch (this.dataType) {
  19844. // Float
  19845. case Animation.ANIMATIONTYPE_FLOAT:
  19846. this._offsetsCache[keyOffset] = toValue - fromValue;
  19847. break;
  19848. // Quaternion
  19849. case Animation.ANIMATIONTYPE_QUATERNION:
  19850. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19851. break;
  19852. // Vector3
  19853. case Animation.ANIMATIONTYPE_VECTOR3:
  19854. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19855. // Vector2
  19856. case Animation.ANIMATIONTYPE_VECTOR2:
  19857. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19858. // Color3
  19859. case Animation.ANIMATIONTYPE_COLOR3:
  19860. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19861. default:
  19862. break;
  19863. }
  19864. this._highLimitsCache[keyOffset] = toValue;
  19865. }
  19866. highLimitValue = this._highLimitsCache[keyOffset];
  19867. offsetValue = this._offsetsCache[keyOffset];
  19868. }
  19869. }
  19870. if (offsetValue === undefined) {
  19871. switch (this.dataType) {
  19872. // Float
  19873. case Animation.ANIMATIONTYPE_FLOAT:
  19874. offsetValue = 0;
  19875. break;
  19876. // Quaternion
  19877. case Animation.ANIMATIONTYPE_QUATERNION:
  19878. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  19879. break;
  19880. // Vector3
  19881. case Animation.ANIMATIONTYPE_VECTOR3:
  19882. offsetValue = BABYLON.Vector3.Zero();
  19883. break;
  19884. // Vector2
  19885. case Animation.ANIMATIONTYPE_VECTOR2:
  19886. offsetValue = BABYLON.Vector2.Zero();
  19887. break;
  19888. // Color3
  19889. case Animation.ANIMATIONTYPE_COLOR3:
  19890. offsetValue = BABYLON.Color3.Black();
  19891. }
  19892. }
  19893. // Compute value
  19894. var repeatCount = (ratio / range) >> 0;
  19895. var currentFrame = returnValue ? from + ratio % range : to;
  19896. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  19897. // Set value
  19898. if (this.targetPropertyPath.length > 1) {
  19899. var property = this._target[this.targetPropertyPath[0]];
  19900. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  19901. property = property[this.targetPropertyPath[index]];
  19902. }
  19903. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  19904. }
  19905. else {
  19906. this._target[this.targetPropertyPath[0]] = currentValue;
  19907. }
  19908. if (this._target.markAsDirty) {
  19909. this._target.markAsDirty(this.targetProperty);
  19910. }
  19911. if (!returnValue) {
  19912. this._stopped = true;
  19913. }
  19914. return returnValue;
  19915. };
  19916. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  19917. get: function () {
  19918. return Animation._ANIMATIONTYPE_FLOAT;
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  19924. get: function () {
  19925. return Animation._ANIMATIONTYPE_VECTOR3;
  19926. },
  19927. enumerable: true,
  19928. configurable: true
  19929. });
  19930. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  19931. get: function () {
  19932. return Animation._ANIMATIONTYPE_VECTOR2;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  19938. get: function () {
  19939. return Animation._ANIMATIONTYPE_QUATERNION;
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  19945. get: function () {
  19946. return Animation._ANIMATIONTYPE_MATRIX;
  19947. },
  19948. enumerable: true,
  19949. configurable: true
  19950. });
  19951. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  19952. get: function () {
  19953. return Animation._ANIMATIONTYPE_COLOR3;
  19954. },
  19955. enumerable: true,
  19956. configurable: true
  19957. });
  19958. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  19959. get: function () {
  19960. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  19961. },
  19962. enumerable: true,
  19963. configurable: true
  19964. });
  19965. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  19966. get: function () {
  19967. return Animation._ANIMATIONLOOPMODE_CYCLE;
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  19973. get: function () {
  19974. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. // Statics
  19980. Animation._ANIMATIONTYPE_FLOAT = 0;
  19981. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  19982. Animation._ANIMATIONTYPE_QUATERNION = 2;
  19983. Animation._ANIMATIONTYPE_MATRIX = 3;
  19984. Animation._ANIMATIONTYPE_COLOR3 = 4;
  19985. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  19986. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  19987. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  19988. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  19989. return Animation;
  19990. })();
  19991. BABYLON.Animation = Animation;
  19992. })(BABYLON || (BABYLON = {}));
  19993. //# sourceMappingURL=babylon.animation.js.map
  19994. var BABYLON;
  19995. (function (BABYLON) {
  19996. var Animatable = (function () {
  19997. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  19998. if (fromFrame === void 0) { fromFrame = 0; }
  19999. if (toFrame === void 0) { toFrame = 100; }
  20000. if (loopAnimation === void 0) { loopAnimation = false; }
  20001. if (speedRatio === void 0) { speedRatio = 1.0; }
  20002. this.target = target;
  20003. this.fromFrame = fromFrame;
  20004. this.toFrame = toFrame;
  20005. this.loopAnimation = loopAnimation;
  20006. this.speedRatio = speedRatio;
  20007. this.onAnimationEnd = onAnimationEnd;
  20008. this._animations = new Array();
  20009. this._paused = false;
  20010. this.animationStarted = false;
  20011. if (animations) {
  20012. this.appendAnimations(target, animations);
  20013. }
  20014. this._scene = scene;
  20015. scene._activeAnimatables.push(this);
  20016. }
  20017. // Methods
  20018. Animatable.prototype.appendAnimations = function (target, animations) {
  20019. for (var index = 0; index < animations.length; index++) {
  20020. var animation = animations[index];
  20021. animation._target = target;
  20022. this._animations.push(animation);
  20023. }
  20024. };
  20025. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  20026. var animations = this._animations;
  20027. for (var index = 0; index < animations.length; index++) {
  20028. if (animations[index].targetProperty === property) {
  20029. return animations[index];
  20030. }
  20031. }
  20032. return null;
  20033. };
  20034. Animatable.prototype.pause = function () {
  20035. if (this._paused) {
  20036. return;
  20037. }
  20038. this._paused = true;
  20039. };
  20040. Animatable.prototype.restart = function () {
  20041. this._paused = false;
  20042. };
  20043. Animatable.prototype.stop = function () {
  20044. var index = this._scene._activeAnimatables.indexOf(this);
  20045. if (index > -1) {
  20046. this._scene._activeAnimatables.splice(index, 1);
  20047. }
  20048. if (this.onAnimationEnd) {
  20049. this.onAnimationEnd();
  20050. }
  20051. };
  20052. Animatable.prototype._animate = function (delay) {
  20053. if (this._paused) {
  20054. if (!this._pausedDelay) {
  20055. this._pausedDelay = delay;
  20056. }
  20057. return true;
  20058. }
  20059. if (!this._localDelayOffset) {
  20060. this._localDelayOffset = delay;
  20061. }
  20062. else if (this._pausedDelay) {
  20063. this._localDelayOffset += delay - this._pausedDelay;
  20064. this._pausedDelay = null;
  20065. }
  20066. // Animating
  20067. var running = false;
  20068. var animations = this._animations;
  20069. for (var index = 0; index < animations.length; index++) {
  20070. var animation = animations[index];
  20071. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  20072. running = running || isRunning;
  20073. }
  20074. if (!running) {
  20075. // Remove from active animatables
  20076. index = this._scene._activeAnimatables.indexOf(this);
  20077. this._scene._activeAnimatables.splice(index, 1);
  20078. }
  20079. if (!running && this.onAnimationEnd) {
  20080. this.onAnimationEnd();
  20081. }
  20082. return running;
  20083. };
  20084. return Animatable;
  20085. })();
  20086. BABYLON.Animatable = Animatable;
  20087. })(BABYLON || (BABYLON = {}));
  20088. //# sourceMappingURL=babylon.animatable.js.map
  20089. var __extends = this.__extends || function (d, b) {
  20090. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20091. function __() { this.constructor = d; }
  20092. __.prototype = b.prototype;
  20093. d.prototype = new __();
  20094. };
  20095. var BABYLON;
  20096. (function (BABYLON) {
  20097. var EasingFunction = (function () {
  20098. function EasingFunction() {
  20099. // Properties
  20100. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  20101. }
  20102. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  20103. get: function () {
  20104. return EasingFunction._EASINGMODE_EASEIN;
  20105. },
  20106. enumerable: true,
  20107. configurable: true
  20108. });
  20109. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  20110. get: function () {
  20111. return EasingFunction._EASINGMODE_EASEOUT;
  20112. },
  20113. enumerable: true,
  20114. configurable: true
  20115. });
  20116. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  20117. get: function () {
  20118. return EasingFunction._EASINGMODE_EASEINOUT;
  20119. },
  20120. enumerable: true,
  20121. configurable: true
  20122. });
  20123. EasingFunction.prototype.setEasingMode = function (easingMode) {
  20124. var n = Math.min(Math.max(easingMode, 0), 2);
  20125. this._easingMode = n;
  20126. };
  20127. EasingFunction.prototype.getEasingMode = function () {
  20128. return this._easingMode;
  20129. };
  20130. EasingFunction.prototype.easeInCore = function (gradient) {
  20131. throw new Error('You must implement this method');
  20132. };
  20133. EasingFunction.prototype.ease = function (gradient) {
  20134. switch (this._easingMode) {
  20135. case EasingFunction.EASINGMODE_EASEIN:
  20136. return this.easeInCore(gradient);
  20137. case EasingFunction.EASINGMODE_EASEOUT:
  20138. return (1 - this.easeInCore(1 - gradient));
  20139. }
  20140. if (gradient >= 0.5) {
  20141. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  20142. }
  20143. return (this.easeInCore(gradient * 2) * 0.5);
  20144. };
  20145. //Statics
  20146. EasingFunction._EASINGMODE_EASEIN = 0;
  20147. EasingFunction._EASINGMODE_EASEOUT = 1;
  20148. EasingFunction._EASINGMODE_EASEINOUT = 2;
  20149. return EasingFunction;
  20150. })();
  20151. BABYLON.EasingFunction = EasingFunction;
  20152. var CircleEase = (function (_super) {
  20153. __extends(CircleEase, _super);
  20154. function CircleEase() {
  20155. _super.apply(this, arguments);
  20156. }
  20157. CircleEase.prototype.easeInCore = function (gradient) {
  20158. gradient = Math.max(0, Math.min(1, gradient));
  20159. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  20160. };
  20161. return CircleEase;
  20162. })(EasingFunction);
  20163. BABYLON.CircleEase = CircleEase;
  20164. var BackEase = (function (_super) {
  20165. __extends(BackEase, _super);
  20166. function BackEase(amplitude) {
  20167. if (amplitude === void 0) { amplitude = 1; }
  20168. _super.call(this);
  20169. this.amplitude = amplitude;
  20170. }
  20171. BackEase.prototype.easeInCore = function (gradient) {
  20172. var num = Math.max(0, this.amplitude);
  20173. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  20174. };
  20175. return BackEase;
  20176. })(EasingFunction);
  20177. BABYLON.BackEase = BackEase;
  20178. var BounceEase = (function (_super) {
  20179. __extends(BounceEase, _super);
  20180. function BounceEase(bounces, bounciness) {
  20181. if (bounces === void 0) { bounces = 3; }
  20182. if (bounciness === void 0) { bounciness = 2; }
  20183. _super.call(this);
  20184. this.bounces = bounces;
  20185. this.bounciness = bounciness;
  20186. }
  20187. BounceEase.prototype.easeInCore = function (gradient) {
  20188. var y = Math.max(0.0, this.bounces);
  20189. var bounciness = this.bounciness;
  20190. if (bounciness <= 1.0) {
  20191. bounciness = 1.001;
  20192. }
  20193. var num9 = Math.pow(bounciness, y);
  20194. var num5 = 1.0 - bounciness;
  20195. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  20196. var num15 = gradient * num4;
  20197. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  20198. var num3 = Math.floor(num65);
  20199. var num13 = num3 + 1.0;
  20200. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  20201. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  20202. var num7 = (num8 + num12) * 0.5;
  20203. var num6 = gradient - num7;
  20204. var num2 = num7 - num8;
  20205. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  20206. };
  20207. return BounceEase;
  20208. })(EasingFunction);
  20209. BABYLON.BounceEase = BounceEase;
  20210. var CubicEase = (function (_super) {
  20211. __extends(CubicEase, _super);
  20212. function CubicEase() {
  20213. _super.apply(this, arguments);
  20214. }
  20215. CubicEase.prototype.easeInCore = function (gradient) {
  20216. return (gradient * gradient * gradient);
  20217. };
  20218. return CubicEase;
  20219. })(EasingFunction);
  20220. BABYLON.CubicEase = CubicEase;
  20221. var ElasticEase = (function (_super) {
  20222. __extends(ElasticEase, _super);
  20223. function ElasticEase(oscillations, springiness) {
  20224. if (oscillations === void 0) { oscillations = 3; }
  20225. if (springiness === void 0) { springiness = 3; }
  20226. _super.call(this);
  20227. this.oscillations = oscillations;
  20228. this.springiness = springiness;
  20229. }
  20230. ElasticEase.prototype.easeInCore = function (gradient) {
  20231. var num2;
  20232. var num3 = Math.max(0.0, this.oscillations);
  20233. var num = Math.max(0.0, this.springiness);
  20234. if (num == 0) {
  20235. num2 = gradient;
  20236. }
  20237. else {
  20238. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  20239. }
  20240. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  20241. };
  20242. return ElasticEase;
  20243. })(EasingFunction);
  20244. BABYLON.ElasticEase = ElasticEase;
  20245. var ExponentialEase = (function (_super) {
  20246. __extends(ExponentialEase, _super);
  20247. function ExponentialEase(exponent) {
  20248. if (exponent === void 0) { exponent = 2; }
  20249. _super.call(this);
  20250. this.exponent = exponent;
  20251. }
  20252. ExponentialEase.prototype.easeInCore = function (gradient) {
  20253. if (this.exponent <= 0) {
  20254. return gradient;
  20255. }
  20256. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  20257. };
  20258. return ExponentialEase;
  20259. })(EasingFunction);
  20260. BABYLON.ExponentialEase = ExponentialEase;
  20261. var PowerEase = (function (_super) {
  20262. __extends(PowerEase, _super);
  20263. function PowerEase(power) {
  20264. if (power === void 0) { power = 2; }
  20265. _super.call(this);
  20266. this.power = power;
  20267. }
  20268. PowerEase.prototype.easeInCore = function (gradient) {
  20269. var y = Math.max(0.0, this.power);
  20270. return Math.pow(gradient, y);
  20271. };
  20272. return PowerEase;
  20273. })(EasingFunction);
  20274. BABYLON.PowerEase = PowerEase;
  20275. var QuadraticEase = (function (_super) {
  20276. __extends(QuadraticEase, _super);
  20277. function QuadraticEase() {
  20278. _super.apply(this, arguments);
  20279. }
  20280. QuadraticEase.prototype.easeInCore = function (gradient) {
  20281. return (gradient * gradient);
  20282. };
  20283. return QuadraticEase;
  20284. })(EasingFunction);
  20285. BABYLON.QuadraticEase = QuadraticEase;
  20286. var QuarticEase = (function (_super) {
  20287. __extends(QuarticEase, _super);
  20288. function QuarticEase() {
  20289. _super.apply(this, arguments);
  20290. }
  20291. QuarticEase.prototype.easeInCore = function (gradient) {
  20292. return (gradient * gradient * gradient * gradient);
  20293. };
  20294. return QuarticEase;
  20295. })(EasingFunction);
  20296. BABYLON.QuarticEase = QuarticEase;
  20297. var QuinticEase = (function (_super) {
  20298. __extends(QuinticEase, _super);
  20299. function QuinticEase() {
  20300. _super.apply(this, arguments);
  20301. }
  20302. QuinticEase.prototype.easeInCore = function (gradient) {
  20303. return (gradient * gradient * gradient * gradient * gradient);
  20304. };
  20305. return QuinticEase;
  20306. })(EasingFunction);
  20307. BABYLON.QuinticEase = QuinticEase;
  20308. var SineEase = (function (_super) {
  20309. __extends(SineEase, _super);
  20310. function SineEase() {
  20311. _super.apply(this, arguments);
  20312. }
  20313. SineEase.prototype.easeInCore = function (gradient) {
  20314. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  20315. };
  20316. return SineEase;
  20317. })(EasingFunction);
  20318. BABYLON.SineEase = SineEase;
  20319. var BezierCurveEase = (function (_super) {
  20320. __extends(BezierCurveEase, _super);
  20321. function BezierCurveEase(x1, y1, x2, y2) {
  20322. if (x1 === void 0) { x1 = 0; }
  20323. if (y1 === void 0) { y1 = 0; }
  20324. if (x2 === void 0) { x2 = 1; }
  20325. if (y2 === void 0) { y2 = 1; }
  20326. _super.call(this);
  20327. this.x1 = x1;
  20328. this.y1 = y1;
  20329. this.x2 = x2;
  20330. this.y2 = y2;
  20331. }
  20332. BezierCurveEase.prototype.easeInCore = function (gradient) {
  20333. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  20334. };
  20335. return BezierCurveEase;
  20336. })(EasingFunction);
  20337. BABYLON.BezierCurveEase = BezierCurveEase;
  20338. })(BABYLON || (BABYLON = {}));
  20339. //# sourceMappingURL=babylon.easing.js.map
  20340. var BABYLON;
  20341. (function (BABYLON) {
  20342. var Octree = (function () {
  20343. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  20344. if (maxDepth === void 0) { maxDepth = 2; }
  20345. this.maxDepth = maxDepth;
  20346. this.dynamicContent = new Array();
  20347. this._maxBlockCapacity = maxBlockCapacity || 64;
  20348. this._selectionContent = new BABYLON.SmartArray(1024);
  20349. this._creationFunc = creationFunc;
  20350. }
  20351. // Methods
  20352. Octree.prototype.update = function (worldMin, worldMax, entries) {
  20353. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  20354. };
  20355. Octree.prototype.addMesh = function (entry) {
  20356. for (var index = 0; index < this.blocks.length; index++) {
  20357. var block = this.blocks[index];
  20358. block.addEntry(entry);
  20359. }
  20360. };
  20361. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  20362. this._selectionContent.reset();
  20363. for (var index = 0; index < this.blocks.length; index++) {
  20364. var block = this.blocks[index];
  20365. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  20366. }
  20367. if (allowDuplicate) {
  20368. this._selectionContent.concat(this.dynamicContent);
  20369. }
  20370. else {
  20371. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20372. }
  20373. return this._selectionContent;
  20374. };
  20375. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  20376. this._selectionContent.reset();
  20377. for (var index = 0; index < this.blocks.length; index++) {
  20378. var block = this.blocks[index];
  20379. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  20380. }
  20381. if (allowDuplicate) {
  20382. this._selectionContent.concat(this.dynamicContent);
  20383. }
  20384. else {
  20385. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20386. }
  20387. return this._selectionContent;
  20388. };
  20389. Octree.prototype.intersectsRay = function (ray) {
  20390. this._selectionContent.reset();
  20391. for (var index = 0; index < this.blocks.length; index++) {
  20392. var block = this.blocks[index];
  20393. block.intersectsRay(ray, this._selectionContent);
  20394. }
  20395. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20396. return this._selectionContent;
  20397. };
  20398. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  20399. target.blocks = new Array();
  20400. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  20401. // Segmenting space
  20402. for (var x = 0; x < 2; x++) {
  20403. for (var y = 0; y < 2; y++) {
  20404. for (var z = 0; z < 2; z++) {
  20405. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  20406. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  20407. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  20408. block.addEntries(entries);
  20409. target.blocks.push(block);
  20410. }
  20411. }
  20412. }
  20413. };
  20414. Octree.CreationFuncForMeshes = function (entry, block) {
  20415. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20416. block.entries.push(entry);
  20417. }
  20418. };
  20419. Octree.CreationFuncForSubMeshes = function (entry, block) {
  20420. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20421. block.entries.push(entry);
  20422. }
  20423. };
  20424. return Octree;
  20425. })();
  20426. BABYLON.Octree = Octree;
  20427. })(BABYLON || (BABYLON = {}));
  20428. //# sourceMappingURL=babylon.octree.js.map
  20429. var BABYLON;
  20430. (function (BABYLON) {
  20431. var OctreeBlock = (function () {
  20432. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  20433. this.entries = new Array();
  20434. this._boundingVectors = new Array();
  20435. this._capacity = capacity;
  20436. this._depth = depth;
  20437. this._maxDepth = maxDepth;
  20438. this._creationFunc = creationFunc;
  20439. this._minPoint = minPoint;
  20440. this._maxPoint = maxPoint;
  20441. this._boundingVectors.push(minPoint.clone());
  20442. this._boundingVectors.push(maxPoint.clone());
  20443. this._boundingVectors.push(minPoint.clone());
  20444. this._boundingVectors[2].x = maxPoint.x;
  20445. this._boundingVectors.push(minPoint.clone());
  20446. this._boundingVectors[3].y = maxPoint.y;
  20447. this._boundingVectors.push(minPoint.clone());
  20448. this._boundingVectors[4].z = maxPoint.z;
  20449. this._boundingVectors.push(maxPoint.clone());
  20450. this._boundingVectors[5].z = minPoint.z;
  20451. this._boundingVectors.push(maxPoint.clone());
  20452. this._boundingVectors[6].x = minPoint.x;
  20453. this._boundingVectors.push(maxPoint.clone());
  20454. this._boundingVectors[7].y = minPoint.y;
  20455. }
  20456. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  20457. // Property
  20458. get: function () {
  20459. return this._capacity;
  20460. },
  20461. enumerable: true,
  20462. configurable: true
  20463. });
  20464. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  20465. get: function () {
  20466. return this._minPoint;
  20467. },
  20468. enumerable: true,
  20469. configurable: true
  20470. });
  20471. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  20472. get: function () {
  20473. return this._maxPoint;
  20474. },
  20475. enumerable: true,
  20476. configurable: true
  20477. });
  20478. // Methods
  20479. OctreeBlock.prototype.addEntry = function (entry) {
  20480. if (this.blocks) {
  20481. for (var index = 0; index < this.blocks.length; index++) {
  20482. var block = this.blocks[index];
  20483. block.addEntry(entry);
  20484. }
  20485. return;
  20486. }
  20487. this._creationFunc(entry, this);
  20488. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  20489. this.createInnerBlocks();
  20490. }
  20491. };
  20492. OctreeBlock.prototype.addEntries = function (entries) {
  20493. for (var index = 0; index < entries.length; index++) {
  20494. var mesh = entries[index];
  20495. this.addEntry(mesh);
  20496. }
  20497. };
  20498. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  20499. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  20500. if (this.blocks) {
  20501. for (var index = 0; index < this.blocks.length; index++) {
  20502. var block = this.blocks[index];
  20503. block.select(frustumPlanes, selection, allowDuplicate);
  20504. }
  20505. return;
  20506. }
  20507. if (allowDuplicate) {
  20508. selection.concat(this.entries);
  20509. }
  20510. else {
  20511. selection.concatWithNoDuplicate(this.entries);
  20512. }
  20513. }
  20514. };
  20515. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  20516. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  20517. if (this.blocks) {
  20518. for (var index = 0; index < this.blocks.length; index++) {
  20519. var block = this.blocks[index];
  20520. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  20521. }
  20522. return;
  20523. }
  20524. if (allowDuplicate) {
  20525. selection.concat(this.entries);
  20526. }
  20527. else {
  20528. selection.concatWithNoDuplicate(this.entries);
  20529. }
  20530. }
  20531. };
  20532. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  20533. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  20534. if (this.blocks) {
  20535. for (var index = 0; index < this.blocks.length; index++) {
  20536. var block = this.blocks[index];
  20537. block.intersectsRay(ray, selection);
  20538. }
  20539. return;
  20540. }
  20541. selection.concatWithNoDuplicate(this.entries);
  20542. }
  20543. };
  20544. OctreeBlock.prototype.createInnerBlocks = function () {
  20545. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  20546. };
  20547. return OctreeBlock;
  20548. })();
  20549. BABYLON.OctreeBlock = OctreeBlock;
  20550. })(BABYLON || (BABYLON = {}));
  20551. //# sourceMappingURL=babylon.octreeBlock.js.map
  20552. var BABYLON;
  20553. (function (BABYLON) {
  20554. var Bone = (function () {
  20555. function Bone(name, skeleton, parentBone, matrix) {
  20556. this.name = name;
  20557. this.children = new Array();
  20558. this.animations = new Array();
  20559. this._worldTransform = new BABYLON.Matrix();
  20560. this._absoluteTransform = new BABYLON.Matrix();
  20561. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  20562. this._skeleton = skeleton;
  20563. this._matrix = matrix;
  20564. this._baseMatrix = matrix;
  20565. skeleton.bones.push(this);
  20566. if (parentBone) {
  20567. this._parent = parentBone;
  20568. parentBone.children.push(this);
  20569. }
  20570. else {
  20571. this._parent = null;
  20572. }
  20573. this._updateDifferenceMatrix();
  20574. }
  20575. // Members
  20576. Bone.prototype.getParent = function () {
  20577. return this._parent;
  20578. };
  20579. Bone.prototype.getLocalMatrix = function () {
  20580. return this._matrix;
  20581. };
  20582. Bone.prototype.getBaseMatrix = function () {
  20583. return this._baseMatrix;
  20584. };
  20585. Bone.prototype.getWorldMatrix = function () {
  20586. return this._worldTransform;
  20587. };
  20588. Bone.prototype.getInvertedAbsoluteTransform = function () {
  20589. return this._invertedAbsoluteTransform;
  20590. };
  20591. Bone.prototype.getAbsoluteMatrix = function () {
  20592. var matrix = this._matrix.clone();
  20593. var parent = this._parent;
  20594. while (parent) {
  20595. matrix = matrix.multiply(parent.getLocalMatrix());
  20596. parent = parent.getParent();
  20597. }
  20598. return matrix;
  20599. };
  20600. // Methods
  20601. Bone.prototype.updateMatrix = function (matrix) {
  20602. this._matrix = matrix;
  20603. this._skeleton._markAsDirty();
  20604. this._updateDifferenceMatrix();
  20605. };
  20606. Bone.prototype._updateDifferenceMatrix = function () {
  20607. if (this._parent) {
  20608. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  20609. }
  20610. else {
  20611. this._absoluteTransform.copyFrom(this._matrix);
  20612. }
  20613. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  20614. for (var index = 0; index < this.children.length; index++) {
  20615. this.children[index]._updateDifferenceMatrix();
  20616. }
  20617. };
  20618. Bone.prototype.markAsDirty = function () {
  20619. this._skeleton._markAsDirty();
  20620. };
  20621. return Bone;
  20622. })();
  20623. BABYLON.Bone = Bone;
  20624. })(BABYLON || (BABYLON = {}));
  20625. //# sourceMappingURL=babylon.bone.js.map
  20626. var BABYLON;
  20627. (function (BABYLON) {
  20628. var Skeleton = (function () {
  20629. function Skeleton(name, id, scene) {
  20630. this.name = name;
  20631. this.id = id;
  20632. this.bones = new Array();
  20633. this._isDirty = true;
  20634. this._identity = BABYLON.Matrix.Identity();
  20635. this.bones = [];
  20636. this._scene = scene;
  20637. scene.skeletons.push(this);
  20638. this.prepare();
  20639. //make sure it will recalculate the matrix next time prepare is called.
  20640. this._isDirty = true;
  20641. }
  20642. // Members
  20643. Skeleton.prototype.getTransformMatrices = function () {
  20644. return this._transformMatrices;
  20645. };
  20646. // Methods
  20647. Skeleton.prototype._markAsDirty = function () {
  20648. this._isDirty = true;
  20649. };
  20650. Skeleton.prototype.prepare = function () {
  20651. if (!this._isDirty) {
  20652. return;
  20653. }
  20654. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  20655. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  20656. }
  20657. for (var index = 0; index < this.bones.length; index++) {
  20658. var bone = this.bones[index];
  20659. var parentBone = bone.getParent();
  20660. if (parentBone) {
  20661. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  20662. }
  20663. else {
  20664. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  20665. }
  20666. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  20667. }
  20668. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  20669. this._isDirty = false;
  20670. this._scene._activeBones += this.bones.length;
  20671. };
  20672. Skeleton.prototype.getAnimatables = function () {
  20673. if (!this._animatables || this._animatables.length !== this.bones.length) {
  20674. this._animatables = [];
  20675. for (var index = 0; index < this.bones.length; index++) {
  20676. this._animatables.push(this.bones[index]);
  20677. }
  20678. }
  20679. return this._animatables;
  20680. };
  20681. Skeleton.prototype.clone = function (name, id) {
  20682. var result = new Skeleton(name, id || name, this._scene);
  20683. for (var index = 0; index < this.bones.length; index++) {
  20684. var source = this.bones[index];
  20685. var parentBone = null;
  20686. if (source.getParent()) {
  20687. var parentIndex = this.bones.indexOf(source.getParent());
  20688. parentBone = result.bones[parentIndex];
  20689. }
  20690. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  20691. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  20692. }
  20693. return result;
  20694. };
  20695. return Skeleton;
  20696. })();
  20697. BABYLON.Skeleton = Skeleton;
  20698. })(BABYLON || (BABYLON = {}));
  20699. //# sourceMappingURL=babylon.skeleton.js.map
  20700. var BABYLON;
  20701. (function (BABYLON) {
  20702. var PostProcess = (function () {
  20703. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  20704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  20705. this.name = name;
  20706. this.width = -1;
  20707. this.height = -1;
  20708. this._reusable = false;
  20709. this._textures = new BABYLON.SmartArray(2);
  20710. this._currentRenderTextureInd = 0;
  20711. if (camera != null) {
  20712. this._camera = camera;
  20713. this._scene = camera.getScene();
  20714. camera.attachPostProcess(this);
  20715. this._engine = this._scene.getEngine();
  20716. }
  20717. else {
  20718. this._engine = engine;
  20719. }
  20720. this._renderRatio = ratio;
  20721. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  20722. this._reusable = reusable || false;
  20723. samplers = samplers || [];
  20724. samplers.push("textureSampler");
  20725. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  20726. }
  20727. PostProcess.prototype.isReusable = function () {
  20728. return this._reusable;
  20729. };
  20730. PostProcess.prototype.activate = function (camera, sourceTexture) {
  20731. camera = camera || this._camera;
  20732. var scene = camera.getScene();
  20733. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  20734. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  20735. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  20736. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  20737. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  20738. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  20739. if (this._textures.length > 0) {
  20740. for (var i = 0; i < this._textures.length; i++) {
  20741. this._engine._releaseTexture(this._textures.data[i]);
  20742. }
  20743. this._textures.reset();
  20744. }
  20745. this.width = desiredWidth;
  20746. this.height = desiredHeight;
  20747. 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 }));
  20748. if (this._reusable) {
  20749. 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 }));
  20750. }
  20751. if (this.onSizeChanged) {
  20752. this.onSizeChanged();
  20753. }
  20754. }
  20755. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  20756. if (this.onActivate) {
  20757. this.onActivate(camera);
  20758. }
  20759. // Clear
  20760. if (this.clearColor) {
  20761. this._engine.clear(this.clearColor, true, true);
  20762. }
  20763. else {
  20764. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  20765. }
  20766. if (this._reusable) {
  20767. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  20768. }
  20769. };
  20770. PostProcess.prototype.apply = function () {
  20771. // Check
  20772. if (!this._effect.isReady())
  20773. return null;
  20774. // States
  20775. this._engine.enableEffect(this._effect);
  20776. this._engine.setState(false);
  20777. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20778. this._engine.setDepthBuffer(false);
  20779. this._engine.setDepthWrite(false);
  20780. // Texture
  20781. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  20782. // Parameters
  20783. if (this.onApply) {
  20784. this.onApply(this._effect);
  20785. }
  20786. return this._effect;
  20787. };
  20788. PostProcess.prototype.dispose = function (camera) {
  20789. camera = camera || this._camera;
  20790. if (this._textures.length > 0) {
  20791. for (var i = 0; i < this._textures.length; i++) {
  20792. this._engine._releaseTexture(this._textures.data[i]);
  20793. }
  20794. this._textures.reset();
  20795. }
  20796. if (!camera) {
  20797. return;
  20798. }
  20799. camera.detachPostProcess(this);
  20800. var index = camera._postProcesses.indexOf(this);
  20801. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  20802. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  20803. }
  20804. };
  20805. return PostProcess;
  20806. })();
  20807. BABYLON.PostProcess = PostProcess;
  20808. })(BABYLON || (BABYLON = {}));
  20809. //# sourceMappingURL=babylon.postProcess.js.map
  20810. var BABYLON;
  20811. (function (BABYLON) {
  20812. var PostProcessManager = (function () {
  20813. function PostProcessManager(scene) {
  20814. this._vertexDeclaration = [2];
  20815. this._vertexStrideSize = 2 * 4;
  20816. this._scene = scene;
  20817. }
  20818. PostProcessManager.prototype._prepareBuffers = function () {
  20819. if (this._vertexBuffer) {
  20820. return;
  20821. }
  20822. // VBO
  20823. var vertices = [];
  20824. vertices.push(1, 1);
  20825. vertices.push(-1, 1);
  20826. vertices.push(-1, -1);
  20827. vertices.push(1, -1);
  20828. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  20829. // Indices
  20830. var indices = [];
  20831. indices.push(0);
  20832. indices.push(1);
  20833. indices.push(2);
  20834. indices.push(0);
  20835. indices.push(2);
  20836. indices.push(3);
  20837. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  20838. };
  20839. // Methods
  20840. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  20841. var postProcesses = this._scene.activeCamera._postProcesses;
  20842. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20843. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20844. return false;
  20845. }
  20846. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  20847. return true;
  20848. };
  20849. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  20850. var engine = this._scene.getEngine();
  20851. for (var index = 0; index < postProcesses.length; index++) {
  20852. if (index < postProcesses.length - 1) {
  20853. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  20854. }
  20855. else {
  20856. if (targetTexture) {
  20857. engine.bindFramebuffer(targetTexture);
  20858. }
  20859. else {
  20860. engine.restoreDefaultFramebuffer();
  20861. }
  20862. }
  20863. var pp = postProcesses[index];
  20864. var effect = pp.apply();
  20865. if (effect) {
  20866. if (pp.onBeforeRender) {
  20867. pp.onBeforeRender(effect);
  20868. }
  20869. // VBOs
  20870. this._prepareBuffers();
  20871. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20872. // Draw order
  20873. engine.draw(true, 0, 6);
  20874. }
  20875. }
  20876. // Restore depth buffer
  20877. engine.setDepthBuffer(true);
  20878. engine.setDepthWrite(true);
  20879. };
  20880. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  20881. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  20882. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20883. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20884. return;
  20885. }
  20886. var engine = this._scene.getEngine();
  20887. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  20888. if (index < postProcessesTakenIndices.length - 1) {
  20889. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  20890. }
  20891. else {
  20892. if (targetTexture) {
  20893. engine.bindFramebuffer(targetTexture);
  20894. }
  20895. else {
  20896. engine.restoreDefaultFramebuffer();
  20897. }
  20898. }
  20899. if (doNotPresent) {
  20900. break;
  20901. }
  20902. var pp = postProcesses[postProcessesTakenIndices[index]];
  20903. var effect = pp.apply();
  20904. if (effect) {
  20905. if (pp.onBeforeRender) {
  20906. pp.onBeforeRender(effect);
  20907. }
  20908. // VBOs
  20909. this._prepareBuffers();
  20910. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20911. // Draw order
  20912. engine.draw(true, 0, 6);
  20913. }
  20914. }
  20915. // Restore depth buffer
  20916. engine.setDepthBuffer(true);
  20917. engine.setDepthWrite(true);
  20918. };
  20919. PostProcessManager.prototype.dispose = function () {
  20920. if (this._vertexBuffer) {
  20921. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20922. this._vertexBuffer = null;
  20923. }
  20924. if (this._indexBuffer) {
  20925. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20926. this._indexBuffer = null;
  20927. }
  20928. };
  20929. return PostProcessManager;
  20930. })();
  20931. BABYLON.PostProcessManager = PostProcessManager;
  20932. })(BABYLON || (BABYLON = {}));
  20933. //# sourceMappingURL=babylon.postProcessManager.js.map
  20934. var __extends = this.__extends || function (d, b) {
  20935. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20936. function __() { this.constructor = d; }
  20937. __.prototype = b.prototype;
  20938. d.prototype = new __();
  20939. };
  20940. var BABYLON;
  20941. (function (BABYLON) {
  20942. var PassPostProcess = (function (_super) {
  20943. __extends(PassPostProcess, _super);
  20944. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20945. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  20946. }
  20947. return PassPostProcess;
  20948. })(BABYLON.PostProcess);
  20949. BABYLON.PassPostProcess = PassPostProcess;
  20950. })(BABYLON || (BABYLON = {}));
  20951. //# sourceMappingURL=babylon.passPostProcess.js.map
  20952. var __extends = this.__extends || function (d, b) {
  20953. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20954. function __() { this.constructor = d; }
  20955. __.prototype = b.prototype;
  20956. d.prototype = new __();
  20957. };
  20958. var BABYLON;
  20959. (function (BABYLON) {
  20960. var BlurPostProcess = (function (_super) {
  20961. __extends(BlurPostProcess, _super);
  20962. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  20963. var _this = this;
  20964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  20965. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  20966. this.direction = direction;
  20967. this.blurWidth = blurWidth;
  20968. this.onApply = function (effect) {
  20969. effect.setFloat2("screenSize", _this.width, _this.height);
  20970. effect.setVector2("direction", _this.direction);
  20971. effect.setFloat("blurWidth", _this.blurWidth);
  20972. };
  20973. }
  20974. return BlurPostProcess;
  20975. })(BABYLON.PostProcess);
  20976. BABYLON.BlurPostProcess = BlurPostProcess;
  20977. })(BABYLON || (BABYLON = {}));
  20978. //# sourceMappingURL=babylon.blurPostProcess.js.map
  20979. var __extends = this.__extends || function (d, b) {
  20980. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20981. function __() { this.constructor = d; }
  20982. __.prototype = b.prototype;
  20983. d.prototype = new __();
  20984. };
  20985. var BABYLON;
  20986. (function (BABYLON) {
  20987. var RefractionPostProcess = (function (_super) {
  20988. __extends(RefractionPostProcess, _super);
  20989. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  20990. var _this = this;
  20991. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  20992. this.color = color;
  20993. this.depth = depth;
  20994. this.colorLevel = colorLevel;
  20995. this.onActivate = function (cam) {
  20996. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  20997. };
  20998. this.onApply = function (effect) {
  20999. effect.setColor3("baseColor", _this.color);
  21000. effect.setFloat("depth", _this.depth);
  21001. effect.setFloat("colorLevel", _this.colorLevel);
  21002. effect.setTexture("refractionSampler", _this._refRexture);
  21003. };
  21004. }
  21005. // Methods
  21006. RefractionPostProcess.prototype.dispose = function (camera) {
  21007. if (this._refRexture) {
  21008. this._refRexture.dispose();
  21009. }
  21010. _super.prototype.dispose.call(this, camera);
  21011. };
  21012. return RefractionPostProcess;
  21013. })(BABYLON.PostProcess);
  21014. BABYLON.RefractionPostProcess = RefractionPostProcess;
  21015. })(BABYLON || (BABYLON = {}));
  21016. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  21017. var __extends = this.__extends || function (d, b) {
  21018. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21019. function __() { this.constructor = d; }
  21020. __.prototype = b.prototype;
  21021. d.prototype = new __();
  21022. };
  21023. var BABYLON;
  21024. (function (BABYLON) {
  21025. var BlackAndWhitePostProcess = (function (_super) {
  21026. __extends(BlackAndWhitePostProcess, _super);
  21027. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21028. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  21029. }
  21030. return BlackAndWhitePostProcess;
  21031. })(BABYLON.PostProcess);
  21032. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  21033. })(BABYLON || (BABYLON = {}));
  21034. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  21035. var __extends = this.__extends || function (d, b) {
  21036. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21037. function __() { this.constructor = d; }
  21038. __.prototype = b.prototype;
  21039. d.prototype = new __();
  21040. };
  21041. var BABYLON;
  21042. (function (BABYLON) {
  21043. var ConvolutionPostProcess = (function (_super) {
  21044. __extends(ConvolutionPostProcess, _super);
  21045. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  21046. var _this = this;
  21047. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  21048. this.kernel = kernel;
  21049. this.onApply = function (effect) {
  21050. effect.setFloat2("screenSize", _this.width, _this.height);
  21051. effect.setArray("kernel", _this.kernel);
  21052. };
  21053. }
  21054. // Statics
  21055. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  21056. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  21057. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  21058. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  21059. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  21060. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  21061. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  21062. return ConvolutionPostProcess;
  21063. })(BABYLON.PostProcess);
  21064. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  21065. })(BABYLON || (BABYLON = {}));
  21066. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  21067. var __extends = this.__extends || function (d, b) {
  21068. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21069. function __() { this.constructor = d; }
  21070. __.prototype = b.prototype;
  21071. d.prototype = new __();
  21072. };
  21073. var BABYLON;
  21074. (function (BABYLON) {
  21075. var FilterPostProcess = (function (_super) {
  21076. __extends(FilterPostProcess, _super);
  21077. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  21078. var _this = this;
  21079. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  21080. this.kernelMatrix = kernelMatrix;
  21081. this.onApply = function (effect) {
  21082. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  21083. };
  21084. }
  21085. return FilterPostProcess;
  21086. })(BABYLON.PostProcess);
  21087. BABYLON.FilterPostProcess = FilterPostProcess;
  21088. })(BABYLON || (BABYLON = {}));
  21089. //# sourceMappingURL=babylon.filterPostProcess.js.map
  21090. var __extends = this.__extends || function (d, b) {
  21091. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21092. function __() { this.constructor = d; }
  21093. __.prototype = b.prototype;
  21094. d.prototype = new __();
  21095. };
  21096. var BABYLON;
  21097. (function (BABYLON) {
  21098. var FxaaPostProcess = (function (_super) {
  21099. __extends(FxaaPostProcess, _super);
  21100. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21101. var _this = this;
  21102. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  21103. this.onSizeChanged = function () {
  21104. _this.texelWidth = 1.0 / _this.width;
  21105. _this.texelHeight = 1.0 / _this.height;
  21106. };
  21107. this.onApply = function (effect) {
  21108. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  21109. };
  21110. }
  21111. return FxaaPostProcess;
  21112. })(BABYLON.PostProcess);
  21113. BABYLON.FxaaPostProcess = FxaaPostProcess;
  21114. })(BABYLON || (BABYLON = {}));
  21115. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  21116. var BABYLON;
  21117. (function (BABYLON) {
  21118. var LensFlare = (function () {
  21119. function LensFlare(size, position, color, imgUrl, system) {
  21120. this.size = size;
  21121. this.position = position;
  21122. this.dispose = function () {
  21123. if (this.texture) {
  21124. this.texture.dispose();
  21125. }
  21126. // Remove from scene
  21127. var index = this._system.lensFlares.indexOf(this);
  21128. this._system.lensFlares.splice(index, 1);
  21129. };
  21130. this.color = color || new BABYLON.Color3(1, 1, 1);
  21131. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  21132. this._system = system;
  21133. system.lensFlares.push(this);
  21134. }
  21135. return LensFlare;
  21136. })();
  21137. BABYLON.LensFlare = LensFlare;
  21138. })(BABYLON || (BABYLON = {}));
  21139. //# sourceMappingURL=babylon.lensFlare.js.map
  21140. var BABYLON;
  21141. (function (BABYLON) {
  21142. var LensFlareSystem = (function () {
  21143. function LensFlareSystem(name, emitter, scene) {
  21144. this.name = name;
  21145. this.lensFlares = new Array();
  21146. this.borderLimit = 300;
  21147. this._vertexDeclaration = [2];
  21148. this._vertexStrideSize = 2 * 4;
  21149. this._isEnabled = true;
  21150. this._scene = scene;
  21151. this._emitter = emitter;
  21152. scene.lensFlareSystems.push(this);
  21153. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  21154. // VBO
  21155. var vertices = [];
  21156. vertices.push(1, 1);
  21157. vertices.push(-1, 1);
  21158. vertices.push(-1, -1);
  21159. vertices.push(1, -1);
  21160. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21161. // Indices
  21162. var indices = [];
  21163. indices.push(0);
  21164. indices.push(1);
  21165. indices.push(2);
  21166. indices.push(0);
  21167. indices.push(2);
  21168. indices.push(3);
  21169. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21170. // Effects
  21171. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  21172. }
  21173. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  21174. get: function () {
  21175. return this._isEnabled;
  21176. },
  21177. set: function (value) {
  21178. this._isEnabled = value;
  21179. },
  21180. enumerable: true,
  21181. configurable: true
  21182. });
  21183. LensFlareSystem.prototype.getScene = function () {
  21184. return this._scene;
  21185. };
  21186. LensFlareSystem.prototype.getEmitter = function () {
  21187. return this._emitter;
  21188. };
  21189. LensFlareSystem.prototype.getEmitterPosition = function () {
  21190. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  21191. };
  21192. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  21193. var position = this.getEmitterPosition();
  21194. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  21195. this._positionX = position.x;
  21196. this._positionY = position.y;
  21197. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  21198. if (position.z > 0) {
  21199. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  21200. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  21201. return true;
  21202. }
  21203. }
  21204. return false;
  21205. };
  21206. LensFlareSystem.prototype._isVisible = function () {
  21207. if (!this._isEnabled) {
  21208. return false;
  21209. }
  21210. var emitterPosition = this.getEmitterPosition();
  21211. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  21212. var distance = direction.length();
  21213. direction.normalize();
  21214. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  21215. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  21216. return !pickInfo.hit || pickInfo.distance > distance;
  21217. };
  21218. LensFlareSystem.prototype.render = function () {
  21219. if (!this._effect.isReady())
  21220. return false;
  21221. var engine = this._scene.getEngine();
  21222. var viewport = this._scene.activeCamera.viewport;
  21223. var globalViewport = viewport.toGlobal(engine);
  21224. // Position
  21225. if (!this.computeEffectivePosition(globalViewport)) {
  21226. return false;
  21227. }
  21228. // Visibility
  21229. if (!this._isVisible()) {
  21230. return false;
  21231. }
  21232. // Intensity
  21233. var awayX;
  21234. var awayY;
  21235. if (this._positionX < this.borderLimit + globalViewport.x) {
  21236. awayX = this.borderLimit + globalViewport.x - this._positionX;
  21237. }
  21238. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  21239. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  21240. }
  21241. else {
  21242. awayX = 0;
  21243. }
  21244. if (this._positionY < this.borderLimit + globalViewport.y) {
  21245. awayY = this.borderLimit + globalViewport.y - this._positionY;
  21246. }
  21247. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  21248. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  21249. }
  21250. else {
  21251. awayY = 0;
  21252. }
  21253. var away = (awayX > awayY) ? awayX : awayY;
  21254. if (away > this.borderLimit) {
  21255. away = this.borderLimit;
  21256. }
  21257. var intensity = 1.0 - (away / this.borderLimit);
  21258. if (intensity < 0) {
  21259. return false;
  21260. }
  21261. if (intensity > 1.0) {
  21262. intensity = 1.0;
  21263. }
  21264. // Position
  21265. var centerX = globalViewport.x + globalViewport.width / 2;
  21266. var centerY = globalViewport.y + globalViewport.height / 2;
  21267. var distX = centerX - this._positionX;
  21268. var distY = centerY - this._positionY;
  21269. // Effects
  21270. engine.enableEffect(this._effect);
  21271. engine.setState(false);
  21272. engine.setDepthBuffer(false);
  21273. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  21274. // VBOs
  21275. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21276. // Flares
  21277. for (var index = 0; index < this.lensFlares.length; index++) {
  21278. var flare = this.lensFlares[index];
  21279. var x = centerX - (distX * flare.position);
  21280. var y = centerY - (distY * flare.position);
  21281. var cw = flare.size;
  21282. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  21283. var cx = 2 * (x / globalViewport.width) - 1.0;
  21284. var cy = 1.0 - 2 * (y / globalViewport.height);
  21285. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  21286. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  21287. // Texture
  21288. this._effect.setTexture("textureSampler", flare.texture);
  21289. // Color
  21290. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  21291. // Draw order
  21292. engine.draw(true, 0, 6);
  21293. }
  21294. engine.setDepthBuffer(true);
  21295. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21296. return true;
  21297. };
  21298. LensFlareSystem.prototype.dispose = function () {
  21299. if (this._vertexBuffer) {
  21300. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21301. this._vertexBuffer = null;
  21302. }
  21303. if (this._indexBuffer) {
  21304. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21305. this._indexBuffer = null;
  21306. }
  21307. while (this.lensFlares.length) {
  21308. this.lensFlares[0].dispose();
  21309. }
  21310. // Remove from scene
  21311. var index = this._scene.lensFlareSystems.indexOf(this);
  21312. this._scene.lensFlareSystems.splice(index, 1);
  21313. };
  21314. return LensFlareSystem;
  21315. })();
  21316. BABYLON.LensFlareSystem = LensFlareSystem;
  21317. })(BABYLON || (BABYLON = {}));
  21318. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  21319. var BABYLON;
  21320. (function (BABYLON) {
  21321. var CannonJSPlugin = (function () {
  21322. function CannonJSPlugin() {
  21323. this._registeredMeshes = [];
  21324. this._physicsMaterials = [];
  21325. this.updateBodyPosition = function (mesh) {
  21326. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21327. var registeredMesh = this._registeredMeshes[index];
  21328. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21329. var body = registeredMesh.body;
  21330. var center = mesh.getBoundingInfo().boundingBox.center;
  21331. body.position.set(center.x, center.z, center.y);
  21332. body.quaternion.x = mesh.rotationQuaternion.x;
  21333. body.quaternion.z = mesh.rotationQuaternion.y;
  21334. body.quaternion.y = mesh.rotationQuaternion.z;
  21335. body.quaternion.w = -mesh.rotationQuaternion.w;
  21336. return;
  21337. }
  21338. }
  21339. };
  21340. }
  21341. CannonJSPlugin.prototype.initialize = function (iterations) {
  21342. if (iterations === void 0) { iterations = 10; }
  21343. this._world = new CANNON.World();
  21344. this._world.broadphase = new CANNON.NaiveBroadphase();
  21345. this._world.solver.iterations = iterations;
  21346. };
  21347. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21348. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21349. };
  21350. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21351. this._world.step(delta);
  21352. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21353. var registeredMesh = this._registeredMeshes[index];
  21354. if (registeredMesh.isChild) {
  21355. continue;
  21356. }
  21357. // Body position
  21358. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21359. var deltaPos = registeredMesh.delta;
  21360. if (deltaPos) {
  21361. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21362. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21363. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21364. }
  21365. else {
  21366. registeredMesh.mesh.position.x = bodyX;
  21367. registeredMesh.mesh.position.y = bodyZ;
  21368. registeredMesh.mesh.position.z = bodyY;
  21369. }
  21370. if (!registeredMesh.mesh.rotationQuaternion) {
  21371. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21372. }
  21373. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21374. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21375. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21376. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21377. }
  21378. };
  21379. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21380. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21381. };
  21382. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21383. this.unregisterMesh(mesh);
  21384. mesh.computeWorldMatrix(true);
  21385. switch (impostor) {
  21386. case BABYLON.PhysicsEngine.SphereImpostor:
  21387. var bbox = mesh.getBoundingInfo().boundingBox;
  21388. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21389. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21390. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21391. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21392. case BABYLON.PhysicsEngine.BoxImpostor:
  21393. bbox = mesh.getBoundingInfo().boundingBox;
  21394. var min = bbox.minimumWorld;
  21395. var max = bbox.maximumWorld;
  21396. var box = max.subtract(min).scale(0.5);
  21397. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21398. case BABYLON.PhysicsEngine.PlaneImpostor:
  21399. return this._createPlane(mesh, options);
  21400. case BABYLON.PhysicsEngine.MeshImpostor:
  21401. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21402. var rawFaces = mesh.getIndices();
  21403. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21404. }
  21405. return null;
  21406. };
  21407. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21408. var shape = new CANNON.Sphere(radius);
  21409. if (!options) {
  21410. return shape;
  21411. }
  21412. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21413. };
  21414. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21415. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21416. if (!options) {
  21417. return shape;
  21418. }
  21419. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21420. };
  21421. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21422. var shape = new CANNON.Plane();
  21423. if (!options) {
  21424. return shape;
  21425. }
  21426. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21427. };
  21428. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21429. var verts = [], faces = [];
  21430. mesh.computeWorldMatrix(true);
  21431. // Get vertices
  21432. for (var i = 0; i < rawVerts.length; i += 3) {
  21433. var transformed = BABYLON.Vector3.Zero();
  21434. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21435. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21436. }
  21437. // Get faces
  21438. for (var j = 0; j < rawFaces.length; j += 3) {
  21439. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21440. }
  21441. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21442. if (!options) {
  21443. return shape;
  21444. }
  21445. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21446. };
  21447. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21448. var index;
  21449. var mat;
  21450. for (index = 0; index < this._physicsMaterials.length; index++) {
  21451. mat = this._physicsMaterials[index];
  21452. if (mat.friction === friction && mat.restitution === restitution) {
  21453. return mat;
  21454. }
  21455. }
  21456. var currentMat = new CANNON.Material();
  21457. currentMat.friction = friction;
  21458. currentMat.restitution = restitution;
  21459. this._physicsMaterials.push(currentMat);
  21460. for (index = 0; index < this._physicsMaterials.length; index++) {
  21461. mat = this._physicsMaterials[index];
  21462. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21463. contactMaterial.contactEquationStiffness = 1e10;
  21464. contactMaterial.contactEquationRegularizationTime = 10;
  21465. this._world.addContactMaterial(contactMaterial);
  21466. }
  21467. return currentMat;
  21468. };
  21469. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21470. var initialRotation = null;
  21471. if (mesh.rotationQuaternion) {
  21472. initialRotation = mesh.rotationQuaternion.clone();
  21473. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21474. }
  21475. // The delta between the mesh position and the mesh bounding box center
  21476. var bbox = mesh.getBoundingInfo().boundingBox;
  21477. var deltaPosition = mesh.position.subtract(bbox.center);
  21478. var material = this._addMaterial(friction, restitution);
  21479. var body = new CANNON.RigidBody(mass, shape, material);
  21480. if (initialRotation) {
  21481. body.quaternion.x = initialRotation.x;
  21482. body.quaternion.z = initialRotation.y;
  21483. body.quaternion.y = initialRotation.z;
  21484. body.quaternion.w = -initialRotation.w;
  21485. }
  21486. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21487. this._world.add(body);
  21488. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21489. return body;
  21490. };
  21491. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21492. var compoundShape = new CANNON.Compound();
  21493. for (var index = 0; index < parts.length; index++) {
  21494. var mesh = parts[index].mesh;
  21495. var shape = this.registerMesh(mesh, parts[index].impostor);
  21496. if (index == 0) {
  21497. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21498. }
  21499. else {
  21500. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21501. }
  21502. }
  21503. var initialMesh = parts[0].mesh;
  21504. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21505. body.parts = parts;
  21506. return body;
  21507. };
  21508. CannonJSPlugin.prototype._unbindBody = function (body) {
  21509. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21510. var registeredMesh = this._registeredMeshes[index];
  21511. if (registeredMesh.body === body) {
  21512. registeredMesh.body = null;
  21513. registeredMesh.delta = 0;
  21514. }
  21515. }
  21516. };
  21517. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21518. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21519. var registeredMesh = this._registeredMeshes[index];
  21520. if (registeredMesh.mesh === mesh) {
  21521. // Remove body
  21522. if (registeredMesh.body) {
  21523. this._world.remove(registeredMesh.body);
  21524. this._unbindBody(registeredMesh.body);
  21525. }
  21526. this._registeredMeshes.splice(index, 1);
  21527. return;
  21528. }
  21529. }
  21530. };
  21531. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21532. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21533. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21534. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21535. var registeredMesh = this._registeredMeshes[index];
  21536. if (registeredMesh.mesh === mesh) {
  21537. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21538. return;
  21539. }
  21540. }
  21541. };
  21542. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21543. var body1 = null, body2 = null;
  21544. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21545. var registeredMesh = this._registeredMeshes[index];
  21546. if (registeredMesh.mesh === mesh1) {
  21547. body1 = registeredMesh.body;
  21548. }
  21549. else if (registeredMesh.mesh === mesh2) {
  21550. body2 = registeredMesh.body;
  21551. }
  21552. }
  21553. if (!body1 || !body2) {
  21554. return false;
  21555. }
  21556. 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));
  21557. this._world.addConstraint(constraint);
  21558. return true;
  21559. };
  21560. CannonJSPlugin.prototype.dispose = function () {
  21561. while (this._registeredMeshes.length) {
  21562. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21563. }
  21564. };
  21565. CannonJSPlugin.prototype.isSupported = function () {
  21566. return window.CANNON !== undefined;
  21567. };
  21568. return CannonJSPlugin;
  21569. })();
  21570. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21571. })(BABYLON || (BABYLON = {}));
  21572. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21573. var BABYLON;
  21574. (function (BABYLON) {
  21575. var OimoJSPlugin = (function () {
  21576. function OimoJSPlugin() {
  21577. this._registeredMeshes = [];
  21578. /**
  21579. * Update the body position according to the mesh position
  21580. * @param mesh
  21581. */
  21582. this.updateBodyPosition = function (mesh) {
  21583. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21584. var registeredMesh = this._registeredMeshes[index];
  21585. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21586. var body = registeredMesh.body.body;
  21587. mesh.computeWorldMatrix(true);
  21588. var center = mesh.getBoundingInfo().boundingBox.center;
  21589. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  21590. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  21591. body.sleeping = false;
  21592. return;
  21593. }
  21594. // Case where the parent has been updated
  21595. if (registeredMesh.mesh.parent === mesh) {
  21596. mesh.computeWorldMatrix(true);
  21597. registeredMesh.mesh.computeWorldMatrix(true);
  21598. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  21599. var absoluteRotation = mesh.rotation;
  21600. body = registeredMesh.body.body;
  21601. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  21602. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  21603. body.sleeping = false;
  21604. return;
  21605. }
  21606. }
  21607. };
  21608. }
  21609. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  21610. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21611. };
  21612. OimoJSPlugin.prototype.initialize = function (iterations) {
  21613. this._world = new OIMO.World();
  21614. this._world.clear();
  21615. };
  21616. OimoJSPlugin.prototype.setGravity = function (gravity) {
  21617. this._world.gravity = gravity;
  21618. };
  21619. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21620. var body = null;
  21621. this.unregisterMesh(mesh);
  21622. mesh.computeWorldMatrix(true);
  21623. var initialRotation = null;
  21624. if (mesh.rotationQuaternion) {
  21625. initialRotation = mesh.rotationQuaternion.clone();
  21626. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21627. mesh.computeWorldMatrix(true);
  21628. }
  21629. var bbox = mesh.getBoundingInfo().boundingBox;
  21630. // The delta between the mesh position and the mesh bounding box center
  21631. var deltaPosition = mesh.position.subtract(bbox.center);
  21632. // Transform delta position with the rotation
  21633. if (initialRotation) {
  21634. var m = new BABYLON.Matrix();
  21635. initialRotation.toRotationMatrix(m);
  21636. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  21637. }
  21638. // register mesh
  21639. switch (impostor) {
  21640. case BABYLON.PhysicsEngine.SphereImpostor:
  21641. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21642. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21643. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21644. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21645. body = new OIMO.Body({
  21646. type: 'sphere',
  21647. size: [size],
  21648. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21649. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21650. move: options.mass != 0,
  21651. config: [options.mass, options.friction, options.restitution],
  21652. world: this._world
  21653. });
  21654. break;
  21655. case BABYLON.PhysicsEngine.PlaneImpostor:
  21656. //Oimo "fakes" a cylinder as a box, so why don't we!
  21657. case BABYLON.PhysicsEngine.CylinderImpostor:
  21658. case BABYLON.PhysicsEngine.BoxImpostor:
  21659. var min = bbox.minimumWorld;
  21660. var max = bbox.maximumWorld;
  21661. var box = max.subtract(min);
  21662. var sizeX = this._checkWithEpsilon(box.x);
  21663. var sizeY = this._checkWithEpsilon(box.y);
  21664. var sizeZ = this._checkWithEpsilon(box.z);
  21665. body = new OIMO.Body({
  21666. type: 'box',
  21667. size: [sizeX, sizeY, sizeZ],
  21668. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21669. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21670. move: options.mass != 0,
  21671. config: [options.mass, options.friction, options.restitution],
  21672. world: this._world
  21673. });
  21674. break;
  21675. }
  21676. //If quaternion was set as the rotation of the object
  21677. if (initialRotation) {
  21678. //We have to access the rigid body's properties to set the quaternion.
  21679. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  21680. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  21681. //update the internal rotation matrix
  21682. body.body.syncShapes();
  21683. }
  21684. this._registeredMeshes.push({
  21685. mesh: mesh,
  21686. body: body,
  21687. delta: deltaPosition
  21688. });
  21689. return body;
  21690. };
  21691. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21692. var types = [], sizes = [], positions = [], rotations = [];
  21693. var initialMesh = parts[0].mesh;
  21694. for (var index = 0; index < parts.length; index++) {
  21695. var part = parts[index];
  21696. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  21697. types.push(bodyParameters.type);
  21698. sizes.push.apply(sizes, bodyParameters.size);
  21699. positions.push.apply(positions, bodyParameters.pos);
  21700. rotations.push.apply(rotations, bodyParameters.rot);
  21701. }
  21702. var body = new OIMO.Body({
  21703. type: types,
  21704. size: sizes,
  21705. pos: positions,
  21706. rot: rotations,
  21707. move: options.mass != 0,
  21708. config: [options.mass, options.friction, options.restitution],
  21709. world: this._world
  21710. });
  21711. this._registeredMeshes.push({
  21712. mesh: initialMesh,
  21713. body: body
  21714. });
  21715. return body;
  21716. };
  21717. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  21718. var bodyParameters = null;
  21719. var mesh = part.mesh;
  21720. // We need the bounding box/sphere info to compute the physics body
  21721. mesh.computeWorldMatrix();
  21722. switch (part.impostor) {
  21723. case BABYLON.PhysicsEngine.SphereImpostor:
  21724. var bbox = mesh.getBoundingInfo().boundingBox;
  21725. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21726. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21727. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21728. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21729. bodyParameters = {
  21730. type: 'sphere',
  21731. /* bug with oimo : sphere needs 3 sizes in this case */
  21732. size: [size, -1, -1],
  21733. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  21734. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  21735. };
  21736. break;
  21737. case BABYLON.PhysicsEngine.PlaneImpostor:
  21738. case BABYLON.PhysicsEngine.BoxImpostor:
  21739. bbox = mesh.getBoundingInfo().boundingBox;
  21740. var min = bbox.minimumWorld;
  21741. var max = bbox.maximumWorld;
  21742. var box = max.subtract(min);
  21743. var sizeX = this._checkWithEpsilon(box.x);
  21744. var sizeY = this._checkWithEpsilon(box.y);
  21745. var sizeZ = this._checkWithEpsilon(box.z);
  21746. var relativePosition = mesh.position;
  21747. bodyParameters = {
  21748. type: 'box',
  21749. size: [sizeX, sizeY, sizeZ],
  21750. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  21751. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  21752. };
  21753. break;
  21754. }
  21755. return bodyParameters;
  21756. };
  21757. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  21758. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21759. var registeredMesh = this._registeredMeshes[index];
  21760. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21761. if (registeredMesh.body) {
  21762. this._world.removeRigidBody(registeredMesh.body.body);
  21763. this._unbindBody(registeredMesh.body);
  21764. }
  21765. this._registeredMeshes.splice(index, 1);
  21766. return;
  21767. }
  21768. }
  21769. };
  21770. OimoJSPlugin.prototype._unbindBody = function (body) {
  21771. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21772. var registeredMesh = this._registeredMeshes[index];
  21773. if (registeredMesh.body === body) {
  21774. registeredMesh.body = null;
  21775. }
  21776. }
  21777. };
  21778. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21779. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21780. var registeredMesh = this._registeredMeshes[index];
  21781. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21782. // Get object mass to have a behaviour similar to cannon.js
  21783. var mass = registeredMesh.body.body.massInfo.mass;
  21784. // The force is scaled with the mass of object
  21785. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  21786. return;
  21787. }
  21788. }
  21789. };
  21790. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21791. var body1 = null, body2 = null;
  21792. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21793. var registeredMesh = this._registeredMeshes[index];
  21794. if (registeredMesh.mesh === mesh1) {
  21795. body1 = registeredMesh.body.body;
  21796. }
  21797. else if (registeredMesh.mesh === mesh2) {
  21798. body2 = registeredMesh.body.body;
  21799. }
  21800. }
  21801. if (!body1 || !body2) {
  21802. return false;
  21803. }
  21804. if (!options) {
  21805. options = {};
  21806. }
  21807. new OIMO.Link({
  21808. type: options.type,
  21809. body1: body1,
  21810. body2: body2,
  21811. min: options.min,
  21812. max: options.max,
  21813. axe1: options.axe1,
  21814. axe2: options.axe2,
  21815. pos1: [pivot1.x, pivot1.y, pivot1.z],
  21816. pos2: [pivot2.x, pivot2.y, pivot2.z],
  21817. collision: options.collision,
  21818. spring: options.spring,
  21819. world: this._world
  21820. });
  21821. return true;
  21822. };
  21823. OimoJSPlugin.prototype.dispose = function () {
  21824. this._world.clear();
  21825. while (this._registeredMeshes.length) {
  21826. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21827. }
  21828. };
  21829. OimoJSPlugin.prototype.isSupported = function () {
  21830. return OIMO !== undefined;
  21831. };
  21832. OimoJSPlugin.prototype._getLastShape = function (body) {
  21833. var lastShape = body.shapes;
  21834. while (lastShape.next) {
  21835. lastShape = lastShape.next;
  21836. }
  21837. return lastShape;
  21838. };
  21839. OimoJSPlugin.prototype.runOneStep = function (time) {
  21840. this._world.step();
  21841. // Update the position of all registered meshes
  21842. var i = this._registeredMeshes.length;
  21843. var m;
  21844. while (i--) {
  21845. var body = this._registeredMeshes[i].body.body;
  21846. var mesh = this._registeredMeshes[i].mesh;
  21847. var delta = this._registeredMeshes[i].delta;
  21848. if (!body.sleeping) {
  21849. if (body.shapes.next) {
  21850. var parentShape = this._getLastShape(body);
  21851. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  21852. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  21853. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  21854. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  21855. if (!mesh.rotationQuaternion) {
  21856. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21857. }
  21858. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  21859. mesh.computeWorldMatrix();
  21860. }
  21861. else {
  21862. m = body.getMatrix();
  21863. mtx = BABYLON.Matrix.FromArray(m);
  21864. // Body position
  21865. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  21866. if (!delta) {
  21867. mesh.position.x = bodyX;
  21868. mesh.position.y = bodyY;
  21869. mesh.position.z = bodyZ;
  21870. }
  21871. else {
  21872. mesh.position.x = bodyX + delta.x;
  21873. mesh.position.y = bodyY + delta.y;
  21874. mesh.position.z = bodyZ + delta.z;
  21875. }
  21876. if (!mesh.rotationQuaternion) {
  21877. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21878. }
  21879. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  21880. mesh.computeWorldMatrix();
  21881. }
  21882. }
  21883. }
  21884. };
  21885. return OimoJSPlugin;
  21886. })();
  21887. BABYLON.OimoJSPlugin = OimoJSPlugin;
  21888. })(BABYLON || (BABYLON = {}));
  21889. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  21890. var BABYLON;
  21891. (function (BABYLON) {
  21892. var PhysicsEngine = (function () {
  21893. function PhysicsEngine(plugin) {
  21894. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  21895. }
  21896. PhysicsEngine.prototype._initialize = function (gravity) {
  21897. this._currentPlugin.initialize();
  21898. this._setGravity(gravity);
  21899. };
  21900. PhysicsEngine.prototype._runOneStep = function (delta) {
  21901. if (delta > 0.1) {
  21902. delta = 0.1;
  21903. }
  21904. else if (delta <= 0) {
  21905. delta = 1.0 / 60.0;
  21906. }
  21907. this._currentPlugin.runOneStep(delta);
  21908. };
  21909. PhysicsEngine.prototype._setGravity = function (gravity) {
  21910. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  21911. this._currentPlugin.setGravity(this.gravity);
  21912. };
  21913. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  21914. return this._currentPlugin.registerMesh(mesh, impostor, options);
  21915. };
  21916. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  21917. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  21918. };
  21919. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  21920. this._currentPlugin.unregisterMesh(mesh);
  21921. };
  21922. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  21923. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  21924. };
  21925. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21926. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  21927. };
  21928. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  21929. this._currentPlugin.updateBodyPosition(mesh);
  21930. };
  21931. PhysicsEngine.prototype.dispose = function () {
  21932. this._currentPlugin.dispose();
  21933. };
  21934. PhysicsEngine.prototype.isSupported = function () {
  21935. return this._currentPlugin.isSupported();
  21936. };
  21937. // Statics
  21938. PhysicsEngine.NoImpostor = 0;
  21939. PhysicsEngine.SphereImpostor = 1;
  21940. PhysicsEngine.BoxImpostor = 2;
  21941. PhysicsEngine.PlaneImpostor = 3;
  21942. PhysicsEngine.MeshImpostor = 4;
  21943. PhysicsEngine.CapsuleImpostor = 5;
  21944. PhysicsEngine.ConeImpostor = 6;
  21945. PhysicsEngine.CylinderImpostor = 7;
  21946. PhysicsEngine.ConvexHullImpostor = 8;
  21947. PhysicsEngine.Epsilon = 0.001;
  21948. return PhysicsEngine;
  21949. })();
  21950. BABYLON.PhysicsEngine = PhysicsEngine;
  21951. })(BABYLON || (BABYLON = {}));
  21952. //# sourceMappingURL=babylon.physicsEngine.js.map
  21953. var BABYLON;
  21954. (function (BABYLON) {
  21955. var serializeLight = function (light) {
  21956. var serializationObject = {};
  21957. serializationObject.name = light.name;
  21958. serializationObject.id = light.id;
  21959. serializationObject.tags = BABYLON.Tags.GetTags(light);
  21960. if (light instanceof BABYLON.PointLight) {
  21961. serializationObject.type = 0;
  21962. serializationObject.position = light.position.asArray();
  21963. }
  21964. else if (light instanceof BABYLON.DirectionalLight) {
  21965. serializationObject.type = 1;
  21966. var directionalLight = light;
  21967. serializationObject.position = directionalLight.position.asArray();
  21968. serializationObject.direction = directionalLight.direction.asArray();
  21969. }
  21970. else if (light instanceof BABYLON.SpotLight) {
  21971. serializationObject.type = 2;
  21972. var spotLight = light;
  21973. serializationObject.position = spotLight.position.asArray();
  21974. serializationObject.direction = spotLight.position.asArray();
  21975. serializationObject.angle = spotLight.angle;
  21976. serializationObject.exponent = spotLight.exponent;
  21977. }
  21978. else if (light instanceof BABYLON.HemisphericLight) {
  21979. serializationObject.type = 3;
  21980. var hemisphericLight = light;
  21981. serializationObject.direction = hemisphericLight.direction.asArray();
  21982. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  21983. }
  21984. if (light.intensity) {
  21985. serializationObject.intensity = light.intensity;
  21986. }
  21987. serializationObject.range = light.range;
  21988. serializationObject.diffuse = light.diffuse.asArray();
  21989. serializationObject.specular = light.specular.asArray();
  21990. return serializationObject;
  21991. };
  21992. var serializeFresnelParameter = function (fresnelParameter) {
  21993. var serializationObject = {};
  21994. serializationObject.isEnabled = fresnelParameter.isEnabled;
  21995. serializationObject.leftColor = fresnelParameter.leftColor;
  21996. serializationObject.rightColor = fresnelParameter.rightColor;
  21997. serializationObject.bias = fresnelParameter.bias;
  21998. serializationObject.power = fresnelParameter.power;
  21999. return serializationObject;
  22000. };
  22001. var appendAnimations = function (source, destination) {
  22002. if (source.animations) {
  22003. destination.animations = [];
  22004. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22005. var animation = source.animations[animationIndex];
  22006. destination.animations.push(serializeAnimation(animation));
  22007. }
  22008. }
  22009. };
  22010. var serializeCamera = function (camera) {
  22011. var serializationObject = {};
  22012. serializationObject.name = camera.name;
  22013. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  22014. serializationObject.id = camera.id;
  22015. serializationObject.position = camera.position.asArray();
  22016. // Parent
  22017. if (camera.parent) {
  22018. serializationObject.parentId = camera.parent.id;
  22019. }
  22020. serializationObject.fov = camera.fov;
  22021. serializationObject.minZ = camera.minZ;
  22022. serializationObject.maxZ = camera.maxZ;
  22023. serializationObject.inertia = camera.inertia;
  22024. //setting the type
  22025. if (camera instanceof BABYLON.FreeCamera) {
  22026. serializationObject.type = "FreeCamera";
  22027. }
  22028. else if (camera instanceof BABYLON.ArcRotateCamera) {
  22029. serializationObject.type = "ArcRotateCamera";
  22030. }
  22031. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  22032. serializationObject.type = "AnaglyphArcRotateCamera";
  22033. }
  22034. else if (camera instanceof BABYLON.GamepadCamera) {
  22035. serializationObject.type = "GamepadCamera";
  22036. }
  22037. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  22038. serializationObject.type = "AnaglyphFreeCamera";
  22039. }
  22040. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  22041. serializationObject.type = "DeviceOrientationCamera";
  22042. }
  22043. else if (camera instanceof BABYLON.FollowCamera) {
  22044. serializationObject.type = "FollowCamera";
  22045. }
  22046. else if (camera instanceof BABYLON.TouchCamera) {
  22047. serializationObject.type = "TouchCamera";
  22048. }
  22049. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  22050. serializationObject.type = "VirtualJoysticksCamera";
  22051. }
  22052. else if (camera instanceof BABYLON.WebVRCamera) {
  22053. serializationObject.type = "WebVRCamera";
  22054. }
  22055. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  22056. serializationObject.type = "VRDeviceOrientationCamera";
  22057. }
  22058. //special properties of specific cameras
  22059. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  22060. var arcCamera = camera;
  22061. serializationObject.alpha = arcCamera.alpha;
  22062. serializationObject.beta = arcCamera.beta;
  22063. serializationObject.radius = arcCamera.radius;
  22064. if (arcCamera.target && arcCamera.target.id) {
  22065. serializationObject.lockedTargetId = arcCamera.target.id;
  22066. }
  22067. }
  22068. else if (camera instanceof BABYLON.FollowCamera) {
  22069. var followCam = camera;
  22070. serializationObject.radius = followCam.radius;
  22071. serializationObject.heightOffset = followCam.heightOffset;
  22072. serializationObject.rotationOffset = followCam.rotationOffset;
  22073. }
  22074. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  22075. //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.
  22076. if (camera['_eyeSpace'] !== undefined) {
  22077. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  22078. }
  22079. }
  22080. //general properties that not all cameras have. The [] is due to typescript's type safety
  22081. if (camera['speed'] !== undefined) {
  22082. serializationObject.speed = camera['speed'];
  22083. }
  22084. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  22085. serializationObject.target = camera['target'].asArray();
  22086. }
  22087. // Target
  22088. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  22089. serializationObject.rotation = camera['rotation'].asArray();
  22090. }
  22091. // Locked target
  22092. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  22093. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  22094. }
  22095. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  22096. serializationObject.applyGravity = camera['applyGravity'] || false;
  22097. if (camera['ellipsoid']) {
  22098. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  22099. }
  22100. // Animations
  22101. appendAnimations(camera, serializationObject);
  22102. // Layer mask
  22103. serializationObject.layerMask = camera.layerMask;
  22104. return serializationObject;
  22105. };
  22106. var serializeAnimation = function (animation) {
  22107. var serializationObject = {};
  22108. serializationObject.name = animation.name;
  22109. serializationObject.property = animation.targetProperty;
  22110. serializationObject.framePerSecond = animation.framePerSecond;
  22111. serializationObject.dataType = animation.dataType;
  22112. serializationObject.loopBehavior = animation.loopMode;
  22113. var dataType = animation.dataType;
  22114. serializationObject.keys = [];
  22115. var keys = animation.getKeys();
  22116. for (var index = 0; index < keys.length; index++) {
  22117. var animationKey = keys[index];
  22118. var key = {};
  22119. key.frame = animationKey.frame;
  22120. switch (dataType) {
  22121. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  22122. key.values = [animationKey.value];
  22123. break;
  22124. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  22125. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  22126. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  22127. key.values = animationKey.value.asArray();
  22128. break;
  22129. }
  22130. serializationObject.keys.push(key);
  22131. }
  22132. return serializationObject;
  22133. };
  22134. var serializeMultiMaterial = function (material) {
  22135. var serializationObject = {};
  22136. serializationObject.name = material.name;
  22137. serializationObject.id = material.id;
  22138. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22139. serializationObject.materials = [];
  22140. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  22141. var subMat = material.subMaterials[matIndex];
  22142. if (subMat) {
  22143. serializationObject.materials.push(subMat.id);
  22144. }
  22145. else {
  22146. serializationObject.materials.push(null);
  22147. }
  22148. }
  22149. return serializationObject;
  22150. };
  22151. var serializeMaterial = function (material) {
  22152. var serializationObject = {};
  22153. serializationObject.name = material.name;
  22154. serializationObject.ambient = material.ambientColor.asArray();
  22155. serializationObject.diffuse = material.diffuseColor.asArray();
  22156. serializationObject.specular = material.specularColor.asArray();
  22157. serializationObject.specularPower = material.specularPower;
  22158. serializationObject.emissive = material.emissiveColor.asArray();
  22159. serializationObject.alpha = material.alpha;
  22160. serializationObject.id = material.id;
  22161. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22162. serializationObject.backFaceCulling = material.backFaceCulling;
  22163. if (material.diffuseTexture) {
  22164. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  22165. }
  22166. if (material.diffuseFresnelParameters) {
  22167. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  22168. }
  22169. if (material.ambientTexture) {
  22170. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  22171. }
  22172. if (material.opacityTexture) {
  22173. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  22174. }
  22175. if (material.opacityFresnelParameters) {
  22176. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  22177. }
  22178. if (material.reflectionTexture) {
  22179. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  22180. }
  22181. if (material.reflectionFresnelParameters) {
  22182. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  22183. }
  22184. if (material.emissiveTexture) {
  22185. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  22186. }
  22187. if (material.emissiveFresnelParameters) {
  22188. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  22189. }
  22190. if (material.specularTexture) {
  22191. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  22192. }
  22193. if (material.bumpTexture) {
  22194. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  22195. }
  22196. return serializationObject;
  22197. };
  22198. var serializeTexture = function (texture) {
  22199. var serializationObject = {};
  22200. if (!texture.name) {
  22201. return null;
  22202. }
  22203. if (texture instanceof BABYLON.CubeTexture) {
  22204. serializationObject.name = texture.name;
  22205. serializationObject.hasAlpha = texture.hasAlpha;
  22206. serializationObject.level = texture.level;
  22207. serializationObject.coordinatesMode = texture.coordinatesMode;
  22208. return serializationObject;
  22209. }
  22210. if (texture instanceof BABYLON.MirrorTexture) {
  22211. var mirrorTexture = texture;
  22212. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  22213. serializationObject.renderList = [];
  22214. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  22215. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  22216. }
  22217. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  22218. }
  22219. else if (texture instanceof BABYLON.RenderTargetTexture) {
  22220. var renderTargetTexture = texture;
  22221. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  22222. serializationObject.renderList = [];
  22223. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  22224. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  22225. }
  22226. }
  22227. var regularTexture = texture;
  22228. serializationObject.name = texture.name;
  22229. serializationObject.hasAlpha = texture.hasAlpha;
  22230. serializationObject.level = texture.level;
  22231. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  22232. serializationObject.coordinatesMode = texture.coordinatesMode;
  22233. serializationObject.uOffset = regularTexture.uOffset;
  22234. serializationObject.vOffset = regularTexture.vOffset;
  22235. serializationObject.uScale = regularTexture.uScale;
  22236. serializationObject.vScale = regularTexture.vScale;
  22237. serializationObject.uAng = regularTexture.uAng;
  22238. serializationObject.vAng = regularTexture.vAng;
  22239. serializationObject.wAng = regularTexture.wAng;
  22240. serializationObject.wrapU = texture.wrapU;
  22241. serializationObject.wrapV = texture.wrapV;
  22242. // Animations
  22243. appendAnimations(texture, serializationObject);
  22244. return serializationObject;
  22245. };
  22246. var serializeSkeleton = function (skeleton) {
  22247. var serializationObject = {};
  22248. serializationObject.name = skeleton.name;
  22249. serializationObject.id = skeleton.id;
  22250. serializationObject.bones = [];
  22251. for (var index = 0; index < skeleton.bones.length; index++) {
  22252. var bone = skeleton.bones[index];
  22253. var serializedBone = {
  22254. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  22255. name: bone.name,
  22256. matrix: bone.getLocalMatrix().toArray()
  22257. };
  22258. serializationObject.bones.push(serializedBone);
  22259. if (bone.animations && bone.animations.length > 0) {
  22260. serializedBone.animation = serializeAnimation(bone.animations[0]);
  22261. }
  22262. }
  22263. return serializationObject;
  22264. };
  22265. var serializeParticleSystem = function (particleSystem) {
  22266. var serializationObject = {};
  22267. serializationObject.emitterId = particleSystem.emitter.id;
  22268. serializationObject.capacity = particleSystem.getCapacity();
  22269. if (particleSystem.particleTexture) {
  22270. serializationObject.textureName = particleSystem.particleTexture.name;
  22271. }
  22272. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  22273. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  22274. serializationObject.minSize = particleSystem.minSize;
  22275. serializationObject.maxSize = particleSystem.maxSize;
  22276. serializationObject.minLifeTime = particleSystem.minLifeTime;
  22277. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  22278. serializationObject.emitRate = particleSystem.emitRate;
  22279. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  22280. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  22281. serializationObject.gravity = particleSystem.gravity.asArray();
  22282. serializationObject.direction1 = particleSystem.direction1.asArray();
  22283. serializationObject.direction2 = particleSystem.direction2.asArray();
  22284. serializationObject.color1 = particleSystem.color1.asArray();
  22285. serializationObject.color2 = particleSystem.color2.asArray();
  22286. serializationObject.colorDead = particleSystem.colorDead.asArray();
  22287. serializationObject.updateSpeed = particleSystem.updateSpeed;
  22288. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  22289. serializationObject.textureMask = particleSystem.textureMask.asArray();
  22290. serializationObject.blendMode = particleSystem.blendMode;
  22291. return serializationObject;
  22292. };
  22293. var serializeLensFlareSystem = function (lensFlareSystem) {
  22294. var serializationObject = {};
  22295. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  22296. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  22297. serializationObject.flares = [];
  22298. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  22299. var flare = lensFlareSystem.lensFlares[index];
  22300. serializationObject.flares.push({
  22301. size: flare.size,
  22302. position: flare.position,
  22303. color: flare.color.asArray(),
  22304. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  22305. });
  22306. }
  22307. return serializationObject;
  22308. };
  22309. var serializeShadowGenerator = function (light) {
  22310. var serializationObject = {};
  22311. var shadowGenerator = light.getShadowGenerator();
  22312. serializationObject.lightId = light.id;
  22313. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  22314. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  22315. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  22316. serializationObject.renderList = [];
  22317. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  22318. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  22319. serializationObject.renderList.push(mesh.id);
  22320. }
  22321. return serializationObject;
  22322. };
  22323. var serializedGeometries = [];
  22324. var serializeGeometry = function (geometry, serializationGeometries) {
  22325. if (serializedGeometries[geometry.id]) {
  22326. return;
  22327. }
  22328. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  22329. serializationGeometries.boxes.push(serializeBox(geometry));
  22330. }
  22331. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  22332. serializationGeometries.spheres.push(serializeSphere(geometry));
  22333. }
  22334. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  22335. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  22336. }
  22337. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  22338. serializationGeometries.toruses.push(serializeTorus(geometry));
  22339. }
  22340. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  22341. serializationGeometries.grounds.push(serializeGround(geometry));
  22342. }
  22343. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  22344. serializationGeometries.planes.push(serializePlane(geometry));
  22345. }
  22346. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  22347. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  22348. }
  22349. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  22350. throw new Error("Unknow primitive type");
  22351. }
  22352. else {
  22353. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  22354. }
  22355. serializedGeometries[geometry.id] = true;
  22356. };
  22357. var serializeGeometryBase = function (geometry) {
  22358. var serializationObject = {};
  22359. serializationObject.id = geometry.id;
  22360. if (BABYLON.Tags.HasTags(geometry)) {
  22361. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  22362. }
  22363. return serializationObject;
  22364. };
  22365. var serializeVertexData = function (vertexData) {
  22366. var serializationObject = serializeGeometryBase(vertexData);
  22367. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22368. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22369. }
  22370. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22371. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22372. }
  22373. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22374. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22375. }
  22376. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22377. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22378. }
  22379. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22380. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22381. }
  22382. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22383. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22384. serializationObject.matricesIndices._isExpanded = true;
  22385. }
  22386. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22387. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22388. }
  22389. serializationObject.indices = vertexData.getIndices();
  22390. return serializationObject;
  22391. };
  22392. var serializePrimitive = function (primitive) {
  22393. var serializationObject = serializeGeometryBase(primitive);
  22394. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  22395. return serializationObject;
  22396. };
  22397. var serializeBox = function (box) {
  22398. var serializationObject = serializePrimitive(box);
  22399. serializationObject.size = box.size;
  22400. return serializationObject;
  22401. };
  22402. var serializeSphere = function (sphere) {
  22403. var serializationObject = serializePrimitive(sphere);
  22404. serializationObject.segments = sphere.segments;
  22405. serializationObject.diameter = sphere.diameter;
  22406. return serializationObject;
  22407. };
  22408. var serializeCylinder = function (cylinder) {
  22409. var serializationObject = serializePrimitive(cylinder);
  22410. serializationObject.height = cylinder.height;
  22411. serializationObject.diameterTop = cylinder.diameterTop;
  22412. serializationObject.diameterBottom = cylinder.diameterBottom;
  22413. serializationObject.tessellation = cylinder.tessellation;
  22414. return serializationObject;
  22415. };
  22416. var serializeTorus = function (torus) {
  22417. var serializationObject = serializePrimitive(torus);
  22418. serializationObject.diameter = torus.diameter;
  22419. serializationObject.thickness = torus.thickness;
  22420. serializationObject.tessellation = torus.tessellation;
  22421. return serializationObject;
  22422. };
  22423. var serializeGround = function (ground) {
  22424. var serializationObject = serializePrimitive(ground);
  22425. serializationObject.width = ground.width;
  22426. serializationObject.height = ground.height;
  22427. serializationObject.subdivisions = ground.subdivisions;
  22428. return serializationObject;
  22429. };
  22430. var serializePlane = function (plane) {
  22431. var serializationObject = serializePrimitive(plane);
  22432. serializationObject.size = plane.size;
  22433. return serializationObject;
  22434. };
  22435. var serializeTorusKnot = function (torusKnot) {
  22436. var serializationObject = serializePrimitive(torusKnot);
  22437. serializationObject.radius = torusKnot.radius;
  22438. serializationObject.tube = torusKnot.tube;
  22439. serializationObject.radialSegments = torusKnot.radialSegments;
  22440. serializationObject.tubularSegments = torusKnot.tubularSegments;
  22441. serializationObject.p = torusKnot.p;
  22442. serializationObject.q = torusKnot.q;
  22443. return serializationObject;
  22444. };
  22445. var serializeMesh = function (mesh, serializationScene) {
  22446. var serializationObject = {};
  22447. serializationObject.name = mesh.name;
  22448. serializationObject.id = mesh.id;
  22449. if (BABYLON.Tags.HasTags(mesh)) {
  22450. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  22451. }
  22452. serializationObject.position = mesh.position.asArray();
  22453. if (mesh.rotationQuaternion) {
  22454. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  22455. }
  22456. else if (mesh.rotation) {
  22457. serializationObject.rotation = mesh.rotation.asArray();
  22458. }
  22459. serializationObject.scaling = mesh.scaling.asArray();
  22460. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  22461. serializationObject.isEnabled = mesh.isEnabled();
  22462. serializationObject.isVisible = mesh.isVisible;
  22463. serializationObject.infiniteDistance = mesh.infiniteDistance;
  22464. serializationObject.pickable = mesh.isPickable;
  22465. serializationObject.receiveShadows = mesh.receiveShadows;
  22466. serializationObject.billboardMode = mesh.billboardMode;
  22467. serializationObject.visibility = mesh.visibility;
  22468. serializationObject.checkCollisions = mesh.checkCollisions;
  22469. // Parent
  22470. if (mesh.parent) {
  22471. serializationObject.parentId = mesh.parent.id;
  22472. }
  22473. // Geometry
  22474. var geometry = mesh._geometry;
  22475. if (geometry) {
  22476. var geometryId = geometry.id;
  22477. serializationObject.geometryId = geometryId;
  22478. if (!mesh.getScene().getGeometryByID(geometryId)) {
  22479. // 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
  22480. serializeGeometry(geometry, serializationScene.geometries);
  22481. }
  22482. // SubMeshes
  22483. serializationObject.subMeshes = [];
  22484. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22485. var subMesh = mesh.subMeshes[subIndex];
  22486. serializationObject.subMeshes.push({
  22487. materialIndex: subMesh.materialIndex,
  22488. verticesStart: subMesh.verticesStart,
  22489. verticesCount: subMesh.verticesCount,
  22490. indexStart: subMesh.indexStart,
  22491. indexCount: subMesh.indexCount
  22492. });
  22493. }
  22494. }
  22495. // Material
  22496. if (mesh.material) {
  22497. serializationObject.materialId = mesh.material.id;
  22498. }
  22499. else {
  22500. mesh.material = null;
  22501. }
  22502. // Skeleton
  22503. if (mesh.skeleton) {
  22504. serializationObject.skeletonId = mesh.skeleton.id;
  22505. }
  22506. // Physics
  22507. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  22508. serializationObject.physicsMass = mesh.getPhysicsMass();
  22509. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  22510. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  22511. switch (mesh.getPhysicsImpostor()) {
  22512. case BABYLON.PhysicsEngine.BoxImpostor:
  22513. serializationObject.physicsImpostor = 1;
  22514. break;
  22515. case BABYLON.PhysicsEngine.SphereImpostor:
  22516. serializationObject.physicsImpostor = 2;
  22517. break;
  22518. }
  22519. }
  22520. // Instances
  22521. serializationObject.instances = [];
  22522. for (var index = 0; index < mesh.instances.length; index++) {
  22523. var instance = mesh.instances[index];
  22524. var serializationInstance = {
  22525. name: instance.name,
  22526. position: instance.position,
  22527. rotation: instance.rotation,
  22528. rotationQuaternion: instance.rotationQuaternion,
  22529. scaling: instance.scaling
  22530. };
  22531. serializationObject.instances.push(serializationInstance);
  22532. // Animations
  22533. appendAnimations(instance, serializationInstance);
  22534. }
  22535. // Animations
  22536. appendAnimations(mesh, serializationObject);
  22537. // Layer mask
  22538. serializationObject.layerMask = mesh.layerMask;
  22539. return serializationObject;
  22540. };
  22541. var SceneSerializer = (function () {
  22542. function SceneSerializer() {
  22543. }
  22544. SceneSerializer.Serialize = function (scene) {
  22545. var serializationObject = {};
  22546. // Scene
  22547. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  22548. serializationObject.autoClear = scene.autoClear;
  22549. serializationObject.clearColor = scene.clearColor.asArray();
  22550. serializationObject.ambientColor = scene.ambientColor.asArray();
  22551. serializationObject.gravity = scene.gravity.asArray();
  22552. // Fog
  22553. if (scene.fogMode && scene.fogMode !== 0) {
  22554. serializationObject.fogMode = scene.fogMode;
  22555. serializationObject.fogColor = scene.fogColor.asArray();
  22556. serializationObject.fogStart = scene.fogStart;
  22557. serializationObject.fogEnd = scene.fogEnd;
  22558. serializationObject.fogDensity = scene.fogDensity;
  22559. }
  22560. // Lights
  22561. serializationObject.lights = [];
  22562. for (var index = 0; index < scene.lights.length; index++) {
  22563. var light = scene.lights[index];
  22564. serializationObject.lights.push(serializeLight(light));
  22565. }
  22566. // Cameras
  22567. serializationObject.cameras = [];
  22568. for (index = 0; index < scene.cameras.length; index++) {
  22569. var camera = scene.cameras[index];
  22570. serializationObject.cameras.push(serializeCamera(camera));
  22571. }
  22572. if (scene.activeCamera) {
  22573. serializationObject.activeCameraID = scene.activeCamera.id;
  22574. }
  22575. // Materials
  22576. serializationObject.materials = [];
  22577. serializationObject.multiMaterials = [];
  22578. for (index = 0; index < scene.materials.length; index++) {
  22579. var material = scene.materials[index];
  22580. if (material instanceof BABYLON.StandardMaterial) {
  22581. serializationObject.materials.push(serializeMaterial(material));
  22582. }
  22583. else if (material instanceof BABYLON.MultiMaterial) {
  22584. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  22585. }
  22586. }
  22587. // Skeletons
  22588. serializationObject.skeletons = [];
  22589. for (index = 0; index < scene.skeletons.length; index++) {
  22590. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  22591. }
  22592. // Geometries
  22593. serializationObject.geometries = {};
  22594. serializationObject.geometries.boxes = [];
  22595. serializationObject.geometries.spheres = [];
  22596. serializationObject.geometries.cylinders = [];
  22597. serializationObject.geometries.toruses = [];
  22598. serializationObject.geometries.grounds = [];
  22599. serializationObject.geometries.planes = [];
  22600. serializationObject.geometries.torusKnots = [];
  22601. serializationObject.geometries.vertexData = [];
  22602. serializedGeometries = [];
  22603. var geometries = scene.getGeometries();
  22604. for (index = 0; index < geometries.length; index++) {
  22605. var geometry = geometries[index];
  22606. if (geometry.isReady()) {
  22607. serializeGeometry(geometry, serializationObject.geometries);
  22608. }
  22609. }
  22610. // Meshes
  22611. serializationObject.meshes = [];
  22612. for (index = 0; index < scene.meshes.length; index++) {
  22613. var abstractMesh = scene.meshes[index];
  22614. if (abstractMesh instanceof BABYLON.Mesh) {
  22615. var mesh = abstractMesh;
  22616. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  22617. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  22618. }
  22619. }
  22620. }
  22621. // Particles Systems
  22622. serializationObject.particleSystems = [];
  22623. for (index = 0; index < scene.particleSystems.length; index++) {
  22624. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  22625. }
  22626. // Lens flares
  22627. serializationObject.lensFlareSystems = [];
  22628. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  22629. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  22630. }
  22631. // Shadows
  22632. serializationObject.shadowGenerators = [];
  22633. for (index = 0; index < scene.lights.length; index++) {
  22634. light = scene.lights[index];
  22635. if (light.getShadowGenerator()) {
  22636. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  22637. }
  22638. }
  22639. return serializationObject;
  22640. };
  22641. return SceneSerializer;
  22642. })();
  22643. BABYLON.SceneSerializer = SceneSerializer;
  22644. })(BABYLON || (BABYLON = {}));
  22645. //# sourceMappingURL=babylon.sceneSerializer.js.map
  22646. var BABYLON;
  22647. (function (BABYLON) {
  22648. // Unique ID when we import meshes from Babylon to CSG
  22649. var currentCSGMeshId = 0;
  22650. // # class Vertex
  22651. // Represents a vertex of a polygon. Use your own vertex class instead of this
  22652. // one to provide additional features like texture coordinates and vertex
  22653. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  22654. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  22655. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  22656. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  22657. // is not used anywhere else.
  22658. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  22659. var Vertex = (function () {
  22660. function Vertex(pos, normal, uv) {
  22661. this.pos = pos;
  22662. this.normal = normal;
  22663. this.uv = uv;
  22664. }
  22665. Vertex.prototype.clone = function () {
  22666. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  22667. };
  22668. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  22669. // orientation of a polygon is flipped.
  22670. Vertex.prototype.flip = function () {
  22671. this.normal = this.normal.scale(-1);
  22672. };
  22673. // Create a new vertex between this vertex and `other` by linearly
  22674. // interpolating all properties using a parameter of `t`. Subclasses should
  22675. // override this to interpolate additional properties.
  22676. Vertex.prototype.interpolate = function (other, t) {
  22677. 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));
  22678. };
  22679. return Vertex;
  22680. })();
  22681. // # class Plane
  22682. // Represents a plane in 3D space.
  22683. var Plane = (function () {
  22684. function Plane(normal, w) {
  22685. this.normal = normal;
  22686. this.w = w;
  22687. }
  22688. Plane.FromPoints = function (a, b, c) {
  22689. var v0 = c.subtract(a);
  22690. var v1 = b.subtract(a);
  22691. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  22692. return null;
  22693. }
  22694. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  22695. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  22696. };
  22697. Plane.prototype.clone = function () {
  22698. return new Plane(this.normal.clone(), this.w);
  22699. };
  22700. Plane.prototype.flip = function () {
  22701. this.normal.scaleInPlace(-1);
  22702. this.w = -this.w;
  22703. };
  22704. // Split `polygon` by this plane if needed, then put the polygon or polygon
  22705. // fragments in the appropriate lists. Coplanar polygons go into either
  22706. // `coplanarFront` or `coplanarBack` depending on their orientation with
  22707. // respect to this plane. Polygons in front or in back of this plane go into
  22708. // either `front` or `back`.
  22709. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  22710. var COPLANAR = 0;
  22711. var FRONT = 1;
  22712. var BACK = 2;
  22713. var SPANNING = 3;
  22714. // Classify each point as well as the entire polygon into one of the above
  22715. // four classes.
  22716. var polygonType = 0;
  22717. var types = [];
  22718. for (var i = 0; i < polygon.vertices.length; i++) {
  22719. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  22720. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  22721. polygonType |= type;
  22722. types.push(type);
  22723. }
  22724. // Put the polygon in the correct list, splitting it when necessary.
  22725. switch (polygonType) {
  22726. case COPLANAR:
  22727. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  22728. break;
  22729. case FRONT:
  22730. front.push(polygon);
  22731. break;
  22732. case BACK:
  22733. back.push(polygon);
  22734. break;
  22735. case SPANNING:
  22736. var f = [], b = [];
  22737. for (i = 0; i < polygon.vertices.length; i++) {
  22738. var j = (i + 1) % polygon.vertices.length;
  22739. var ti = types[i], tj = types[j];
  22740. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  22741. if (ti != BACK)
  22742. f.push(vi);
  22743. if (ti != FRONT)
  22744. b.push(ti != BACK ? vi.clone() : vi);
  22745. if ((ti | tj) == SPANNING) {
  22746. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  22747. var v = vi.interpolate(vj, t);
  22748. f.push(v);
  22749. b.push(v.clone());
  22750. }
  22751. }
  22752. if (f.length >= 3) {
  22753. var poly = new Polygon(f, polygon.shared);
  22754. if (poly.plane)
  22755. front.push(poly);
  22756. }
  22757. if (b.length >= 3) {
  22758. poly = new Polygon(b, polygon.shared);
  22759. if (poly.plane)
  22760. back.push(poly);
  22761. }
  22762. break;
  22763. }
  22764. };
  22765. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  22766. // point is on the plane.
  22767. Plane.EPSILON = 1e-5;
  22768. return Plane;
  22769. })();
  22770. // # class Polygon
  22771. // Represents a convex polygon. The vertices used to initialize a polygon must
  22772. // be coplanar and form a convex loop.
  22773. //
  22774. // Each convex polygon has a `shared` property, which is shared between all
  22775. // polygons that are clones of each other or were split from the same polygon.
  22776. // This can be used to define per-polygon properties (such as surface color).
  22777. var Polygon = (function () {
  22778. function Polygon(vertices, shared) {
  22779. this.vertices = vertices;
  22780. this.shared = shared;
  22781. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  22782. }
  22783. Polygon.prototype.clone = function () {
  22784. var vertices = this.vertices.map(function (v) { return v.clone(); });
  22785. return new Polygon(vertices, this.shared);
  22786. };
  22787. Polygon.prototype.flip = function () {
  22788. this.vertices.reverse().map(function (v) { v.flip(); });
  22789. this.plane.flip();
  22790. };
  22791. return Polygon;
  22792. })();
  22793. // # class Node
  22794. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  22795. // by picking a polygon to split along. That polygon (and all other coplanar
  22796. // polygons) are added directly to that node and the other polygons are added to
  22797. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  22798. // no distinction between internal and leaf nodes.
  22799. var Node = (function () {
  22800. function Node(polygons) {
  22801. this.plane = null;
  22802. this.front = null;
  22803. this.back = null;
  22804. this.polygons = [];
  22805. if (polygons) {
  22806. this.build(polygons);
  22807. }
  22808. }
  22809. Node.prototype.clone = function () {
  22810. var node = new Node();
  22811. node.plane = this.plane && this.plane.clone();
  22812. node.front = this.front && this.front.clone();
  22813. node.back = this.back && this.back.clone();
  22814. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  22815. return node;
  22816. };
  22817. // Convert solid space to empty space and empty space to solid space.
  22818. Node.prototype.invert = function () {
  22819. for (var i = 0; i < this.polygons.length; i++) {
  22820. this.polygons[i].flip();
  22821. }
  22822. if (this.plane) {
  22823. this.plane.flip();
  22824. }
  22825. if (this.front) {
  22826. this.front.invert();
  22827. }
  22828. if (this.back) {
  22829. this.back.invert();
  22830. }
  22831. var temp = this.front;
  22832. this.front = this.back;
  22833. this.back = temp;
  22834. };
  22835. // Recursively remove all polygons in `polygons` that are inside this BSP
  22836. // tree.
  22837. Node.prototype.clipPolygons = function (polygons) {
  22838. if (!this.plane)
  22839. return polygons.slice();
  22840. var front = [], back = [];
  22841. for (var i = 0; i < polygons.length; i++) {
  22842. this.plane.splitPolygon(polygons[i], front, back, front, back);
  22843. }
  22844. if (this.front) {
  22845. front = this.front.clipPolygons(front);
  22846. }
  22847. if (this.back) {
  22848. back = this.back.clipPolygons(back);
  22849. }
  22850. else {
  22851. back = [];
  22852. }
  22853. return front.concat(back);
  22854. };
  22855. // Remove all polygons in this BSP tree that are inside the other BSP tree
  22856. // `bsp`.
  22857. Node.prototype.clipTo = function (bsp) {
  22858. this.polygons = bsp.clipPolygons(this.polygons);
  22859. if (this.front)
  22860. this.front.clipTo(bsp);
  22861. if (this.back)
  22862. this.back.clipTo(bsp);
  22863. };
  22864. // Return a list of all polygons in this BSP tree.
  22865. Node.prototype.allPolygons = function () {
  22866. var polygons = this.polygons.slice();
  22867. if (this.front)
  22868. polygons = polygons.concat(this.front.allPolygons());
  22869. if (this.back)
  22870. polygons = polygons.concat(this.back.allPolygons());
  22871. return polygons;
  22872. };
  22873. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  22874. // new polygons are filtered down to the bottom of the tree and become new
  22875. // nodes there. Each set of polygons is partitioned using the first polygon
  22876. // (no heuristic is used to pick a good split).
  22877. Node.prototype.build = function (polygons) {
  22878. if (!polygons.length)
  22879. return;
  22880. if (!this.plane)
  22881. this.plane = polygons[0].plane.clone();
  22882. var front = [], back = [];
  22883. for (var i = 0; i < polygons.length; i++) {
  22884. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  22885. }
  22886. if (front.length) {
  22887. if (!this.front)
  22888. this.front = new Node();
  22889. this.front.build(front);
  22890. }
  22891. if (back.length) {
  22892. if (!this.back)
  22893. this.back = new Node();
  22894. this.back.build(back);
  22895. }
  22896. };
  22897. return Node;
  22898. })();
  22899. var CSG = (function () {
  22900. function CSG() {
  22901. this.polygons = new Array();
  22902. }
  22903. // Convert BABYLON.Mesh to BABYLON.CSG
  22904. CSG.FromMesh = function (mesh) {
  22905. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  22906. if (mesh instanceof BABYLON.Mesh) {
  22907. mesh.computeWorldMatrix(true);
  22908. var matrix = mesh.getWorldMatrix();
  22909. var meshPosition = mesh.position.clone();
  22910. var meshRotation = mesh.rotation.clone();
  22911. var meshScaling = mesh.scaling.clone();
  22912. }
  22913. else {
  22914. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  22915. }
  22916. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22917. var subMeshes = mesh.subMeshes;
  22918. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  22919. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  22920. vertices = [];
  22921. for (var j = 0; j < 3; j++) {
  22922. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  22923. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  22924. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  22925. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  22926. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  22927. vertex = new Vertex(position, normal, uv);
  22928. vertices.push(vertex);
  22929. }
  22930. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  22931. // To handle the case of degenerated triangle
  22932. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  22933. if (polygon.plane)
  22934. polygons.push(polygon);
  22935. }
  22936. }
  22937. var csg = CSG.FromPolygons(polygons);
  22938. csg.matrix = matrix;
  22939. csg.position = meshPosition;
  22940. csg.rotation = meshRotation;
  22941. csg.scaling = meshScaling;
  22942. currentCSGMeshId++;
  22943. return csg;
  22944. };
  22945. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  22946. CSG.FromPolygons = function (polygons) {
  22947. var csg = new BABYLON.CSG();
  22948. csg.polygons = polygons;
  22949. return csg;
  22950. };
  22951. CSG.prototype.clone = function () {
  22952. var csg = new BABYLON.CSG();
  22953. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  22954. csg.copyTransformAttributes(this);
  22955. return csg;
  22956. };
  22957. CSG.prototype.toPolygons = function () {
  22958. return this.polygons;
  22959. };
  22960. CSG.prototype.union = function (csg) {
  22961. var a = new Node(this.clone().polygons);
  22962. var b = new Node(csg.clone().polygons);
  22963. a.clipTo(b);
  22964. b.clipTo(a);
  22965. b.invert();
  22966. b.clipTo(a);
  22967. b.invert();
  22968. a.build(b.allPolygons());
  22969. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22970. };
  22971. CSG.prototype.unionInPlace = function (csg) {
  22972. var a = new Node(this.polygons);
  22973. var b = new Node(csg.polygons);
  22974. a.clipTo(b);
  22975. b.clipTo(a);
  22976. b.invert();
  22977. b.clipTo(a);
  22978. b.invert();
  22979. a.build(b.allPolygons());
  22980. this.polygons = a.allPolygons();
  22981. };
  22982. CSG.prototype.subtract = function (csg) {
  22983. var a = new Node(this.clone().polygons);
  22984. var b = new Node(csg.clone().polygons);
  22985. a.invert();
  22986. a.clipTo(b);
  22987. b.clipTo(a);
  22988. b.invert();
  22989. b.clipTo(a);
  22990. b.invert();
  22991. a.build(b.allPolygons());
  22992. a.invert();
  22993. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22994. };
  22995. CSG.prototype.subtractInPlace = function (csg) {
  22996. var a = new Node(this.polygons);
  22997. var b = new Node(csg.polygons);
  22998. a.invert();
  22999. a.clipTo(b);
  23000. b.clipTo(a);
  23001. b.invert();
  23002. b.clipTo(a);
  23003. b.invert();
  23004. a.build(b.allPolygons());
  23005. a.invert();
  23006. this.polygons = a.allPolygons();
  23007. };
  23008. CSG.prototype.intersect = function (csg) {
  23009. var a = new Node(this.clone().polygons);
  23010. var b = new Node(csg.clone().polygons);
  23011. a.invert();
  23012. b.clipTo(a);
  23013. b.invert();
  23014. a.clipTo(b);
  23015. b.clipTo(a);
  23016. a.build(b.allPolygons());
  23017. a.invert();
  23018. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  23019. };
  23020. CSG.prototype.intersectInPlace = function (csg) {
  23021. var a = new Node(this.polygons);
  23022. var b = new Node(csg.polygons);
  23023. a.invert();
  23024. b.clipTo(a);
  23025. b.invert();
  23026. a.clipTo(b);
  23027. b.clipTo(a);
  23028. a.build(b.allPolygons());
  23029. a.invert();
  23030. this.polygons = a.allPolygons();
  23031. };
  23032. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  23033. // not modified.
  23034. CSG.prototype.inverse = function () {
  23035. var csg = this.clone();
  23036. csg.inverseInPlace();
  23037. return csg;
  23038. };
  23039. CSG.prototype.inverseInPlace = function () {
  23040. this.polygons.map(function (p) { p.flip(); });
  23041. };
  23042. // This is used to keep meshes transformations so they can be restored
  23043. // when we build back a Babylon Mesh
  23044. // NB : All CSG operations are performed in world coordinates
  23045. CSG.prototype.copyTransformAttributes = function (csg) {
  23046. this.matrix = csg.matrix;
  23047. this.position = csg.position;
  23048. this.rotation = csg.rotation;
  23049. this.scaling = csg.scaling;
  23050. return this;
  23051. };
  23052. // Build Raw mesh from CSG
  23053. // Coordinates here are in world space
  23054. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  23055. var matrix = this.matrix.clone();
  23056. matrix.invert();
  23057. 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;
  23058. if (keepSubMeshes) {
  23059. // Sort Polygons, since subMeshes are indices range
  23060. polygons.sort(function (a, b) {
  23061. if (a.shared.meshId === b.shared.meshId) {
  23062. return a.shared.subMeshId - b.shared.subMeshId;
  23063. }
  23064. else {
  23065. return a.shared.meshId - b.shared.meshId;
  23066. }
  23067. });
  23068. }
  23069. for (var i = 0, il = polygons.length; i < il; i++) {
  23070. polygon = polygons[i];
  23071. // Building SubMeshes
  23072. if (!subMesh_dict[polygon.shared.meshId]) {
  23073. subMesh_dict[polygon.shared.meshId] = {};
  23074. }
  23075. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  23076. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  23077. indexStart: +Infinity,
  23078. indexEnd: -Infinity,
  23079. materialIndex: polygon.shared.materialIndex
  23080. };
  23081. }
  23082. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  23083. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  23084. polygonIndices[0] = 0;
  23085. polygonIndices[1] = j - 1;
  23086. polygonIndices[2] = j;
  23087. for (var k = 0; k < 3; k++) {
  23088. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  23089. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  23090. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  23091. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  23092. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  23093. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  23094. // Check if 2 points can be merged
  23095. if (!(typeof vertex_idx !== 'undefined' &&
  23096. normals[vertex_idx * 3] === localNormal.x &&
  23097. normals[vertex_idx * 3 + 1] === localNormal.y &&
  23098. normals[vertex_idx * 3 + 2] === localNormal.z &&
  23099. uvs[vertex_idx * 2] === uv.x &&
  23100. uvs[vertex_idx * 2 + 1] === uv.y)) {
  23101. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  23102. uvs.push(uv.x, uv.y);
  23103. normals.push(normal.x, normal.y, normal.z);
  23104. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  23105. }
  23106. indices.push(vertex_idx);
  23107. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  23108. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  23109. currentIndex++;
  23110. }
  23111. }
  23112. }
  23113. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  23114. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23115. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  23116. mesh.setIndices(indices);
  23117. if (keepSubMeshes) {
  23118. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  23119. var materialIndexOffset = 0, materialMaxIndex;
  23120. mesh.subMeshes.length = 0;
  23121. for (var m in subMesh_dict) {
  23122. materialMaxIndex = -1;
  23123. for (var sm in subMesh_dict[m]) {
  23124. subMesh_obj = subMesh_dict[m][sm];
  23125. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  23126. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  23127. }
  23128. materialIndexOffset += ++materialMaxIndex;
  23129. }
  23130. }
  23131. return mesh;
  23132. };
  23133. // Build Mesh from CSG taking material and transforms into account
  23134. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  23135. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  23136. mesh.material = material;
  23137. mesh.position.copyFrom(this.position);
  23138. mesh.rotation.copyFrom(this.rotation);
  23139. mesh.scaling.copyFrom(this.scaling);
  23140. mesh.computeWorldMatrix(true);
  23141. return mesh;
  23142. };
  23143. return CSG;
  23144. })();
  23145. BABYLON.CSG = CSG;
  23146. })(BABYLON || (BABYLON = {}));
  23147. //# sourceMappingURL=babylon.csg.js.map
  23148. var __extends = this.__extends || function (d, b) {
  23149. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23150. function __() { this.constructor = d; }
  23151. __.prototype = b.prototype;
  23152. d.prototype = new __();
  23153. };
  23154. var BABYLON;
  23155. (function (BABYLON) {
  23156. var VRDistortionCorrectionPostProcess = (function (_super) {
  23157. __extends(VRDistortionCorrectionPostProcess, _super);
  23158. //ANY
  23159. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  23160. var _this = this;
  23161. _super.call(this, name, "vrDistortionCorrection", [
  23162. 'LensCenter',
  23163. 'Scale',
  23164. 'ScaleIn',
  23165. 'HmdWarpParam'
  23166. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  23167. this._isRightEye = isRightEye;
  23168. this._distortionFactors = cameraSettings.DistortionK;
  23169. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  23170. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  23171. this.onSizeChanged = function () {
  23172. _this.aspectRatio = _this.width * .5 / _this.height;
  23173. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  23174. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  23175. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  23176. };
  23177. this.onApply = function (effect) {
  23178. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  23179. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  23180. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  23181. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  23182. };
  23183. }
  23184. return VRDistortionCorrectionPostProcess;
  23185. })(BABYLON.PostProcess);
  23186. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  23187. })(BABYLON || (BABYLON = {}));
  23188. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  23189. // Mainly based on these 2 articles :
  23190. // 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
  23191. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  23192. var BABYLON;
  23193. (function (BABYLON) {
  23194. (function (JoystickAxis) {
  23195. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  23196. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  23197. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  23198. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  23199. var JoystickAxis = BABYLON.JoystickAxis;
  23200. var VirtualJoystick = (function () {
  23201. function VirtualJoystick(leftJoystick) {
  23202. var _this = this;
  23203. if (leftJoystick) {
  23204. this._leftJoystick = true;
  23205. }
  23206. else {
  23207. this._leftJoystick = false;
  23208. }
  23209. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  23210. VirtualJoystick._globalJoystickIndex++;
  23211. // By default left & right arrow keys are moving the X
  23212. // and up & down keys are moving the Y
  23213. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  23214. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  23215. this.reverseLeftRight = false;
  23216. this.reverseUpDown = false;
  23217. // collections of pointers
  23218. this._touches = new BABYLON.SmartCollection();
  23219. this.deltaPosition = BABYLON.Vector3.Zero();
  23220. this._joystickSensibility = 25;
  23221. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23222. this._rotationSpeed = 25;
  23223. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  23224. this._rotateOnAxisRelativeToMesh = false;
  23225. // injecting a canvas element on top of the canvas 3D game
  23226. if (!VirtualJoystick.vjCanvas) {
  23227. window.addEventListener("resize", function () {
  23228. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23229. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23230. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  23231. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  23232. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  23233. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  23234. }, false);
  23235. VirtualJoystick.vjCanvas = document.createElement("canvas");
  23236. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23237. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23238. VirtualJoystick.vjCanvas.width = window.innerWidth;
  23239. VirtualJoystick.vjCanvas.height = window.innerHeight;
  23240. VirtualJoystick.vjCanvas.style.width = "100%";
  23241. VirtualJoystick.vjCanvas.style.height = "100%";
  23242. VirtualJoystick.vjCanvas.style.position = "absolute";
  23243. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  23244. VirtualJoystick.vjCanvas.style.top = "0px";
  23245. VirtualJoystick.vjCanvas.style.left = "0px";
  23246. VirtualJoystick.vjCanvas.style.zIndex = "5";
  23247. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  23248. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  23249. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  23250. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23251. document.body.appendChild(VirtualJoystick.vjCanvas);
  23252. }
  23253. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  23254. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  23255. this.pressed = false;
  23256. // default joystick color
  23257. this._joystickColor = "cyan";
  23258. this._joystickPointerID = -1;
  23259. // current joystick position
  23260. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  23261. // origin joystick position
  23262. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  23263. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  23264. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  23265. _this._onPointerDown(evt);
  23266. }, false);
  23267. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  23268. _this._onPointerMove(evt);
  23269. }, false);
  23270. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  23271. _this._onPointerUp(evt);
  23272. }, false);
  23273. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  23274. _this._onPointerUp(evt);
  23275. }, false);
  23276. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  23277. evt.preventDefault(); // Disables system menu
  23278. }, false);
  23279. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  23280. }
  23281. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  23282. this._joystickSensibility = newJoystickSensibility;
  23283. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23284. };
  23285. VirtualJoystick.prototype._onPointerDown = function (e) {
  23286. var positionOnScreenCondition;
  23287. e.preventDefault();
  23288. if (this._leftJoystick === true) {
  23289. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  23290. }
  23291. else {
  23292. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  23293. }
  23294. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  23295. // First contact will be dedicated to the virtual joystick
  23296. this._joystickPointerID = e.pointerId;
  23297. this._joystickPointerStartPos.x = e.clientX;
  23298. this._joystickPointerStartPos.y = e.clientY;
  23299. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  23300. this._deltaJoystickVector.x = 0;
  23301. this._deltaJoystickVector.y = 0;
  23302. this.pressed = true;
  23303. this._touches.add(e.pointerId.toString(), e);
  23304. }
  23305. else {
  23306. // You can only trigger the action buttons with a joystick declared
  23307. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  23308. this._action();
  23309. this._touches.add(e.pointerId.toString(), e);
  23310. }
  23311. }
  23312. };
  23313. VirtualJoystick.prototype._onPointerMove = function (e) {
  23314. // If the current pointer is the one associated to the joystick (first touch contact)
  23315. if (this._joystickPointerID == e.pointerId) {
  23316. this._joystickPointerPos.x = e.clientX;
  23317. this._joystickPointerPos.y = e.clientY;
  23318. this._deltaJoystickVector = this._joystickPointerPos.clone();
  23319. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  23320. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  23321. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  23322. switch (this._axisTargetedByLeftAndRight) {
  23323. case JoystickAxis.X:
  23324. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  23325. break;
  23326. case JoystickAxis.Y:
  23327. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  23328. break;
  23329. case JoystickAxis.Z:
  23330. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  23331. break;
  23332. }
  23333. var directionUpDown = this.reverseUpDown ? 1 : -1;
  23334. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  23335. switch (this._axisTargetedByUpAndDown) {
  23336. case JoystickAxis.X:
  23337. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  23338. break;
  23339. case JoystickAxis.Y:
  23340. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  23341. break;
  23342. case JoystickAxis.Z:
  23343. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  23344. break;
  23345. }
  23346. }
  23347. else {
  23348. if (this._touches.item(e.pointerId.toString())) {
  23349. this._touches.item(e.pointerId.toString()).x = e.clientX;
  23350. this._touches.item(e.pointerId.toString()).y = e.clientY;
  23351. }
  23352. }
  23353. };
  23354. VirtualJoystick.prototype._onPointerUp = function (e) {
  23355. this._clearCanvas();
  23356. if (this._joystickPointerID == e.pointerId) {
  23357. this._joystickPointerID = -1;
  23358. this.pressed = false;
  23359. }
  23360. this._deltaJoystickVector.x = 0;
  23361. this._deltaJoystickVector.y = 0;
  23362. this._touches.remove(e.pointerId.toString());
  23363. };
  23364. /**
  23365. * Change the color of the virtual joystick
  23366. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  23367. */
  23368. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  23369. this._joystickColor = newColor;
  23370. };
  23371. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  23372. this._action = action;
  23373. };
  23374. // Define which axis you'd like to control for left & right
  23375. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  23376. switch (axis) {
  23377. case JoystickAxis.X:
  23378. case JoystickAxis.Y:
  23379. case JoystickAxis.Z:
  23380. this._axisTargetedByLeftAndRight = axis;
  23381. break;
  23382. default:
  23383. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  23384. break;
  23385. }
  23386. };
  23387. // Define which axis you'd like to control for up & down
  23388. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  23389. switch (axis) {
  23390. case JoystickAxis.X:
  23391. case JoystickAxis.Y:
  23392. case JoystickAxis.Z:
  23393. this._axisTargetedByUpAndDown = axis;
  23394. break;
  23395. default:
  23396. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  23397. break;
  23398. }
  23399. };
  23400. VirtualJoystick.prototype._clearCanvas = function () {
  23401. if (this._leftJoystick) {
  23402. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  23403. }
  23404. else {
  23405. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  23406. }
  23407. };
  23408. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  23409. var _this = this;
  23410. if (this.pressed) {
  23411. this._clearCanvas();
  23412. this._touches.forEach(function (touch) {
  23413. if (touch.pointerId === _this._joystickPointerID) {
  23414. VirtualJoystick.vjCanvasContext.beginPath();
  23415. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23416. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23417. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  23418. VirtualJoystick.vjCanvasContext.stroke();
  23419. VirtualJoystick.vjCanvasContext.beginPath();
  23420. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23421. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23422. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  23423. VirtualJoystick.vjCanvasContext.stroke();
  23424. VirtualJoystick.vjCanvasContext.beginPath();
  23425. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23426. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  23427. VirtualJoystick.vjCanvasContext.stroke();
  23428. }
  23429. else {
  23430. VirtualJoystick.vjCanvasContext.beginPath();
  23431. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  23432. VirtualJoystick.vjCanvasContext.beginPath();
  23433. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  23434. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23435. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  23436. VirtualJoystick.vjCanvasContext.stroke();
  23437. }
  23438. ;
  23439. });
  23440. }
  23441. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  23442. };
  23443. VirtualJoystick.prototype.releaseCanvas = function () {
  23444. if (VirtualJoystick.vjCanvas) {
  23445. document.body.removeChild(VirtualJoystick.vjCanvas);
  23446. VirtualJoystick.vjCanvas = null;
  23447. }
  23448. };
  23449. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  23450. VirtualJoystick._globalJoystickIndex = 0;
  23451. return VirtualJoystick;
  23452. })();
  23453. BABYLON.VirtualJoystick = VirtualJoystick;
  23454. })(BABYLON || (BABYLON = {}));
  23455. //# sourceMappingURL=babylon.virtualJoystick.js.map
  23456. var __extends = this.__extends || function (d, b) {
  23457. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23458. function __() { this.constructor = d; }
  23459. __.prototype = b.prototype;
  23460. d.prototype = new __();
  23461. };
  23462. var BABYLON;
  23463. (function (BABYLON) {
  23464. var DefaultVRConstants = {
  23465. HResolution: 1280,
  23466. VResolution: 800,
  23467. HScreenSize: 0.149759993,
  23468. VScreenSize: 0.0935999975,
  23469. VScreenCenter: 0.0467999987,
  23470. EyeToScreenDistance: 0.0410000011,
  23471. LensSeparationDistance: 0.0635000020,
  23472. InterpupillaryDistance: 0.0640000030,
  23473. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  23474. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  23475. PostProcessScaleFactor: 1.714605507808412,
  23476. LensCenterOffset: 0.151976421
  23477. };
  23478. var _VRInnerCamera = (function (_super) {
  23479. __extends(_VRInnerCamera, _super);
  23480. function _VRInnerCamera(name, position, scene, isLeftEye, compensateDistorsion) {
  23481. _super.call(this, name, position, scene);
  23482. this._workMatrix = new BABYLON.Matrix();
  23483. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  23484. // Constants
  23485. this._aspectRatioAspectRatio = DefaultVRConstants.HResolution / (2 * DefaultVRConstants.VResolution);
  23486. this._aspectRatioFov = (2 * Math.atan((DefaultVRConstants.PostProcessScaleFactor * DefaultVRConstants.VScreenSize) / (2 * DefaultVRConstants.EyeToScreenDistance)));
  23487. var hMeters = (DefaultVRConstants.HScreenSize / 4) - (DefaultVRConstants.LensSeparationDistance / 2);
  23488. var h = (4 * hMeters) / DefaultVRConstants.HScreenSize;
  23489. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  23490. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  23491. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * DefaultVRConstants.InterpupillaryDistance : -.5 * DefaultVRConstants.InterpupillaryDistance, 0, 0);
  23492. if (compensateDistorsion) {
  23493. // Postprocess
  23494. var postProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR Distortion", this, !isLeftEye, DefaultVRConstants);
  23495. }
  23496. }
  23497. _VRInnerCamera.prototype.getProjectionMatrix = function () {
  23498. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  23499. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  23500. return this._projectionMatrix;
  23501. };
  23502. _VRInnerCamera.prototype._getViewMatrix = function () {
  23503. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  23504. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  23505. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  23506. // Computing target and final matrix
  23507. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  23508. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  23509. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  23510. return this._viewMatrix;
  23511. };
  23512. return _VRInnerCamera;
  23513. })(BABYLON.FreeCamera);
  23514. var VRCamera = (function (_super) {
  23515. __extends(VRCamera, _super);
  23516. function VRCamera(name, position, scene, compensateDistorsion) {
  23517. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  23518. _super.call(this, name, position, scene);
  23519. this._leftCamera = new _VRInnerCamera(name + "_left", position.clone(), scene, true, compensateDistorsion);
  23520. this._rightCamera = new _VRInnerCamera(name + "_right", position.clone(), scene, false, compensateDistorsion);
  23521. this.subCameras.push(this._leftCamera);
  23522. this.subCameras.push(this._rightCamera);
  23523. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  23524. }
  23525. VRCamera.prototype._update = function () {
  23526. this._leftCamera.position.copyFrom(this.position);
  23527. this._rightCamera.position.copyFrom(this.position);
  23528. this._updateCamera(this._leftCamera);
  23529. this._updateCamera(this._rightCamera);
  23530. _super.prototype._update.call(this);
  23531. };
  23532. VRCamera.prototype._updateCamera = function (camera) {
  23533. camera.minZ = this.minZ;
  23534. camera.maxZ = this.maxZ;
  23535. camera.rotation.x = this.rotation.x;
  23536. camera.rotation.y = this.rotation.y;
  23537. camera.rotation.z = this.rotation.z;
  23538. };
  23539. // Orientation events
  23540. VRCamera.prototype._onOrientationEvent = function (evt) {
  23541. var yaw = evt.alpha / 180 * Math.PI;
  23542. var pitch = evt.beta / 180 * Math.PI;
  23543. var roll = evt.gamma / 180 * Math.PI;
  23544. if (!this._offsetOrientation) {
  23545. this._offsetOrientation = {
  23546. yaw: yaw,
  23547. pitch: pitch,
  23548. roll: roll
  23549. };
  23550. return;
  23551. }
  23552. else {
  23553. this.rotation.y += yaw - this._offsetOrientation.yaw;
  23554. this.rotation.x += pitch - this._offsetOrientation.pitch;
  23555. this.rotation.z += this._offsetOrientation.roll - roll;
  23556. this._offsetOrientation.yaw = yaw;
  23557. this._offsetOrientation.pitch = pitch;
  23558. this._offsetOrientation.roll = roll;
  23559. }
  23560. };
  23561. VRCamera.prototype.attachControl = function (element, noPreventDefault) {
  23562. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23563. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  23564. };
  23565. VRCamera.prototype.detachControl = function (element) {
  23566. _super.prototype.detachControl.call(this, element);
  23567. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  23568. };
  23569. return VRCamera;
  23570. })(BABYLON.FreeCamera);
  23571. BABYLON.VRCamera = VRCamera;
  23572. })(BABYLON || (BABYLON = {}));
  23573. //# sourceMappingURL=babylon.vrCamera.js.map
  23574. var __extends = this.__extends || function (d, b) {
  23575. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23576. function __() { this.constructor = d; }
  23577. __.prototype = b.prototype;
  23578. d.prototype = new __();
  23579. };
  23580. var BABYLON;
  23581. (function (BABYLON) {
  23582. // We're mainly based on the logic defined into the FreeCamera code
  23583. var VirtualJoysticksCamera = (function (_super) {
  23584. __extends(VirtualJoysticksCamera, _super);
  23585. function VirtualJoysticksCamera(name, position, scene) {
  23586. _super.call(this, name, position, scene);
  23587. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  23588. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  23589. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  23590. this._leftjoystick.setJoystickSensibility(0.15);
  23591. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  23592. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  23593. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  23594. this._rightjoystick.reverseUpDown = true;
  23595. this._rightjoystick.setJoystickSensibility(0.05);
  23596. this._rightjoystick.setJoystickColor("yellow");
  23597. }
  23598. VirtualJoysticksCamera.prototype._checkInputs = function () {
  23599. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23600. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  23601. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23602. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  23603. if (!this._leftjoystick.pressed) {
  23604. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  23605. }
  23606. if (!this._rightjoystick.pressed) {
  23607. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  23608. }
  23609. };
  23610. VirtualJoysticksCamera.prototype.dispose = function () {
  23611. this._leftjoystick.releaseCanvas();
  23612. _super.prototype.dispose.call(this);
  23613. };
  23614. return VirtualJoysticksCamera;
  23615. })(BABYLON.FreeCamera);
  23616. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  23617. })(BABYLON || (BABYLON = {}));
  23618. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  23619. var __extends = this.__extends || function (d, b) {
  23620. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23621. function __() { this.constructor = d; }
  23622. __.prototype = b.prototype;
  23623. d.prototype = new __();
  23624. };
  23625. var BABYLON;
  23626. (function (BABYLON) {
  23627. var ShaderMaterial = (function (_super) {
  23628. __extends(ShaderMaterial, _super);
  23629. function ShaderMaterial(name, scene, shaderPath, options) {
  23630. _super.call(this, name, scene);
  23631. this._textures = new Array();
  23632. this._floats = new Array();
  23633. this._floatsArrays = {};
  23634. this._colors3 = new Array();
  23635. this._colors4 = new Array();
  23636. this._vectors2 = new Array();
  23637. this._vectors3 = new Array();
  23638. this._matrices = new Array();
  23639. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  23640. this._shaderPath = shaderPath;
  23641. options.needAlphaBlending = options.needAlphaBlending || false;
  23642. options.needAlphaTesting = options.needAlphaTesting || false;
  23643. options.attributes = options.attributes || ["position", "normal", "uv"];
  23644. options.uniforms = options.uniforms || ["worldViewProjection"];
  23645. options.samplers = options.samplers || [];
  23646. this._options = options;
  23647. }
  23648. ShaderMaterial.prototype.needAlphaBlending = function () {
  23649. return this._options.needAlphaBlending;
  23650. };
  23651. ShaderMaterial.prototype.needAlphaTesting = function () {
  23652. return this._options.needAlphaTesting;
  23653. };
  23654. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  23655. if (this._options.uniforms.indexOf(uniformName) === -1) {
  23656. this._options.uniforms.push(uniformName);
  23657. }
  23658. };
  23659. ShaderMaterial.prototype.setTexture = function (name, texture) {
  23660. if (this._options.samplers.indexOf(name) === -1) {
  23661. this._options.samplers.push(name);
  23662. }
  23663. this._textures[name] = texture;
  23664. return this;
  23665. };
  23666. ShaderMaterial.prototype.setFloat = function (name, value) {
  23667. this._checkUniform(name);
  23668. this._floats[name] = value;
  23669. return this;
  23670. };
  23671. ShaderMaterial.prototype.setFloats = function (name, value) {
  23672. this._checkUniform(name);
  23673. this._floatsArrays[name] = value;
  23674. return this;
  23675. };
  23676. ShaderMaterial.prototype.setColor3 = function (name, value) {
  23677. this._checkUniform(name);
  23678. this._colors3[name] = value;
  23679. return this;
  23680. };
  23681. ShaderMaterial.prototype.setColor4 = function (name, value) {
  23682. this._checkUniform(name);
  23683. this._colors4[name] = value;
  23684. return this;
  23685. };
  23686. ShaderMaterial.prototype.setVector2 = function (name, value) {
  23687. this._checkUniform(name);
  23688. this._vectors2[name] = value;
  23689. return this;
  23690. };
  23691. ShaderMaterial.prototype.setVector3 = function (name, value) {
  23692. this._checkUniform(name);
  23693. this._vectors3[name] = value;
  23694. return this;
  23695. };
  23696. ShaderMaterial.prototype.setMatrix = function (name, value) {
  23697. this._checkUniform(name);
  23698. this._matrices[name] = value;
  23699. return this;
  23700. };
  23701. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  23702. var scene = this.getScene();
  23703. var engine = scene.getEngine();
  23704. if (!this.checkReadyOnEveryCall) {
  23705. if (this._renderId === scene.getRenderId()) {
  23706. return true;
  23707. }
  23708. }
  23709. // Instances
  23710. var defines = [];
  23711. var fallbacks = new BABYLON.EffectFallbacks();
  23712. if (useInstances) {
  23713. defines.push("#define INSTANCES");
  23714. }
  23715. // Bones
  23716. if (mesh && mesh.useBones) {
  23717. defines.push("#define BONES");
  23718. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23719. defines.push("#define BONES4");
  23720. fallbacks.addFallback(0, "BONES4");
  23721. }
  23722. // Alpha test
  23723. if (engine.getAlphaTesting()) {
  23724. defines.push("#define ALPHATEST");
  23725. }
  23726. var previousEffect = this._effect;
  23727. var join = defines.join("\n");
  23728. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  23729. if (!this._effect.isReady()) {
  23730. return false;
  23731. }
  23732. if (previousEffect !== this._effect) {
  23733. scene.resetCachedMaterial();
  23734. }
  23735. this._renderId = scene.getRenderId();
  23736. return true;
  23737. };
  23738. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23739. var scene = this.getScene();
  23740. if (this._options.uniforms.indexOf("world") !== -1) {
  23741. this._effect.setMatrix("world", world);
  23742. }
  23743. if (this._options.uniforms.indexOf("worldView") !== -1) {
  23744. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  23745. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  23746. }
  23747. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  23748. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  23749. }
  23750. };
  23751. ShaderMaterial.prototype.bind = function (world, mesh) {
  23752. // Std values
  23753. this.bindOnlyWorldMatrix(world);
  23754. if (this.getScene().getCachedMaterial() !== this) {
  23755. if (this._options.uniforms.indexOf("view") !== -1) {
  23756. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  23757. }
  23758. if (this._options.uniforms.indexOf("projection") !== -1) {
  23759. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  23760. }
  23761. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  23762. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23763. }
  23764. // Bones
  23765. if (mesh && mesh.useBones) {
  23766. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23767. }
  23768. // Texture
  23769. for (var name in this._textures) {
  23770. this._effect.setTexture(name, this._textures[name]);
  23771. }
  23772. // Float
  23773. for (name in this._floats) {
  23774. this._effect.setFloat(name, this._floats[name]);
  23775. }
  23776. // Float s
  23777. for (name in this._floatsArrays) {
  23778. this._effect.setArray(name, this._floatsArrays[name]);
  23779. }
  23780. // Color3
  23781. for (name in this._colors3) {
  23782. this._effect.setColor3(name, this._colors3[name]);
  23783. }
  23784. // Color4
  23785. for (name in this._colors4) {
  23786. var color = this._colors4[name];
  23787. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23788. }
  23789. // Vector2
  23790. for (name in this._vectors2) {
  23791. this._effect.setVector2(name, this._vectors2[name]);
  23792. }
  23793. // Vector3
  23794. for (name in this._vectors3) {
  23795. this._effect.setVector3(name, this._vectors3[name]);
  23796. }
  23797. // Matrix
  23798. for (name in this._matrices) {
  23799. this._effect.setMatrix(name, this._matrices[name]);
  23800. }
  23801. }
  23802. _super.prototype.bind.call(this, world, mesh);
  23803. };
  23804. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  23805. for (var name in this._textures) {
  23806. this._textures[name].dispose();
  23807. }
  23808. this._textures = [];
  23809. _super.prototype.dispose.call(this, forceDisposeEffect);
  23810. };
  23811. return ShaderMaterial;
  23812. })(BABYLON.Material);
  23813. BABYLON.ShaderMaterial = ShaderMaterial;
  23814. })(BABYLON || (BABYLON = {}));
  23815. //# sourceMappingURL=babylon.shaderMaterial.js.map
  23816. var BABYLON;
  23817. (function (BABYLON) {
  23818. var VertexData = (function () {
  23819. function VertexData() {
  23820. }
  23821. VertexData.prototype.set = function (data, kind) {
  23822. switch (kind) {
  23823. case BABYLON.VertexBuffer.PositionKind:
  23824. this.positions = data;
  23825. break;
  23826. case BABYLON.VertexBuffer.NormalKind:
  23827. this.normals = data;
  23828. break;
  23829. case BABYLON.VertexBuffer.UVKind:
  23830. this.uvs = data;
  23831. break;
  23832. case BABYLON.VertexBuffer.UV2Kind:
  23833. this.uv2s = data;
  23834. break;
  23835. case BABYLON.VertexBuffer.ColorKind:
  23836. this.colors = data;
  23837. break;
  23838. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23839. this.matricesIndices = data;
  23840. break;
  23841. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23842. this.matricesWeights = data;
  23843. break;
  23844. }
  23845. };
  23846. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23847. this._applyTo(mesh, updatable);
  23848. };
  23849. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23850. this._applyTo(geometry, updatable);
  23851. };
  23852. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23853. this._update(mesh);
  23854. };
  23855. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23856. this._update(geometry);
  23857. };
  23858. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23859. if (this.positions) {
  23860. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23861. }
  23862. if (this.normals) {
  23863. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23864. }
  23865. if (this.uvs) {
  23866. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23867. }
  23868. if (this.uv2s) {
  23869. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  23870. }
  23871. if (this.colors) {
  23872. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23873. }
  23874. if (this.matricesIndices) {
  23875. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23876. }
  23877. if (this.matricesWeights) {
  23878. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23879. }
  23880. if (this.indices) {
  23881. meshOrGeometry.setIndices(this.indices);
  23882. }
  23883. };
  23884. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23885. if (this.positions) {
  23886. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23887. }
  23888. if (this.normals) {
  23889. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23890. }
  23891. if (this.uvs) {
  23892. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23893. }
  23894. if (this.uv2s) {
  23895. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  23896. }
  23897. if (this.colors) {
  23898. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23899. }
  23900. if (this.matricesIndices) {
  23901. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23902. }
  23903. if (this.matricesWeights) {
  23904. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23905. }
  23906. if (this.indices) {
  23907. meshOrGeometry.setIndices(this.indices);
  23908. }
  23909. };
  23910. VertexData.prototype.transform = function (matrix) {
  23911. var transformed = BABYLON.Vector3.Zero();
  23912. if (this.positions) {
  23913. var position = BABYLON.Vector3.Zero();
  23914. for (var index = 0; index < this.positions.length; index += 3) {
  23915. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23916. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23917. this.positions[index] = transformed.x;
  23918. this.positions[index + 1] = transformed.y;
  23919. this.positions[index + 2] = transformed.z;
  23920. }
  23921. }
  23922. if (this.normals) {
  23923. var normal = BABYLON.Vector3.Zero();
  23924. for (index = 0; index < this.normals.length; index += 3) {
  23925. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23926. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23927. this.normals[index] = transformed.x;
  23928. this.normals[index + 1] = transformed.y;
  23929. this.normals[index + 2] = transformed.z;
  23930. }
  23931. }
  23932. };
  23933. VertexData.prototype.merge = function (other) {
  23934. if (other.indices) {
  23935. if (!this.indices) {
  23936. this.indices = [];
  23937. }
  23938. var offset = this.positions ? this.positions.length / 3 : 0;
  23939. for (var index = 0; index < other.indices.length; index++) {
  23940. this.indices.push(other.indices[index] + offset);
  23941. }
  23942. }
  23943. if (other.positions) {
  23944. if (!this.positions) {
  23945. this.positions = [];
  23946. }
  23947. for (index = 0; index < other.positions.length; index++) {
  23948. this.positions.push(other.positions[index]);
  23949. }
  23950. }
  23951. if (other.normals) {
  23952. if (!this.normals) {
  23953. this.normals = [];
  23954. }
  23955. for (index = 0; index < other.normals.length; index++) {
  23956. this.normals.push(other.normals[index]);
  23957. }
  23958. }
  23959. if (other.uvs) {
  23960. if (!this.uvs) {
  23961. this.uvs = [];
  23962. }
  23963. for (index = 0; index < other.uvs.length; index++) {
  23964. this.uvs.push(other.uvs[index]);
  23965. }
  23966. }
  23967. if (other.uv2s) {
  23968. if (!this.uv2s) {
  23969. this.uv2s = [];
  23970. }
  23971. for (index = 0; index < other.uv2s.length; index++) {
  23972. this.uv2s.push(other.uv2s[index]);
  23973. }
  23974. }
  23975. if (other.matricesIndices) {
  23976. if (!this.matricesIndices) {
  23977. this.matricesIndices = [];
  23978. }
  23979. for (index = 0; index < other.matricesIndices.length; index++) {
  23980. this.matricesIndices.push(other.matricesIndices[index]);
  23981. }
  23982. }
  23983. if (other.matricesWeights) {
  23984. if (!this.matricesWeights) {
  23985. this.matricesWeights = [];
  23986. }
  23987. for (index = 0; index < other.matricesWeights.length; index++) {
  23988. this.matricesWeights.push(other.matricesWeights[index]);
  23989. }
  23990. }
  23991. if (other.colors) {
  23992. if (!this.colors) {
  23993. this.colors = [];
  23994. }
  23995. for (index = 0; index < other.colors.length; index++) {
  23996. this.colors.push(other.colors[index]);
  23997. }
  23998. }
  23999. };
  24000. // Statics
  24001. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24002. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24003. };
  24004. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24005. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24006. };
  24007. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24008. var result = new VertexData();
  24009. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24010. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24011. }
  24012. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24013. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24014. }
  24015. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24016. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24017. }
  24018. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24019. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24020. }
  24021. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24022. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24023. }
  24024. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24025. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24026. }
  24027. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24028. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24029. }
  24030. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24031. return result;
  24032. };
  24033. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24034. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24035. closeArray = closeArray || false;
  24036. closePath = closePath || false;
  24037. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24038. offset = offset || defaultOffset;
  24039. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24040. var positions = [];
  24041. var indices = [];
  24042. var normals = [];
  24043. var uvs = [];
  24044. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24045. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24046. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24047. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24048. var minlg; // minimal length among all paths from pathArray
  24049. var lg = []; // array of path lengths : nb of vertex per path
  24050. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24051. var p; // path iterator
  24052. var i; // point iterator
  24053. var j; // point iterator
  24054. // if single path in pathArray
  24055. if (pathArray.length < 2) {
  24056. var ar1 = [];
  24057. var ar2 = [];
  24058. for (i = 0; i < pathArray[0].length - offset; i++) {
  24059. ar1.push(pathArray[0][i]);
  24060. ar2.push(pathArray[0][i + offset]);
  24061. }
  24062. pathArray = [ar1, ar2];
  24063. }
  24064. // positions and horizontal distances (u)
  24065. var idc = 0;
  24066. minlg = pathArray[0].length;
  24067. for (p = 0; p < pathArray.length; p++) {
  24068. uTotalDistance[p] = 0;
  24069. us[p] = [0];
  24070. var path = pathArray[p];
  24071. var l = path.length;
  24072. minlg = (minlg < l) ? minlg : l;
  24073. lg[p] = l;
  24074. idx[p] = idc;
  24075. j = 0;
  24076. while (j < l) {
  24077. positions.push(path[j].x, path[j].y, path[j].z);
  24078. if (j > 0) {
  24079. var vectlg = path[j].subtract(path[j - 1]).length();
  24080. var dist = vectlg + uTotalDistance[p];
  24081. us[p].push(dist);
  24082. uTotalDistance[p] = dist;
  24083. }
  24084. j++;
  24085. }
  24086. if (closePath) {
  24087. vectlg = path[0].subtract(path[j - 1]).length();
  24088. dist = vectlg + uTotalDistance[p];
  24089. uTotalDistance[p] = dist;
  24090. }
  24091. idc += l;
  24092. }
  24093. // vertical distances (v)
  24094. for (i = 0; i < minlg; i++) {
  24095. vTotalDistance[i] = 0;
  24096. vs[i] = [0];
  24097. var path1;
  24098. var path2;
  24099. for (p = 0; p < pathArray.length - 1; p++) {
  24100. path1 = pathArray[p];
  24101. path2 = pathArray[p + 1];
  24102. vectlg = path2[i].subtract(path1[i]).length();
  24103. dist = vectlg + vTotalDistance[i];
  24104. vs[i].push(dist);
  24105. vTotalDistance[i] = dist;
  24106. }
  24107. if (closeArray) {
  24108. path1 = pathArray[p];
  24109. path2 = pathArray[0];
  24110. vectlg = path2[i].subtract(path1[i]).length();
  24111. dist = vectlg + vTotalDistance[i];
  24112. vTotalDistance[i] = dist;
  24113. }
  24114. }
  24115. // uvs
  24116. var u;
  24117. var v;
  24118. for (p = 0; p < pathArray.length; p++) {
  24119. for (i = 0; i < minlg; i++) {
  24120. u = us[p][i] / uTotalDistance[p];
  24121. v = vs[i][p] / vTotalDistance[i];
  24122. uvs.push(u, v);
  24123. }
  24124. }
  24125. // indices
  24126. p = 0; // path index
  24127. var pi = 0; // positions array index
  24128. var l1 = lg[p] - 1; // path1 length
  24129. var l2 = lg[p + 1] - 1; // path2 length
  24130. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24131. var shft = idx[1] - idx[0]; // shift
  24132. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  24133. var t1; // two consecutive triangles, so 4 points : point1
  24134. var t2; // point2
  24135. var t3; // point3
  24136. var t4; // point4
  24137. while (pi <= min && p < path1nb) {
  24138. // 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
  24139. t1 = pi;
  24140. t2 = pi + shft;
  24141. t3 = pi + 1;
  24142. t4 = pi + shft + 1;
  24143. indices.push(pi, pi + shft, pi + 1);
  24144. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24145. pi += 1;
  24146. if (pi === min) {
  24147. if (closePath) {
  24148. indices.push(pi, pi + shft, idx[p]);
  24149. indices.push(idx[p] + shft, idx[p], pi + shft);
  24150. t3 = idx[p];
  24151. t4 = idx[p] + shft;
  24152. }
  24153. p++;
  24154. if (p === lg.length - 1) {
  24155. shft = idx[0] - idx[p];
  24156. l1 = lg[p] - 1;
  24157. l2 = lg[0] - 1;
  24158. }
  24159. else {
  24160. shft = idx[p + 1] - idx[p];
  24161. l1 = lg[p] - 1;
  24162. l2 = lg[p + 1] - 1;
  24163. }
  24164. pi = idx[p];
  24165. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24166. }
  24167. }
  24168. // normals
  24169. VertexData.ComputeNormals(positions, indices, normals);
  24170. // sides
  24171. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24172. // Result
  24173. var vertexData = new VertexData();
  24174. vertexData.indices = indices;
  24175. vertexData.positions = positions;
  24176. vertexData.normals = normals;
  24177. vertexData.uvs = uvs;
  24178. return vertexData;
  24179. };
  24180. VertexData.CreateBox = function (size, sideOrientation) {
  24181. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24182. var normalsSource = [
  24183. new BABYLON.Vector3(0, 0, 1),
  24184. new BABYLON.Vector3(0, 0, -1),
  24185. new BABYLON.Vector3(1, 0, 0),
  24186. new BABYLON.Vector3(-1, 0, 0),
  24187. new BABYLON.Vector3(0, 1, 0),
  24188. new BABYLON.Vector3(0, -1, 0)
  24189. ];
  24190. var indices = [];
  24191. var positions = [];
  24192. var normals = [];
  24193. var uvs = [];
  24194. size = size || 1;
  24195. // Create each face in turn.
  24196. for (var index = 0; index < normalsSource.length; index++) {
  24197. var normal = normalsSource[index];
  24198. // Get two vectors perpendicular to the face normal and to each other.
  24199. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24200. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24201. // Six indices (two triangles) per face.
  24202. var verticesLength = positions.length / 3;
  24203. indices.push(verticesLength);
  24204. indices.push(verticesLength + 1);
  24205. indices.push(verticesLength + 2);
  24206. indices.push(verticesLength);
  24207. indices.push(verticesLength + 2);
  24208. indices.push(verticesLength + 3);
  24209. // Four vertices per face.
  24210. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  24211. positions.push(vertex.x, vertex.y, vertex.z);
  24212. normals.push(normal.x, normal.y, normal.z);
  24213. uvs.push(1.0, 1.0);
  24214. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  24215. positions.push(vertex.x, vertex.y, vertex.z);
  24216. normals.push(normal.x, normal.y, normal.z);
  24217. uvs.push(0.0, 1.0);
  24218. vertex = normal.add(side1).add(side2).scale(size / 2);
  24219. positions.push(vertex.x, vertex.y, vertex.z);
  24220. normals.push(normal.x, normal.y, normal.z);
  24221. uvs.push(0.0, 0.0);
  24222. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  24223. positions.push(vertex.x, vertex.y, vertex.z);
  24224. normals.push(normal.x, normal.y, normal.z);
  24225. uvs.push(1.0, 0.0);
  24226. }
  24227. // sides
  24228. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24229. // Result
  24230. var vertexData = new VertexData();
  24231. vertexData.indices = indices;
  24232. vertexData.positions = positions;
  24233. vertexData.normals = normals;
  24234. vertexData.uvs = uvs;
  24235. return vertexData;
  24236. };
  24237. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  24238. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24239. segments = segments || 32;
  24240. diameter = diameter || 1;
  24241. var radius = diameter / 2;
  24242. var totalZRotationSteps = 2 + segments;
  24243. var totalYRotationSteps = 2 * totalZRotationSteps;
  24244. var indices = [];
  24245. var positions = [];
  24246. var normals = [];
  24247. var uvs = [];
  24248. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24249. var normalizedZ = zRotationStep / totalZRotationSteps;
  24250. var angleZ = (normalizedZ * Math.PI);
  24251. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24252. var normalizedY = yRotationStep / totalYRotationSteps;
  24253. var angleY = normalizedY * Math.PI * 2;
  24254. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24255. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24256. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24257. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24258. var vertex = complete.scale(radius);
  24259. var normal = BABYLON.Vector3.Normalize(vertex);
  24260. positions.push(vertex.x, vertex.y, vertex.z);
  24261. normals.push(normal.x, normal.y, normal.z);
  24262. uvs.push(normalizedZ, normalizedY);
  24263. }
  24264. if (zRotationStep > 0) {
  24265. var verticesCount = positions.length / 3;
  24266. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24267. indices.push((firstIndex));
  24268. indices.push((firstIndex + 1));
  24269. indices.push(firstIndex + totalYRotationSteps + 1);
  24270. indices.push((firstIndex + totalYRotationSteps + 1));
  24271. indices.push((firstIndex + 1));
  24272. indices.push((firstIndex + totalYRotationSteps + 2));
  24273. }
  24274. }
  24275. }
  24276. // Sides
  24277. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24278. // Result
  24279. var vertexData = new VertexData();
  24280. vertexData.indices = indices;
  24281. vertexData.positions = positions;
  24282. vertexData.normals = normals;
  24283. vertexData.uvs = uvs;
  24284. return vertexData;
  24285. };
  24286. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  24287. if (subdivisions === void 0) { subdivisions = 1; }
  24288. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24289. var radiusTop = diameterTop / 2;
  24290. var radiusBottom = diameterBottom / 2;
  24291. var indices = [];
  24292. var positions = [];
  24293. var normals = [];
  24294. var uvs = [];
  24295. height = height || 1;
  24296. diameterTop = diameterTop || 0.5;
  24297. diameterBottom = diameterBottom || 1;
  24298. tessellation = tessellation || 16;
  24299. subdivisions = subdivisions || 1;
  24300. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  24301. var getCircleVector = function (i) {
  24302. var angle = (i * 2.0 * Math.PI / tessellation);
  24303. var dx = Math.cos(angle);
  24304. var dz = Math.sin(angle);
  24305. return new BABYLON.Vector3(dx, 0, dz);
  24306. };
  24307. var createCylinderCap = function (isTop) {
  24308. var radius = isTop ? radiusTop : radiusBottom;
  24309. if (radius === 0) {
  24310. return;
  24311. }
  24312. var vbase = positions.length / 3;
  24313. var offset = new BABYLON.Vector3(0, height / 2, 0);
  24314. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24315. if (!isTop) {
  24316. offset.scaleInPlace(-1);
  24317. textureScale.x = -textureScale.x;
  24318. }
  24319. // Positions, normals & uvs
  24320. for (var i = 0; i < tessellation; i++) {
  24321. var circleVector = getCircleVector(i);
  24322. var position = circleVector.scale(radius).add(offset);
  24323. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  24324. positions.push(position.x, position.y, position.z);
  24325. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24326. }
  24327. // Indices
  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. // Positions, normals & uvs
  24345. for (var i = 0; i <= tessellation; i++) {
  24346. var circleVector = getCircleVector(i);
  24347. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  24348. var position, radius = radiusBottom;
  24349. for (var s = 0; s <= subdivisions; s++) {
  24350. // Update variables
  24351. position = circleVector.scale(radius);
  24352. position.addInPlace(base.add(offset.scale(s)));
  24353. textureCoordinate.y += 1 / subdivisions;
  24354. radius += (radiusTop - radiusBottom) / subdivisions;
  24355. // Push in arrays
  24356. positions.push(position.x, position.y, position.z);
  24357. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24358. }
  24359. }
  24360. subdivisions += 1;
  24361. // Indices
  24362. for (s = 0; s < subdivisions - 1; s++) {
  24363. for (i = 0; i <= tessellation; i++) {
  24364. indices.push(i * subdivisions + s);
  24365. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24366. indices.push(i * subdivisions + (s + 1));
  24367. indices.push(i * subdivisions + (s + 1));
  24368. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24369. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  24370. }
  24371. }
  24372. // Create flat triangle fan caps to seal the top and bottom.
  24373. createCylinderCap(true);
  24374. createCylinderCap(false);
  24375. // Normals
  24376. VertexData.ComputeNormals(positions, indices, normals);
  24377. // Sides
  24378. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24379. // Result
  24380. var vertexData = new VertexData();
  24381. vertexData.indices = indices;
  24382. vertexData.positions = positions;
  24383. vertexData.normals = normals;
  24384. vertexData.uvs = uvs;
  24385. return vertexData;
  24386. };
  24387. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  24388. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24389. var indices = [];
  24390. var positions = [];
  24391. var normals = [];
  24392. var uvs = [];
  24393. diameter = diameter || 1;
  24394. thickness = thickness || 0.5;
  24395. tessellation = tessellation || 16;
  24396. var stride = tessellation + 1;
  24397. for (var i = 0; i <= tessellation; i++) {
  24398. var u = i / tessellation;
  24399. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24400. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24401. for (var j = 0; j <= tessellation; j++) {
  24402. var v = 1 - j / tessellation;
  24403. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24404. var dx = Math.cos(innerAngle);
  24405. var dy = Math.sin(innerAngle);
  24406. // Create a vertex.
  24407. var normal = new BABYLON.Vector3(dx, dy, 0);
  24408. var position = normal.scale(thickness / 2);
  24409. var textureCoordinate = new BABYLON.Vector2(u, v);
  24410. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24411. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24412. positions.push(position.x, position.y, position.z);
  24413. normals.push(normal.x, normal.y, normal.z);
  24414. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24415. // And create indices for two triangles.
  24416. var nextI = (i + 1) % stride;
  24417. var nextJ = (j + 1) % stride;
  24418. indices.push(i * stride + j);
  24419. indices.push(i * stride + nextJ);
  24420. indices.push(nextI * stride + j);
  24421. indices.push(i * stride + nextJ);
  24422. indices.push(nextI * stride + nextJ);
  24423. indices.push(nextI * stride + j);
  24424. }
  24425. }
  24426. // Sides
  24427. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24428. // Result
  24429. var vertexData = new VertexData();
  24430. vertexData.indices = indices;
  24431. vertexData.positions = positions;
  24432. vertexData.normals = normals;
  24433. vertexData.uvs = uvs;
  24434. return vertexData;
  24435. };
  24436. VertexData.CreateLines = function (points) {
  24437. var indices = [];
  24438. var positions = [];
  24439. for (var index = 0; index < points.length; index++) {
  24440. positions.push(points[index].x, points[index].y, points[index].z);
  24441. if (index > 0) {
  24442. indices.push(index - 1);
  24443. indices.push(index);
  24444. }
  24445. }
  24446. // Result
  24447. var vertexData = new VertexData();
  24448. vertexData.indices = indices;
  24449. vertexData.positions = positions;
  24450. return vertexData;
  24451. };
  24452. VertexData.CreateGround = function (width, height, subdivisions) {
  24453. var indices = [];
  24454. var positions = [];
  24455. var normals = [];
  24456. var uvs = [];
  24457. var row, col;
  24458. width = width || 1;
  24459. height = height || 1;
  24460. subdivisions = subdivisions || 1;
  24461. for (row = 0; row <= subdivisions; row++) {
  24462. for (col = 0; col <= subdivisions; col++) {
  24463. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24464. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24465. positions.push(position.x, position.y, position.z);
  24466. normals.push(normal.x, normal.y, normal.z);
  24467. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24468. }
  24469. }
  24470. for (row = 0; row < subdivisions; row++) {
  24471. for (col = 0; col < subdivisions; col++) {
  24472. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24473. indices.push(col + 1 + row * (subdivisions + 1));
  24474. indices.push(col + row * (subdivisions + 1));
  24475. indices.push(col + (row + 1) * (subdivisions + 1));
  24476. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24477. indices.push(col + row * (subdivisions + 1));
  24478. }
  24479. }
  24480. // Result
  24481. var vertexData = new VertexData();
  24482. vertexData.indices = indices;
  24483. vertexData.positions = positions;
  24484. vertexData.normals = normals;
  24485. vertexData.uvs = uvs;
  24486. return vertexData;
  24487. };
  24488. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  24489. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  24490. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  24491. var indices = [];
  24492. var positions = [];
  24493. var normals = [];
  24494. var uvs = [];
  24495. var row, col, tileRow, tileCol;
  24496. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24497. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24498. precision.w = (precision.w < 1) ? 1 : precision.w;
  24499. precision.h = (precision.h < 1) ? 1 : precision.h;
  24500. var tileSize = {
  24501. 'w': (xmax - xmin) / subdivisions.w,
  24502. 'h': (zmax - zmin) / subdivisions.h
  24503. };
  24504. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24505. // Indices
  24506. var base = positions.length / 3;
  24507. var rowLength = precision.w + 1;
  24508. for (row = 0; row < precision.h; row++) {
  24509. for (col = 0; col < precision.w; col++) {
  24510. var square = [
  24511. base + col + row * rowLength,
  24512. base + (col + 1) + row * rowLength,
  24513. base + (col + 1) + (row + 1) * rowLength,
  24514. base + col + (row + 1) * rowLength
  24515. ];
  24516. indices.push(square[1]);
  24517. indices.push(square[2]);
  24518. indices.push(square[3]);
  24519. indices.push(square[0]);
  24520. indices.push(square[1]);
  24521. indices.push(square[3]);
  24522. }
  24523. }
  24524. // Position, normals and uvs
  24525. var position = BABYLON.Vector3.Zero();
  24526. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24527. for (row = 0; row <= precision.h; row++) {
  24528. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24529. for (col = 0; col <= precision.w; col++) {
  24530. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24531. position.y = 0;
  24532. positions.push(position.x, position.y, position.z);
  24533. normals.push(normal.x, normal.y, normal.z);
  24534. uvs.push(col / precision.w, row / precision.h);
  24535. }
  24536. }
  24537. }
  24538. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24539. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24540. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24541. }
  24542. }
  24543. // Result
  24544. var vertexData = new VertexData();
  24545. vertexData.indices = indices;
  24546. vertexData.positions = positions;
  24547. vertexData.normals = normals;
  24548. vertexData.uvs = uvs;
  24549. return vertexData;
  24550. };
  24551. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  24552. var indices = [];
  24553. var positions = [];
  24554. var normals = [];
  24555. var uvs = [];
  24556. var row, col;
  24557. // Vertices
  24558. for (row = 0; row <= subdivisions; row++) {
  24559. for (col = 0; col <= subdivisions; col++) {
  24560. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24561. // Compute height
  24562. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  24563. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  24564. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  24565. var r = buffer[pos] / 255.0;
  24566. var g = buffer[pos + 1] / 255.0;
  24567. var b = buffer[pos + 2] / 255.0;
  24568. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24569. position.y = minHeight + (maxHeight - minHeight) * gradient;
  24570. // Add vertex
  24571. positions.push(position.x, position.y, position.z);
  24572. normals.push(0, 0, 0);
  24573. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24574. }
  24575. }
  24576. // Indices
  24577. for (row = 0; row < subdivisions; row++) {
  24578. for (col = 0; col < subdivisions; col++) {
  24579. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24580. indices.push(col + 1 + row * (subdivisions + 1));
  24581. indices.push(col + row * (subdivisions + 1));
  24582. indices.push(col + (row + 1) * (subdivisions + 1));
  24583. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24584. indices.push(col + row * (subdivisions + 1));
  24585. }
  24586. }
  24587. // Normals
  24588. VertexData.ComputeNormals(positions, indices, normals);
  24589. // Result
  24590. var vertexData = new VertexData();
  24591. vertexData.indices = indices;
  24592. vertexData.positions = positions;
  24593. vertexData.normals = normals;
  24594. vertexData.uvs = uvs;
  24595. return vertexData;
  24596. };
  24597. VertexData.CreatePlane = function (size, sideOrientation) {
  24598. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24599. var indices = [];
  24600. var positions = [];
  24601. var normals = [];
  24602. var uvs = [];
  24603. size = size || 1;
  24604. // Vertices
  24605. var halfSize = size / 2.0;
  24606. positions.push(-halfSize, -halfSize, 0);
  24607. normals.push(0, 0, -1.0);
  24608. uvs.push(0.0, 0.0);
  24609. positions.push(halfSize, -halfSize, 0);
  24610. normals.push(0, 0, -1.0);
  24611. uvs.push(1.0, 0.0);
  24612. positions.push(halfSize, halfSize, 0);
  24613. normals.push(0, 0, -1.0);
  24614. uvs.push(1.0, 1.0);
  24615. positions.push(-halfSize, halfSize, 0);
  24616. normals.push(0, 0, -1.0);
  24617. uvs.push(0.0, 1.0);
  24618. // Indices
  24619. indices.push(0);
  24620. indices.push(1);
  24621. indices.push(2);
  24622. indices.push(0);
  24623. indices.push(2);
  24624. indices.push(3);
  24625. // Sides
  24626. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24627. // Result
  24628. var vertexData = new VertexData();
  24629. vertexData.indices = indices;
  24630. vertexData.positions = positions;
  24631. vertexData.normals = normals;
  24632. vertexData.uvs = uvs;
  24633. return vertexData;
  24634. };
  24635. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  24636. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24637. var positions = [];
  24638. var indices = [];
  24639. var normals = [];
  24640. var uvs = [];
  24641. // positions and uvs
  24642. positions.push(0, 0, 0); // disc center first
  24643. uvs.push(0.5, 0.5);
  24644. var step = Math.PI * 2 / tessellation;
  24645. for (var a = 0; a < Math.PI * 2; a += step) {
  24646. var x = Math.cos(a);
  24647. var y = Math.sin(a);
  24648. var u = (x + 1) / 2;
  24649. var v = (1 - y) / 2;
  24650. positions.push(radius * x, radius * y, 0);
  24651. uvs.push(u, v);
  24652. }
  24653. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24654. uvs.push(uvs[2], uvs[3]);
  24655. //indices
  24656. var vertexNb = positions.length / 3;
  24657. for (var i = 1; i < vertexNb - 1; i++) {
  24658. indices.push(i + 1, 0, i);
  24659. }
  24660. // result
  24661. VertexData.ComputeNormals(positions, indices, normals);
  24662. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24663. var vertexData = new VertexData();
  24664. vertexData.indices = indices;
  24665. vertexData.positions = positions;
  24666. vertexData.normals = normals;
  24667. vertexData.uvs = uvs;
  24668. return vertexData;
  24669. };
  24670. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24671. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  24672. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24673. var indices = [];
  24674. var positions = [];
  24675. var normals = [];
  24676. var uvs = [];
  24677. radius = radius || 2;
  24678. tube = tube || 0.5;
  24679. radialSegments = radialSegments || 32;
  24680. tubularSegments = tubularSegments || 32;
  24681. p = p || 2;
  24682. q = q || 3;
  24683. // Helper
  24684. var getPos = function (angle) {
  24685. var cu = Math.cos(angle);
  24686. var su = Math.sin(angle);
  24687. var quOverP = q / p * angle;
  24688. var cs = Math.cos(quOverP);
  24689. var tx = radius * (2 + cs) * 0.5 * cu;
  24690. var ty = radius * (2 + cs) * su * 0.5;
  24691. var tz = radius * Math.sin(quOverP) * 0.5;
  24692. return new BABYLON.Vector3(tx, ty, tz);
  24693. };
  24694. // Vertices
  24695. for (var i = 0; i <= radialSegments; i++) {
  24696. var modI = i % radialSegments;
  24697. var u = modI / radialSegments * 2 * p * Math.PI;
  24698. var p1 = getPos(u);
  24699. var p2 = getPos(u + 0.01);
  24700. var tang = p2.subtract(p1);
  24701. var n = p2.add(p1);
  24702. var bitan = BABYLON.Vector3.Cross(tang, n);
  24703. n = BABYLON.Vector3.Cross(bitan, tang);
  24704. bitan.normalize();
  24705. n.normalize();
  24706. for (var j = 0; j < tubularSegments; j++) {
  24707. var modJ = j % tubularSegments;
  24708. var v = modJ / tubularSegments * 2 * Math.PI;
  24709. var cx = -tube * Math.cos(v);
  24710. var cy = tube * Math.sin(v);
  24711. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24712. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24713. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24714. uvs.push(i / radialSegments);
  24715. uvs.push(j / tubularSegments);
  24716. }
  24717. }
  24718. for (i = 0; i < radialSegments; i++) {
  24719. for (j = 0; j < tubularSegments; j++) {
  24720. var jNext = (j + 1) % tubularSegments;
  24721. var a = i * tubularSegments + j;
  24722. var b = (i + 1) * tubularSegments + j;
  24723. var c = (i + 1) * tubularSegments + jNext;
  24724. var d = i * tubularSegments + jNext;
  24725. indices.push(d);
  24726. indices.push(b);
  24727. indices.push(a);
  24728. indices.push(d);
  24729. indices.push(c);
  24730. indices.push(b);
  24731. }
  24732. }
  24733. // Normals
  24734. VertexData.ComputeNormals(positions, indices, normals);
  24735. // Sides
  24736. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24737. // Result
  24738. var vertexData = new VertexData();
  24739. vertexData.indices = indices;
  24740. vertexData.positions = positions;
  24741. vertexData.normals = normals;
  24742. vertexData.uvs = uvs;
  24743. return vertexData;
  24744. };
  24745. // Tools
  24746. /**
  24747. * @param {any} - positions (number[] or Float32Array)
  24748. * @param {any} - indices (number[] or Uint16Array)
  24749. * @param {any} - normals (number[] or Float32Array)
  24750. */
  24751. VertexData.ComputeNormals = function (positions, indices, normals) {
  24752. var index = 0;
  24753. // temp Vector3
  24754. var p1 = BABYLON.Vector3.Zero();
  24755. var p2 = BABYLON.Vector3.Zero();
  24756. var p3 = BABYLON.Vector3.Zero();
  24757. var p1p2 = BABYLON.Vector3.Zero();
  24758. var p3p2 = BABYLON.Vector3.Zero();
  24759. var faceNormal = BABYLON.Vector3.Zero();
  24760. var vertexNormali1 = BABYLON.Vector3.Zero();
  24761. var vertexNormali2 = BABYLON.Vector3.Zero();
  24762. var vertexNormali3 = BABYLON.Vector3.Zero();
  24763. // indice triplet = 1 face
  24764. var nbFaces = indices.length / 3;
  24765. for (index = 0; index < nbFaces; index++) {
  24766. var i1 = indices[index * 3];
  24767. var i2 = indices[index * 3 + 1];
  24768. var i3 = indices[index * 3 + 2];
  24769. // setting the temp V3
  24770. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  24771. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  24772. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  24773. p1.subtractToRef(p2, p1p2);
  24774. p3.subtractToRef(p2, p3p2);
  24775. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24776. faceNormal.normalize();
  24777. // All intermediate results are stored in the normals array :
  24778. // get the normals at i1, i2 and i3 indexes
  24779. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  24780. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  24781. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  24782. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  24783. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  24784. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  24785. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  24786. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  24787. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  24788. // make intermediate vectors3 from normals values
  24789. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  24790. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  24791. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  24792. // add the current face normals to these intermediate vectors3
  24793. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  24794. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  24795. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  24796. // store back intermediate vectors3 into the normals array
  24797. normals[i1 * 3] = vertexNormali1.x;
  24798. normals[i1 * 3 + 1] = vertexNormali1.y;
  24799. normals[i1 * 3 + 2] = vertexNormali1.z;
  24800. normals[i2 * 3] = vertexNormali2.x;
  24801. normals[i2 * 3 + 1] = vertexNormali2.y;
  24802. normals[i2 * 3 + 2] = vertexNormali2.z;
  24803. normals[i3 * 3] = vertexNormali3.x;
  24804. normals[i3 * 3 + 1] = vertexNormali3.y;
  24805. normals[i3 * 3 + 2] = vertexNormali3.z;
  24806. }
  24807. // last normalization
  24808. for (index = 0; index < normals.length / 3; index++) {
  24809. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24810. vertexNormali1.normalize();
  24811. normals[index * 3] = vertexNormali1.x;
  24812. normals[index * 3 + 1] = vertexNormali1.y;
  24813. normals[index * 3 + 2] = vertexNormali1.z;
  24814. }
  24815. };
  24816. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24817. var li = indices.length;
  24818. var ln = normals.length;
  24819. var i;
  24820. var n;
  24821. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24822. switch (sideOrientation) {
  24823. case BABYLON.Mesh.FRONTSIDE:
  24824. // nothing changed
  24825. break;
  24826. case BABYLON.Mesh.BACKSIDE:
  24827. var tmp;
  24828. // indices
  24829. for (i = 0; i < li; i += 3) {
  24830. tmp = indices[i];
  24831. indices[i] = indices[i + 2];
  24832. indices[i + 2] = tmp;
  24833. }
  24834. // normals
  24835. for (n = 0; n < ln; n++) {
  24836. normals[n] = -normals[n];
  24837. }
  24838. break;
  24839. case BABYLON.Mesh.DOUBLESIDE:
  24840. // positions
  24841. var lp = positions.length;
  24842. var l = lp / 3;
  24843. for (var p = 0; p < lp; p++) {
  24844. positions[lp + p] = positions[p];
  24845. }
  24846. // indices
  24847. for (i = 0; i < li; i += 3) {
  24848. indices[i + li] = indices[i + 2] + l;
  24849. indices[i + 1 + li] = indices[i + 1] + l;
  24850. indices[i + 2 + li] = indices[i] + l;
  24851. }
  24852. // normals
  24853. for (n = 0; n < ln; n++) {
  24854. normals[ln + n] = -normals[n];
  24855. }
  24856. // uvs
  24857. var lu = uvs.length;
  24858. for (var u = 0; u < lu; u++) {
  24859. uvs[u + lu] = uvs[u];
  24860. }
  24861. break;
  24862. }
  24863. };
  24864. return VertexData;
  24865. })();
  24866. BABYLON.VertexData = VertexData;
  24867. })(BABYLON || (BABYLON = {}));
  24868. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  24869. var __extends = this.__extends || function (d, b) {
  24870. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24871. function __() { this.constructor = d; }
  24872. __.prototype = b.prototype;
  24873. d.prototype = new __();
  24874. };
  24875. var BABYLON;
  24876. (function (BABYLON) {
  24877. var buildCamera = function (that, name) {
  24878. that._leftCamera.isIntermediate = true;
  24879. that.subCameras.push(that._leftCamera);
  24880. that.subCameras.push(that._rightCamera);
  24881. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  24882. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  24883. that._anaglyphPostProcess.onApply = function (effect) {
  24884. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  24885. };
  24886. that._update();
  24887. };
  24888. var AnaglyphArcRotateCamera = (function (_super) {
  24889. __extends(AnaglyphArcRotateCamera, _super);
  24890. // ANY
  24891. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  24892. _super.call(this, name, alpha, beta, radius, target, scene);
  24893. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24894. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  24895. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  24896. buildCamera(this, name);
  24897. }
  24898. AnaglyphArcRotateCamera.prototype._update = function () {
  24899. this._updateCamera(this._leftCamera);
  24900. this._updateCamera(this._rightCamera);
  24901. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  24902. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  24903. _super.prototype._update.call(this);
  24904. };
  24905. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  24906. camera.beta = this.beta;
  24907. camera.radius = this.radius;
  24908. camera.minZ = this.minZ;
  24909. camera.maxZ = this.maxZ;
  24910. camera.fov = this.fov;
  24911. camera.target = this.target;
  24912. };
  24913. return AnaglyphArcRotateCamera;
  24914. })(BABYLON.ArcRotateCamera);
  24915. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  24916. var AnaglyphFreeCamera = (function (_super) {
  24917. __extends(AnaglyphFreeCamera, _super);
  24918. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  24919. _super.call(this, name, position, scene);
  24920. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24921. this._transformMatrix = new BABYLON.Matrix();
  24922. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  24923. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  24924. buildCamera(this, name);
  24925. }
  24926. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  24927. var target = this.getTarget();
  24928. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  24929. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  24930. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  24931. };
  24932. AnaglyphFreeCamera.prototype._update = function () {
  24933. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  24934. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  24935. this._updateCamera(this._leftCamera);
  24936. this._updateCamera(this._rightCamera);
  24937. _super.prototype._update.call(this);
  24938. };
  24939. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  24940. camera.minZ = this.minZ;
  24941. camera.maxZ = this.maxZ;
  24942. camera.fov = this.fov;
  24943. camera.viewport = this.viewport;
  24944. camera.setTarget(this.getTarget());
  24945. };
  24946. return AnaglyphFreeCamera;
  24947. })(BABYLON.FreeCamera);
  24948. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  24949. })(BABYLON || (BABYLON = {}));
  24950. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  24951. var __extends = this.__extends || function (d, b) {
  24952. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24953. function __() { this.constructor = d; }
  24954. __.prototype = b.prototype;
  24955. d.prototype = new __();
  24956. };
  24957. var BABYLON;
  24958. (function (BABYLON) {
  24959. var AnaglyphPostProcess = (function (_super) {
  24960. __extends(AnaglyphPostProcess, _super);
  24961. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  24962. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  24963. }
  24964. return AnaglyphPostProcess;
  24965. })(BABYLON.PostProcess);
  24966. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  24967. })(BABYLON || (BABYLON = {}));
  24968. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  24969. var BABYLON;
  24970. (function (BABYLON) {
  24971. var Tags = (function () {
  24972. function Tags() {
  24973. }
  24974. Tags.EnableFor = function (obj) {
  24975. obj._tags = obj._tags || {};
  24976. obj.hasTags = function () {
  24977. return Tags.HasTags(obj);
  24978. };
  24979. obj.addTags = function (tagsString) {
  24980. return Tags.AddTagsTo(obj, tagsString);
  24981. };
  24982. obj.removeTags = function (tagsString) {
  24983. return Tags.RemoveTagsFrom(obj, tagsString);
  24984. };
  24985. obj.matchesTagsQuery = function (tagsQuery) {
  24986. return Tags.MatchesQuery(obj, tagsQuery);
  24987. };
  24988. };
  24989. Tags.DisableFor = function (obj) {
  24990. delete obj._tags;
  24991. delete obj.hasTags;
  24992. delete obj.addTags;
  24993. delete obj.removeTags;
  24994. delete obj.matchesTagsQuery;
  24995. };
  24996. Tags.HasTags = function (obj) {
  24997. if (!obj._tags) {
  24998. return false;
  24999. }
  25000. return !BABYLON.Tools.IsEmpty(obj._tags);
  25001. };
  25002. Tags.GetTags = function (obj) {
  25003. if (!obj._tags) {
  25004. return null;
  25005. }
  25006. return obj._tags;
  25007. };
  25008. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25009. // a tag cannot start with '||', '&&', and '!'
  25010. // it cannot contain whitespaces
  25011. Tags.AddTagsTo = function (obj, tagsString) {
  25012. if (!tagsString) {
  25013. return;
  25014. }
  25015. var tags = tagsString.split(" ");
  25016. for (var t in tags) {
  25017. Tags._AddTagTo(obj, tags[t]);
  25018. }
  25019. };
  25020. Tags._AddTagTo = function (obj, tag) {
  25021. tag = tag.trim();
  25022. if (tag === "" || tag === "true" || tag === "false") {
  25023. return;
  25024. }
  25025. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25026. return;
  25027. }
  25028. Tags.EnableFor(obj);
  25029. obj._tags[tag] = true;
  25030. };
  25031. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25032. if (!Tags.HasTags(obj)) {
  25033. return;
  25034. }
  25035. var tags = tagsString.split(" ");
  25036. for (var t in tags) {
  25037. Tags._RemoveTagFrom(obj, tags[t]);
  25038. }
  25039. };
  25040. Tags._RemoveTagFrom = function (obj, tag) {
  25041. delete obj._tags[tag];
  25042. };
  25043. Tags.MatchesQuery = function (obj, tagsQuery) {
  25044. if (tagsQuery === undefined) {
  25045. return true;
  25046. }
  25047. if (tagsQuery === "") {
  25048. return Tags.HasTags(obj);
  25049. }
  25050. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25051. };
  25052. return Tags;
  25053. })();
  25054. BABYLON.Tags = Tags;
  25055. })(BABYLON || (BABYLON = {}));
  25056. //# sourceMappingURL=babylon.tags.js.map
  25057. var BABYLON;
  25058. (function (BABYLON) {
  25059. var Internals;
  25060. (function (Internals) {
  25061. var AndOrNotEvaluator = (function () {
  25062. function AndOrNotEvaluator() {
  25063. }
  25064. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25065. if (!query.match(/\([^\(\)]*\)/g)) {
  25066. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25067. }
  25068. else {
  25069. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25070. // remove parenthesis
  25071. r = r.slice(1, r.length - 1);
  25072. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25073. });
  25074. }
  25075. if (query === "true") {
  25076. return true;
  25077. }
  25078. if (query === "false") {
  25079. return false;
  25080. }
  25081. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25082. };
  25083. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25084. evaluateCallback = evaluateCallback || (function (r) {
  25085. return r === "true" ? true : false;
  25086. });
  25087. var result;
  25088. var or = parenthesisContent.split("||");
  25089. for (var i in or) {
  25090. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25091. var and = ori.split("&&");
  25092. if (and.length > 1) {
  25093. for (var j = 0; j < and.length; ++j) {
  25094. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25095. if (andj !== "true" && andj !== "false") {
  25096. if (andj[0] === "!") {
  25097. result = !evaluateCallback(andj.substring(1));
  25098. }
  25099. else {
  25100. result = evaluateCallback(andj);
  25101. }
  25102. }
  25103. else {
  25104. result = andj === "true" ? true : false;
  25105. }
  25106. if (!result) {
  25107. ori = "false";
  25108. break;
  25109. }
  25110. }
  25111. }
  25112. if (result || ori === "true") {
  25113. result = true;
  25114. break;
  25115. }
  25116. // result equals false (or undefined)
  25117. if (ori !== "true" && ori !== "false") {
  25118. if (ori[0] === "!") {
  25119. result = !evaluateCallback(ori.substring(1));
  25120. }
  25121. else {
  25122. result = evaluateCallback(ori);
  25123. }
  25124. }
  25125. else {
  25126. result = ori === "true" ? true : false;
  25127. }
  25128. }
  25129. // the whole parenthesis scope is replaced by 'true' or 'false'
  25130. return result ? "true" : "false";
  25131. };
  25132. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25133. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25134. // remove whitespaces
  25135. r = r.replace(/[\s]/g, function () { return ""; });
  25136. return r.length % 2 ? "!" : "";
  25137. });
  25138. booleanString = booleanString.trim();
  25139. if (booleanString === "!true") {
  25140. booleanString = "false";
  25141. }
  25142. else if (booleanString === "!false") {
  25143. booleanString = "true";
  25144. }
  25145. return booleanString;
  25146. };
  25147. return AndOrNotEvaluator;
  25148. })();
  25149. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25150. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25151. })(BABYLON || (BABYLON = {}));
  25152. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  25153. var BABYLON;
  25154. (function (BABYLON) {
  25155. var PostProcessRenderPass = (function () {
  25156. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25157. this._enabled = true;
  25158. this._refCount = 0;
  25159. this._name = name;
  25160. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25161. this.setRenderList(renderList);
  25162. this._renderTexture.onBeforeRender = beforeRender;
  25163. this._renderTexture.onAfterRender = afterRender;
  25164. this._scene = scene;
  25165. this._renderList = renderList;
  25166. }
  25167. // private
  25168. PostProcessRenderPass.prototype._incRefCount = function () {
  25169. if (this._refCount === 0) {
  25170. this._scene.customRenderTargets.push(this._renderTexture);
  25171. }
  25172. return ++this._refCount;
  25173. };
  25174. PostProcessRenderPass.prototype._decRefCount = function () {
  25175. this._refCount--;
  25176. if (this._refCount <= 0) {
  25177. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25178. }
  25179. return this._refCount;
  25180. };
  25181. PostProcessRenderPass.prototype._update = function () {
  25182. this.setRenderList(this._renderList);
  25183. };
  25184. // public
  25185. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25186. this._renderTexture.renderList = renderList;
  25187. };
  25188. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25189. return this._renderTexture;
  25190. };
  25191. return PostProcessRenderPass;
  25192. })();
  25193. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25194. })(BABYLON || (BABYLON = {}));
  25195. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  25196. var BABYLON;
  25197. (function (BABYLON) {
  25198. var PostProcessRenderEffect = (function () {
  25199. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25200. this._engine = engine;
  25201. this._name = name;
  25202. this._singleInstance = singleInstance || true;
  25203. this._getPostProcess = getPostProcess;
  25204. this._cameras = [];
  25205. this._indicesForCamera = [];
  25206. this._postProcesses = {};
  25207. this._renderPasses = {};
  25208. this._renderEffectAsPasses = {};
  25209. }
  25210. PostProcessRenderEffect.prototype._update = function () {
  25211. for (var renderPassName in this._renderPasses) {
  25212. this._renderPasses[renderPassName]._update();
  25213. }
  25214. };
  25215. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25216. this._renderPasses[renderPass._name] = renderPass;
  25217. this._linkParameters();
  25218. };
  25219. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25220. delete this._renderPasses[renderPass._name];
  25221. this._linkParameters();
  25222. };
  25223. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25224. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25225. this._linkParameters();
  25226. };
  25227. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25228. for (var renderPassName in this._renderPasses) {
  25229. if (renderPassName === passName) {
  25230. return this._renderPasses[passName];
  25231. }
  25232. }
  25233. };
  25234. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25235. this._renderPasses = {};
  25236. this._linkParameters();
  25237. };
  25238. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25239. var cameraKey;
  25240. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25241. for (var i = 0; i < _cam.length; i++) {
  25242. var camera = _cam[i];
  25243. var cameraName = camera.name;
  25244. if (this._singleInstance) {
  25245. cameraKey = 0;
  25246. }
  25247. else {
  25248. cameraKey = cameraName;
  25249. }
  25250. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25251. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25252. if (!this._indicesForCamera[cameraName]) {
  25253. this._indicesForCamera[cameraName] = [];
  25254. }
  25255. this._indicesForCamera[cameraName].push(index);
  25256. if (this._cameras.indexOf(camera) === -1) {
  25257. this._cameras[cameraName] = camera;
  25258. }
  25259. for (var passName in this._renderPasses) {
  25260. this._renderPasses[passName]._incRefCount();
  25261. }
  25262. }
  25263. this._linkParameters();
  25264. };
  25265. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25266. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25267. for (var i = 0; i < _cam.length; i++) {
  25268. var camera = _cam[i];
  25269. var cameraName = camera.name;
  25270. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25271. var index = this._cameras.indexOf(cameraName);
  25272. this._indicesForCamera.splice(index, 1);
  25273. this._cameras.splice(index, 1);
  25274. for (var passName in this._renderPasses) {
  25275. this._renderPasses[passName]._decRefCount();
  25276. }
  25277. }
  25278. };
  25279. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25280. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25281. for (var i = 0; i < _cam.length; i++) {
  25282. var camera = _cam[i];
  25283. var cameraName = camera.name;
  25284. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25285. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25286. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25287. }
  25288. }
  25289. for (var passName in this._renderPasses) {
  25290. this._renderPasses[passName]._incRefCount();
  25291. }
  25292. }
  25293. };
  25294. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25295. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25296. for (var i = 0; i < _cam.length; i++) {
  25297. var camera = _cam[i];
  25298. var cameraName = camera.Name;
  25299. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25300. for (var passName in this._renderPasses) {
  25301. this._renderPasses[passName]._decRefCount();
  25302. }
  25303. }
  25304. };
  25305. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25306. if (this._singleInstance) {
  25307. return this._postProcesses[0];
  25308. }
  25309. else {
  25310. return this._postProcesses[camera.name];
  25311. }
  25312. };
  25313. PostProcessRenderEffect.prototype._linkParameters = function () {
  25314. var _this = this;
  25315. for (var index in this._postProcesses) {
  25316. if (this.applyParameters) {
  25317. this.applyParameters(this._postProcesses[index]);
  25318. }
  25319. this._postProcesses[index].onBeforeRender = function (effect) {
  25320. _this._linkTextures(effect);
  25321. };
  25322. }
  25323. };
  25324. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25325. for (var renderPassName in this._renderPasses) {
  25326. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25327. }
  25328. for (var renderEffectName in this._renderEffectAsPasses) {
  25329. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25330. }
  25331. };
  25332. return PostProcessRenderEffect;
  25333. })();
  25334. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25335. })(BABYLON || (BABYLON = {}));
  25336. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  25337. var BABYLON;
  25338. (function (BABYLON) {
  25339. var PostProcessRenderPipeline = (function () {
  25340. function PostProcessRenderPipeline(engine, name) {
  25341. this._engine = engine;
  25342. this._name = name;
  25343. this._renderEffects = {};
  25344. this._renderEffectsForIsolatedPass = {};
  25345. this._cameras = [];
  25346. }
  25347. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25348. this._renderEffects[renderEffect._name] = renderEffect;
  25349. };
  25350. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25351. var renderEffects = this._renderEffects[renderEffectName];
  25352. if (!renderEffects) {
  25353. return;
  25354. }
  25355. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25356. };
  25357. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25358. var renderEffects = this._renderEffects[renderEffectName];
  25359. if (!renderEffects) {
  25360. return;
  25361. }
  25362. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25363. };
  25364. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25365. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25366. var indicesToDelete = [];
  25367. for (var i = 0; i < _cam.length; i++) {
  25368. var camera = _cam[i];
  25369. var cameraName = camera.name;
  25370. if (this._cameras.indexOf(camera) === -1) {
  25371. this._cameras[cameraName] = camera;
  25372. }
  25373. else if (unique) {
  25374. indicesToDelete.push(i);
  25375. }
  25376. }
  25377. for (var i = 0; i < indicesToDelete.length; i++) {
  25378. cameras.splice(indicesToDelete[i], 1);
  25379. }
  25380. for (var renderEffectName in this._renderEffects) {
  25381. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25382. }
  25383. };
  25384. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25385. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25386. for (var renderEffectName in this._renderEffects) {
  25387. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25388. }
  25389. for (var i = 0; i < _cam.length; i++) {
  25390. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25391. }
  25392. };
  25393. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25394. var _this = this;
  25395. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25396. var pass = null;
  25397. for (var renderEffectName in this._renderEffects) {
  25398. pass = this._renderEffects[renderEffectName].getPass(passName);
  25399. if (pass != null) {
  25400. break;
  25401. }
  25402. }
  25403. if (pass === null) {
  25404. return;
  25405. }
  25406. for (var renderEffectName in this._renderEffects) {
  25407. this._renderEffects[renderEffectName]._disable(_cam);
  25408. }
  25409. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25410. for (var i = 0; i < _cam.length; i++) {
  25411. var camera = _cam[i];
  25412. var cameraName = camera.name;
  25413. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  25414. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25415. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25416. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25417. }
  25418. };
  25419. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25420. var _this = this;
  25421. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25422. for (var i = 0; i < _cam.length; i++) {
  25423. var camera = _cam[i];
  25424. var cameraName = camera.name;
  25425. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  25426. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25427. }
  25428. for (var renderEffectName in this._renderEffects) {
  25429. this._renderEffects[renderEffectName]._enable(_cam);
  25430. }
  25431. };
  25432. PostProcessRenderPipeline.prototype._update = function () {
  25433. for (var renderEffectName in this._renderEffects) {
  25434. this._renderEffects[renderEffectName]._update();
  25435. }
  25436. for (var i = 0; i < this._cameras.length; i++) {
  25437. var cameraName = this._cameras[i].name;
  25438. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25439. this._renderEffectsForIsolatedPass[cameraName]._update();
  25440. }
  25441. }
  25442. };
  25443. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25444. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25445. return PostProcessRenderPipeline;
  25446. })();
  25447. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25448. })(BABYLON || (BABYLON = {}));
  25449. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  25450. var BABYLON;
  25451. (function (BABYLON) {
  25452. var PostProcessRenderPipelineManager = (function () {
  25453. function PostProcessRenderPipelineManager() {
  25454. this._renderPipelines = {};
  25455. }
  25456. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25457. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25458. };
  25459. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25460. var renderPipeline = this._renderPipelines[renderPipelineName];
  25461. if (!renderPipeline) {
  25462. return;
  25463. }
  25464. renderPipeline._attachCameras(cameras, unique);
  25465. };
  25466. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25467. var renderPipeline = this._renderPipelines[renderPipelineName];
  25468. if (!renderPipeline) {
  25469. return;
  25470. }
  25471. renderPipeline._detachCameras(cameras);
  25472. };
  25473. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25474. var renderPipeline = this._renderPipelines[renderPipelineName];
  25475. if (!renderPipeline) {
  25476. return;
  25477. }
  25478. renderPipeline._enableEffect(renderEffectName, cameras);
  25479. };
  25480. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25481. var renderPipeline = this._renderPipelines[renderPipelineName];
  25482. if (!renderPipeline) {
  25483. return;
  25484. }
  25485. renderPipeline._disableEffect(renderEffectName, cameras);
  25486. };
  25487. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25488. var renderPipeline = this._renderPipelines[renderPipelineName];
  25489. if (!renderPipeline) {
  25490. return;
  25491. }
  25492. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25493. };
  25494. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25495. var renderPipeline = this._renderPipelines[renderPipelineName];
  25496. if (!renderPipeline) {
  25497. return;
  25498. }
  25499. renderPipeline._disableDisplayOnlyPass(cameras);
  25500. };
  25501. PostProcessRenderPipelineManager.prototype.update = function () {
  25502. for (var renderPipelineName in this._renderPipelines) {
  25503. this._renderPipelines[renderPipelineName]._update();
  25504. }
  25505. };
  25506. return PostProcessRenderPipelineManager;
  25507. })();
  25508. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25509. })(BABYLON || (BABYLON = {}));
  25510. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  25511. var __extends = this.__extends || function (d, b) {
  25512. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25513. function __() { this.constructor = d; }
  25514. __.prototype = b.prototype;
  25515. d.prototype = new __();
  25516. };
  25517. var BABYLON;
  25518. (function (BABYLON) {
  25519. var DisplayPassPostProcess = (function (_super) {
  25520. __extends(DisplayPassPostProcess, _super);
  25521. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25522. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  25523. }
  25524. return DisplayPassPostProcess;
  25525. })(BABYLON.PostProcess);
  25526. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  25527. })(BABYLON || (BABYLON = {}));
  25528. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  25529. var BABYLON;
  25530. (function (BABYLON) {
  25531. var BoundingBoxRenderer = (function () {
  25532. function BoundingBoxRenderer(scene) {
  25533. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25534. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25535. this.showBackLines = true;
  25536. this.renderList = new BABYLON.SmartArray(32);
  25537. this._scene = scene;
  25538. }
  25539. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25540. if (this._colorShader) {
  25541. return;
  25542. }
  25543. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25544. attributes: ["position"],
  25545. uniforms: ["worldViewProjection", "color"]
  25546. });
  25547. var engine = this._scene.getEngine();
  25548. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25549. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25550. 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]);
  25551. };
  25552. BoundingBoxRenderer.prototype.reset = function () {
  25553. this.renderList.reset();
  25554. };
  25555. BoundingBoxRenderer.prototype.render = function () {
  25556. if (this.renderList.length === 0) {
  25557. return;
  25558. }
  25559. this._prepareRessources();
  25560. if (!this._colorShader.isReady()) {
  25561. return;
  25562. }
  25563. var engine = this._scene.getEngine();
  25564. engine.setDepthWrite(false);
  25565. this._colorShader._preBind();
  25566. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25567. var boundingBox = this.renderList.data[boundingBoxIndex];
  25568. var min = boundingBox.minimum;
  25569. var max = boundingBox.maximum;
  25570. var diff = max.subtract(min);
  25571. var median = min.add(diff.scale(0.5));
  25572. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25573. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25574. .multiply(boundingBox.getWorldMatrix());
  25575. // VBOs
  25576. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25577. if (this.showBackLines) {
  25578. // Back
  25579. engine.setDepthFunctionToGreaterOrEqual();
  25580. this._scene.resetCachedMaterial();
  25581. this._colorShader.setColor4("color", this.backColor.toColor4());
  25582. this._colorShader.bind(worldMatrix);
  25583. // Draw order
  25584. engine.draw(false, 0, 24);
  25585. }
  25586. // Front
  25587. engine.setDepthFunctionToLess();
  25588. this._scene.resetCachedMaterial();
  25589. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25590. this._colorShader.bind(worldMatrix);
  25591. // Draw order
  25592. engine.draw(false, 0, 24);
  25593. }
  25594. this._colorShader.unbind();
  25595. engine.setDepthFunctionToLessOrEqual();
  25596. engine.setDepthWrite(true);
  25597. };
  25598. BoundingBoxRenderer.prototype.dispose = function () {
  25599. if (!this._colorShader) {
  25600. return;
  25601. }
  25602. this._colorShader.dispose();
  25603. this._vb.dispose();
  25604. this._scene.getEngine()._releaseBuffer(this._ib);
  25605. };
  25606. return BoundingBoxRenderer;
  25607. })();
  25608. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25609. })(BABYLON || (BABYLON = {}));
  25610. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  25611. var __extends = this.__extends || function (d, b) {
  25612. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25613. function __() { this.constructor = d; }
  25614. __.prototype = b.prototype;
  25615. d.prototype = new __();
  25616. };
  25617. var BABYLON;
  25618. (function (BABYLON) {
  25619. var Condition = (function () {
  25620. function Condition(actionManager) {
  25621. this._actionManager = actionManager;
  25622. }
  25623. Condition.prototype.isValid = function () {
  25624. return true;
  25625. };
  25626. Condition.prototype._getProperty = function (propertyPath) {
  25627. return this._actionManager._getProperty(propertyPath);
  25628. };
  25629. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25630. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25631. };
  25632. return Condition;
  25633. })();
  25634. BABYLON.Condition = Condition;
  25635. var ValueCondition = (function (_super) {
  25636. __extends(ValueCondition, _super);
  25637. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25638. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25639. _super.call(this, actionManager);
  25640. this.propertyPath = propertyPath;
  25641. this.value = value;
  25642. this.operator = operator;
  25643. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25644. this._property = this._getProperty(this.propertyPath);
  25645. }
  25646. Object.defineProperty(ValueCondition, "IsEqual", {
  25647. get: function () {
  25648. return ValueCondition._IsEqual;
  25649. },
  25650. enumerable: true,
  25651. configurable: true
  25652. });
  25653. Object.defineProperty(ValueCondition, "IsDifferent", {
  25654. get: function () {
  25655. return ValueCondition._IsDifferent;
  25656. },
  25657. enumerable: true,
  25658. configurable: true
  25659. });
  25660. Object.defineProperty(ValueCondition, "IsGreater", {
  25661. get: function () {
  25662. return ValueCondition._IsGreater;
  25663. },
  25664. enumerable: true,
  25665. configurable: true
  25666. });
  25667. Object.defineProperty(ValueCondition, "IsLesser", {
  25668. get: function () {
  25669. return ValueCondition._IsLesser;
  25670. },
  25671. enumerable: true,
  25672. configurable: true
  25673. });
  25674. // Methods
  25675. ValueCondition.prototype.isValid = function () {
  25676. switch (this.operator) {
  25677. case ValueCondition.IsGreater:
  25678. return this._target[this._property] > this.value;
  25679. case ValueCondition.IsLesser:
  25680. return this._target[this._property] < this.value;
  25681. case ValueCondition.IsEqual:
  25682. case ValueCondition.IsDifferent:
  25683. var check;
  25684. if (this.value.equals) {
  25685. check = this.value.equals(this._target[this._property]);
  25686. }
  25687. else {
  25688. check = this.value === this._target[this._property];
  25689. }
  25690. return this.operator === ValueCondition.IsEqual ? check : !check;
  25691. }
  25692. return false;
  25693. };
  25694. // Statics
  25695. ValueCondition._IsEqual = 0;
  25696. ValueCondition._IsDifferent = 1;
  25697. ValueCondition._IsGreater = 2;
  25698. ValueCondition._IsLesser = 3;
  25699. return ValueCondition;
  25700. })(Condition);
  25701. BABYLON.ValueCondition = ValueCondition;
  25702. var PredicateCondition = (function (_super) {
  25703. __extends(PredicateCondition, _super);
  25704. function PredicateCondition(actionManager, predicate) {
  25705. _super.call(this, actionManager);
  25706. this.predicate = predicate;
  25707. }
  25708. PredicateCondition.prototype.isValid = function () {
  25709. return this.predicate();
  25710. };
  25711. return PredicateCondition;
  25712. })(Condition);
  25713. BABYLON.PredicateCondition = PredicateCondition;
  25714. var StateCondition = (function (_super) {
  25715. __extends(StateCondition, _super);
  25716. function StateCondition(actionManager, target, value) {
  25717. _super.call(this, actionManager);
  25718. this.value = value;
  25719. this._target = target;
  25720. }
  25721. // Methods
  25722. StateCondition.prototype.isValid = function () {
  25723. return this._target.state === this.value;
  25724. };
  25725. return StateCondition;
  25726. })(Condition);
  25727. BABYLON.StateCondition = StateCondition;
  25728. })(BABYLON || (BABYLON = {}));
  25729. //# sourceMappingURL=babylon.condition.js.map
  25730. var BABYLON;
  25731. (function (BABYLON) {
  25732. var Action = (function () {
  25733. function Action(triggerOptions, condition) {
  25734. this.triggerOptions = triggerOptions;
  25735. if (triggerOptions.parameter) {
  25736. this.trigger = triggerOptions.trigger;
  25737. this._triggerParameter = triggerOptions.parameter;
  25738. }
  25739. else {
  25740. this.trigger = triggerOptions;
  25741. }
  25742. this._nextActiveAction = this;
  25743. this._condition = condition;
  25744. }
  25745. // Methods
  25746. Action.prototype._prepare = function () {
  25747. };
  25748. Action.prototype.getTriggerParameter = function () {
  25749. return this._triggerParameter;
  25750. };
  25751. Action.prototype._executeCurrent = function (evt) {
  25752. if (this._nextActiveAction._condition) {
  25753. var condition = this._nextActiveAction._condition;
  25754. var currentRenderId = this._actionManager.getScene().getRenderId();
  25755. // We cache the current evaluation for the current frame
  25756. if (condition._evaluationId === currentRenderId) {
  25757. if (!condition._currentResult) {
  25758. return;
  25759. }
  25760. }
  25761. else {
  25762. condition._evaluationId = currentRenderId;
  25763. if (!condition.isValid()) {
  25764. condition._currentResult = false;
  25765. return;
  25766. }
  25767. condition._currentResult = true;
  25768. }
  25769. }
  25770. this._nextActiveAction.execute(evt);
  25771. if (this._nextActiveAction._child) {
  25772. if (!this._nextActiveAction._child._actionManager) {
  25773. this._nextActiveAction._child._actionManager = this._actionManager;
  25774. }
  25775. this._nextActiveAction = this._nextActiveAction._child;
  25776. }
  25777. else {
  25778. this._nextActiveAction = this;
  25779. }
  25780. };
  25781. Action.prototype.execute = function (evt) {
  25782. };
  25783. Action.prototype.then = function (action) {
  25784. this._child = action;
  25785. action._actionManager = this._actionManager;
  25786. action._prepare();
  25787. return action;
  25788. };
  25789. Action.prototype._getProperty = function (propertyPath) {
  25790. return this._actionManager._getProperty(propertyPath);
  25791. };
  25792. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25793. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25794. };
  25795. return Action;
  25796. })();
  25797. BABYLON.Action = Action;
  25798. })(BABYLON || (BABYLON = {}));
  25799. //# sourceMappingURL=babylon.action.js.map
  25800. var BABYLON;
  25801. (function (BABYLON) {
  25802. /**
  25803. * ActionEvent is the event beint sent when an action is triggered.
  25804. */
  25805. var ActionEvent = (function () {
  25806. /**
  25807. * @constructor
  25808. * @param source The mesh that triggered the action.
  25809. * @param pointerX the X mouse cursor position at the time of the event
  25810. * @param pointerY the Y mouse cursor position at the time of the event
  25811. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25812. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25813. */
  25814. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  25815. this.source = source;
  25816. this.pointerX = pointerX;
  25817. this.pointerY = pointerY;
  25818. this.meshUnderPointer = meshUnderPointer;
  25819. this.sourceEvent = sourceEvent;
  25820. }
  25821. /**
  25822. * Helper function to auto-create an ActionEvent from a source mesh.
  25823. * @param source the source mesh that triggered the event
  25824. * @param evt {Event} The original (browser) event
  25825. */
  25826. ActionEvent.CreateNew = function (source, evt) {
  25827. var scene = source.getScene();
  25828. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25829. };
  25830. /**
  25831. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25832. * @param scene the scene where the event occurred
  25833. * @param evt {Event} The original (browser) event
  25834. */
  25835. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25836. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25837. };
  25838. return ActionEvent;
  25839. })();
  25840. BABYLON.ActionEvent = ActionEvent;
  25841. /**
  25842. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25843. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25844. */
  25845. var ActionManager = (function () {
  25846. function ActionManager(scene) {
  25847. // Members
  25848. this.actions = new Array();
  25849. this._scene = scene;
  25850. scene._actionManagers.push(this);
  25851. }
  25852. Object.defineProperty(ActionManager, "NothingTrigger", {
  25853. get: function () {
  25854. return ActionManager._NothingTrigger;
  25855. },
  25856. enumerable: true,
  25857. configurable: true
  25858. });
  25859. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25860. get: function () {
  25861. return ActionManager._OnPickTrigger;
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25867. get: function () {
  25868. return ActionManager._OnLeftPickTrigger;
  25869. },
  25870. enumerable: true,
  25871. configurable: true
  25872. });
  25873. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25874. get: function () {
  25875. return ActionManager._OnRightPickTrigger;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25881. get: function () {
  25882. return ActionManager._OnCenterPickTrigger;
  25883. },
  25884. enumerable: true,
  25885. configurable: true
  25886. });
  25887. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25888. get: function () {
  25889. return ActionManager._OnPointerOverTrigger;
  25890. },
  25891. enumerable: true,
  25892. configurable: true
  25893. });
  25894. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25895. get: function () {
  25896. return ActionManager._OnPointerOutTrigger;
  25897. },
  25898. enumerable: true,
  25899. configurable: true
  25900. });
  25901. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25902. get: function () {
  25903. return ActionManager._OnEveryFrameTrigger;
  25904. },
  25905. enumerable: true,
  25906. configurable: true
  25907. });
  25908. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25909. get: function () {
  25910. return ActionManager._OnIntersectionEnterTrigger;
  25911. },
  25912. enumerable: true,
  25913. configurable: true
  25914. });
  25915. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25916. get: function () {
  25917. return ActionManager._OnIntersectionExitTrigger;
  25918. },
  25919. enumerable: true,
  25920. configurable: true
  25921. });
  25922. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25923. get: function () {
  25924. return ActionManager._OnKeyDownTrigger;
  25925. },
  25926. enumerable: true,
  25927. configurable: true
  25928. });
  25929. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25930. get: function () {
  25931. return ActionManager._OnKeyUpTrigger;
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25937. get: function () {
  25938. return ActionManager._OnPickUpTrigger;
  25939. },
  25940. enumerable: true,
  25941. configurable: true
  25942. });
  25943. // Methods
  25944. ActionManager.prototype.dispose = function () {
  25945. var index = this._scene._actionManagers.indexOf(this);
  25946. if (index > -1) {
  25947. this._scene._actionManagers.splice(index, 1);
  25948. }
  25949. };
  25950. ActionManager.prototype.getScene = function () {
  25951. return this._scene;
  25952. };
  25953. /**
  25954. * Does this action manager handles actions of any of the given triggers
  25955. * @param {number[]} triggers - the triggers to be tested
  25956. * @return {boolean} whether one (or more) of the triggers is handeled
  25957. */
  25958. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25959. for (var index = 0; index < this.actions.length; index++) {
  25960. var action = this.actions[index];
  25961. if (triggers.indexOf(action.trigger) > -1) {
  25962. return true;
  25963. }
  25964. }
  25965. return false;
  25966. };
  25967. /**
  25968. * Does this action manager handles actions of a given trigger
  25969. * @param {number} trigger - the trigger to be tested
  25970. * @return {boolean} whether the trigger is handeled
  25971. */
  25972. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25973. for (var index = 0; index < this.actions.length; index++) {
  25974. var action = this.actions[index];
  25975. if (action.trigger === trigger) {
  25976. return true;
  25977. }
  25978. }
  25979. return false;
  25980. };
  25981. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25982. /**
  25983. * Does this action manager has pointer triggers
  25984. * @return {boolean} whether or not it has pointer triggers
  25985. */
  25986. get: function () {
  25987. for (var index = 0; index < this.actions.length; index++) {
  25988. var action = this.actions[index];
  25989. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25990. return true;
  25991. }
  25992. if (action.trigger == ActionManager._OnPickUpTrigger) {
  25993. return true;
  25994. }
  25995. }
  25996. return false;
  25997. },
  25998. enumerable: true,
  25999. configurable: true
  26000. });
  26001. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26002. /**
  26003. * Does this action manager has pick triggers
  26004. * @return {boolean} whether or not it has pick triggers
  26005. */
  26006. get: function () {
  26007. for (var index = 0; index < this.actions.length; index++) {
  26008. var action = this.actions[index];
  26009. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26010. return true;
  26011. }
  26012. }
  26013. return false;
  26014. },
  26015. enumerable: true,
  26016. configurable: true
  26017. });
  26018. /**
  26019. * Registers an action to this action manager
  26020. * @param {BABYLON.Action} action - the action to be registered
  26021. * @return {BABYLON.Action} the action amended (prepared) after registration
  26022. */
  26023. ActionManager.prototype.registerAction = function (action) {
  26024. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26025. if (this.getScene().actionManager !== this) {
  26026. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26027. return null;
  26028. }
  26029. }
  26030. this.actions.push(action);
  26031. action._actionManager = this;
  26032. action._prepare();
  26033. return action;
  26034. };
  26035. /**
  26036. * Process a specific trigger
  26037. * @param {number} trigger - the trigger to process
  26038. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26039. */
  26040. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26041. for (var index = 0; index < this.actions.length; index++) {
  26042. var action = this.actions[index];
  26043. if (action.trigger === trigger) {
  26044. if (trigger === ActionManager.OnKeyUpTrigger
  26045. || trigger === ActionManager.OnKeyDownTrigger) {
  26046. var parameter = action.getTriggerParameter();
  26047. if (parameter) {
  26048. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26049. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26050. if (actualkey !== parameter.toLowerCase()) {
  26051. continue;
  26052. }
  26053. }
  26054. }
  26055. action._executeCurrent(evt);
  26056. }
  26057. }
  26058. };
  26059. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26060. var properties = propertyPath.split(".");
  26061. for (var index = 0; index < properties.length - 1; index++) {
  26062. target = target[properties[index]];
  26063. }
  26064. return target;
  26065. };
  26066. ActionManager.prototype._getProperty = function (propertyPath) {
  26067. var properties = propertyPath.split(".");
  26068. return properties[properties.length - 1];
  26069. };
  26070. // Statics
  26071. ActionManager._NothingTrigger = 0;
  26072. ActionManager._OnPickTrigger = 1;
  26073. ActionManager._OnLeftPickTrigger = 2;
  26074. ActionManager._OnRightPickTrigger = 3;
  26075. ActionManager._OnCenterPickTrigger = 4;
  26076. ActionManager._OnPointerOverTrigger = 5;
  26077. ActionManager._OnPointerOutTrigger = 6;
  26078. ActionManager._OnEveryFrameTrigger = 7;
  26079. ActionManager._OnIntersectionEnterTrigger = 8;
  26080. ActionManager._OnIntersectionExitTrigger = 9;
  26081. ActionManager._OnKeyDownTrigger = 10;
  26082. ActionManager._OnKeyUpTrigger = 11;
  26083. ActionManager._OnPickUpTrigger = 12;
  26084. return ActionManager;
  26085. })();
  26086. BABYLON.ActionManager = ActionManager;
  26087. })(BABYLON || (BABYLON = {}));
  26088. //# sourceMappingURL=babylon.actionManager.js.map
  26089. var __extends = this.__extends || function (d, b) {
  26090. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26091. function __() { this.constructor = d; }
  26092. __.prototype = b.prototype;
  26093. d.prototype = new __();
  26094. };
  26095. var BABYLON;
  26096. (function (BABYLON) {
  26097. var InterpolateValueAction = (function (_super) {
  26098. __extends(InterpolateValueAction, _super);
  26099. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26100. if (duration === void 0) { duration = 1000; }
  26101. _super.call(this, triggerOptions, condition);
  26102. this.propertyPath = propertyPath;
  26103. this.value = value;
  26104. this.duration = duration;
  26105. this.stopOtherAnimations = stopOtherAnimations;
  26106. this._target = target;
  26107. }
  26108. InterpolateValueAction.prototype._prepare = function () {
  26109. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26110. this._property = this._getProperty(this.propertyPath);
  26111. };
  26112. InterpolateValueAction.prototype.execute = function () {
  26113. var scene = this._actionManager.getScene();
  26114. var keys = [
  26115. {
  26116. frame: 0,
  26117. value: this._target[this._property]
  26118. }, {
  26119. frame: 100,
  26120. value: this.value
  26121. }
  26122. ];
  26123. var dataType;
  26124. if (typeof this.value === "number") {
  26125. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26126. }
  26127. else if (this.value instanceof BABYLON.Color3) {
  26128. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26129. }
  26130. else if (this.value instanceof BABYLON.Vector3) {
  26131. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26132. }
  26133. else if (this.value instanceof BABYLON.Matrix) {
  26134. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26135. }
  26136. else if (this.value instanceof BABYLON.Quaternion) {
  26137. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26138. }
  26139. else {
  26140. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26141. return;
  26142. }
  26143. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26144. animation.setKeys(keys);
  26145. if (this.stopOtherAnimations) {
  26146. scene.stopAnimation(this._target);
  26147. }
  26148. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  26149. };
  26150. return InterpolateValueAction;
  26151. })(BABYLON.Action);
  26152. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26153. })(BABYLON || (BABYLON = {}));
  26154. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  26155. var __extends = this.__extends || function (d, b) {
  26156. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26157. function __() { this.constructor = d; }
  26158. __.prototype = b.prototype;
  26159. d.prototype = new __();
  26160. };
  26161. var BABYLON;
  26162. (function (BABYLON) {
  26163. var SwitchBooleanAction = (function (_super) {
  26164. __extends(SwitchBooleanAction, _super);
  26165. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26166. _super.call(this, triggerOptions, condition);
  26167. this.propertyPath = propertyPath;
  26168. this._target = target;
  26169. }
  26170. SwitchBooleanAction.prototype._prepare = function () {
  26171. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26172. this._property = this._getProperty(this.propertyPath);
  26173. };
  26174. SwitchBooleanAction.prototype.execute = function () {
  26175. this._target[this._property] = !this._target[this._property];
  26176. };
  26177. return SwitchBooleanAction;
  26178. })(BABYLON.Action);
  26179. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26180. var SetStateAction = (function (_super) {
  26181. __extends(SetStateAction, _super);
  26182. function SetStateAction(triggerOptions, target, value, condition) {
  26183. _super.call(this, triggerOptions, condition);
  26184. this.value = value;
  26185. this._target = target;
  26186. }
  26187. SetStateAction.prototype.execute = function () {
  26188. this._target.state = this.value;
  26189. };
  26190. return SetStateAction;
  26191. })(BABYLON.Action);
  26192. BABYLON.SetStateAction = SetStateAction;
  26193. var SetValueAction = (function (_super) {
  26194. __extends(SetValueAction, _super);
  26195. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26196. _super.call(this, triggerOptions, condition);
  26197. this.propertyPath = propertyPath;
  26198. this.value = value;
  26199. this._target = target;
  26200. }
  26201. SetValueAction.prototype._prepare = function () {
  26202. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26203. this._property = this._getProperty(this.propertyPath);
  26204. };
  26205. SetValueAction.prototype.execute = function () {
  26206. this._target[this._property] = this.value;
  26207. };
  26208. return SetValueAction;
  26209. })(BABYLON.Action);
  26210. BABYLON.SetValueAction = SetValueAction;
  26211. var IncrementValueAction = (function (_super) {
  26212. __extends(IncrementValueAction, _super);
  26213. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26214. _super.call(this, triggerOptions, condition);
  26215. this.propertyPath = propertyPath;
  26216. this.value = value;
  26217. this._target = target;
  26218. }
  26219. IncrementValueAction.prototype._prepare = function () {
  26220. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26221. this._property = this._getProperty(this.propertyPath);
  26222. if (typeof this._target[this._property] !== "number") {
  26223. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26224. }
  26225. };
  26226. IncrementValueAction.prototype.execute = function () {
  26227. this._target[this._property] += this.value;
  26228. };
  26229. return IncrementValueAction;
  26230. })(BABYLON.Action);
  26231. BABYLON.IncrementValueAction = IncrementValueAction;
  26232. var PlayAnimationAction = (function (_super) {
  26233. __extends(PlayAnimationAction, _super);
  26234. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26235. _super.call(this, triggerOptions, condition);
  26236. this.from = from;
  26237. this.to = to;
  26238. this.loop = loop;
  26239. this._target = target;
  26240. }
  26241. PlayAnimationAction.prototype._prepare = function () {
  26242. };
  26243. PlayAnimationAction.prototype.execute = function () {
  26244. var scene = this._actionManager.getScene();
  26245. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26246. };
  26247. return PlayAnimationAction;
  26248. })(BABYLON.Action);
  26249. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26250. var StopAnimationAction = (function (_super) {
  26251. __extends(StopAnimationAction, _super);
  26252. function StopAnimationAction(triggerOptions, target, condition) {
  26253. _super.call(this, triggerOptions, condition);
  26254. this._target = target;
  26255. }
  26256. StopAnimationAction.prototype._prepare = function () {
  26257. };
  26258. StopAnimationAction.prototype.execute = function () {
  26259. var scene = this._actionManager.getScene();
  26260. scene.stopAnimation(this._target);
  26261. };
  26262. return StopAnimationAction;
  26263. })(BABYLON.Action);
  26264. BABYLON.StopAnimationAction = StopAnimationAction;
  26265. var DoNothingAction = (function (_super) {
  26266. __extends(DoNothingAction, _super);
  26267. function DoNothingAction(triggerOptions, condition) {
  26268. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26269. _super.call(this, triggerOptions, condition);
  26270. }
  26271. DoNothingAction.prototype.execute = function () {
  26272. };
  26273. return DoNothingAction;
  26274. })(BABYLON.Action);
  26275. BABYLON.DoNothingAction = DoNothingAction;
  26276. var CombineAction = (function (_super) {
  26277. __extends(CombineAction, _super);
  26278. function CombineAction(triggerOptions, children, condition) {
  26279. _super.call(this, triggerOptions, condition);
  26280. this.children = children;
  26281. }
  26282. CombineAction.prototype._prepare = function () {
  26283. for (var index = 0; index < this.children.length; index++) {
  26284. this.children[index]._actionManager = this._actionManager;
  26285. this.children[index]._prepare();
  26286. }
  26287. };
  26288. CombineAction.prototype.execute = function (evt) {
  26289. for (var index = 0; index < this.children.length; index++) {
  26290. this.children[index].execute(evt);
  26291. }
  26292. };
  26293. return CombineAction;
  26294. })(BABYLON.Action);
  26295. BABYLON.CombineAction = CombineAction;
  26296. var ExecuteCodeAction = (function (_super) {
  26297. __extends(ExecuteCodeAction, _super);
  26298. function ExecuteCodeAction(triggerOptions, func, condition) {
  26299. _super.call(this, triggerOptions, condition);
  26300. this.func = func;
  26301. }
  26302. ExecuteCodeAction.prototype.execute = function (evt) {
  26303. this.func(evt);
  26304. };
  26305. return ExecuteCodeAction;
  26306. })(BABYLON.Action);
  26307. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26308. var SetParentAction = (function (_super) {
  26309. __extends(SetParentAction, _super);
  26310. function SetParentAction(triggerOptions, target, parent, condition) {
  26311. _super.call(this, triggerOptions, condition);
  26312. this._target = target;
  26313. this._parent = parent;
  26314. }
  26315. SetParentAction.prototype._prepare = function () {
  26316. };
  26317. SetParentAction.prototype.execute = function () {
  26318. if (this._target.parent === this._parent) {
  26319. return;
  26320. }
  26321. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26322. invertParentWorldMatrix.invert();
  26323. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26324. this._target.parent = this._parent;
  26325. };
  26326. return SetParentAction;
  26327. })(BABYLON.Action);
  26328. BABYLON.SetParentAction = SetParentAction;
  26329. var PlaySoundAction = (function (_super) {
  26330. __extends(PlaySoundAction, _super);
  26331. function PlaySoundAction(triggerOptions, sound, condition) {
  26332. _super.call(this, triggerOptions, condition);
  26333. this._sound = sound;
  26334. }
  26335. PlaySoundAction.prototype._prepare = function () {
  26336. };
  26337. PlaySoundAction.prototype.execute = function () {
  26338. if (this._sound !== undefined)
  26339. this._sound.play();
  26340. };
  26341. return PlaySoundAction;
  26342. })(BABYLON.Action);
  26343. BABYLON.PlaySoundAction = PlaySoundAction;
  26344. var StopSoundAction = (function (_super) {
  26345. __extends(StopSoundAction, _super);
  26346. function StopSoundAction(triggerOptions, sound, condition) {
  26347. _super.call(this, triggerOptions, condition);
  26348. this._sound = sound;
  26349. }
  26350. StopSoundAction.prototype._prepare = function () {
  26351. };
  26352. StopSoundAction.prototype.execute = function () {
  26353. if (this._sound !== undefined)
  26354. this._sound.stop();
  26355. };
  26356. return StopSoundAction;
  26357. })(BABYLON.Action);
  26358. BABYLON.StopSoundAction = StopSoundAction;
  26359. })(BABYLON || (BABYLON = {}));
  26360. //# sourceMappingURL=babylon.directActions.js.map
  26361. var __extends = this.__extends || function (d, b) {
  26362. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26363. function __() { this.constructor = d; }
  26364. __.prototype = b.prototype;
  26365. d.prototype = new __();
  26366. };
  26367. var BABYLON;
  26368. (function (BABYLON) {
  26369. var Geometry = (function () {
  26370. function Geometry(id, scene, vertexData, updatable, mesh) {
  26371. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26372. this._totalVertices = 0;
  26373. this._indices = [];
  26374. this._isDisposed = false;
  26375. this.id = id;
  26376. this._engine = scene.getEngine();
  26377. this._meshes = [];
  26378. this._scene = scene;
  26379. // vertexData
  26380. if (vertexData) {
  26381. this.setAllVerticesData(vertexData, updatable);
  26382. }
  26383. else {
  26384. this._totalVertices = 0;
  26385. this._indices = [];
  26386. }
  26387. // applyToMesh
  26388. if (mesh) {
  26389. this.applyToMesh(mesh);
  26390. mesh.computeWorldMatrix(true);
  26391. }
  26392. }
  26393. Geometry.prototype.getScene = function () {
  26394. return this._scene;
  26395. };
  26396. Geometry.prototype.getEngine = function () {
  26397. return this._engine;
  26398. };
  26399. Geometry.prototype.isReady = function () {
  26400. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26401. };
  26402. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26403. vertexData.applyToGeometry(this, updatable);
  26404. this.notifyUpdate();
  26405. };
  26406. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26407. this._vertexBuffers = this._vertexBuffers || {};
  26408. if (this._vertexBuffers[kind]) {
  26409. this._vertexBuffers[kind].dispose();
  26410. }
  26411. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26412. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26413. stride = this._vertexBuffers[kind].getStrideSize();
  26414. this._totalVertices = data.length / stride;
  26415. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26416. var meshes = this._meshes;
  26417. var numOfMeshes = meshes.length;
  26418. for (var index = 0; index < numOfMeshes; index++) {
  26419. var mesh = meshes[index];
  26420. mesh._resetPointsArrayCache();
  26421. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26422. mesh._createGlobalSubMesh();
  26423. mesh.computeWorldMatrix(true);
  26424. }
  26425. }
  26426. this.notifyUpdate(kind);
  26427. };
  26428. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26429. var vertexBuffer = this.getVertexBuffer(kind);
  26430. if (!vertexBuffer) {
  26431. return;
  26432. }
  26433. vertexBuffer.updateDirectly(data, offset);
  26434. this.notifyUpdate(kind);
  26435. };
  26436. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26437. var vertexBuffer = this.getVertexBuffer(kind);
  26438. if (!vertexBuffer) {
  26439. return;
  26440. }
  26441. vertexBuffer.update(data);
  26442. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26443. var extend;
  26444. var stride = vertexBuffer.getStrideSize();
  26445. this._totalVertices = data.length / stride;
  26446. if (updateExtends) {
  26447. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26448. }
  26449. var meshes = this._meshes;
  26450. var numOfMeshes = meshes.length;
  26451. for (var index = 0; index < numOfMeshes; index++) {
  26452. var mesh = meshes[index];
  26453. mesh._resetPointsArrayCache();
  26454. if (updateExtends) {
  26455. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26456. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26457. var subMesh = mesh.subMeshes[subIndex];
  26458. subMesh.refreshBoundingInfo();
  26459. }
  26460. }
  26461. }
  26462. }
  26463. this.notifyUpdate(kind);
  26464. };
  26465. Geometry.prototype.getTotalVertices = function () {
  26466. if (!this.isReady()) {
  26467. return 0;
  26468. }
  26469. return this._totalVertices;
  26470. };
  26471. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26472. var vertexBuffer = this.getVertexBuffer(kind);
  26473. if (!vertexBuffer) {
  26474. return null;
  26475. }
  26476. var orig = vertexBuffer.getData();
  26477. if (!copyWhenShared || this._meshes.length === 1) {
  26478. return orig;
  26479. }
  26480. else {
  26481. var len = orig.length;
  26482. var copy = [];
  26483. for (var i = 0; i < len; i++) {
  26484. copy.push(orig[i]);
  26485. }
  26486. return copy;
  26487. }
  26488. };
  26489. Geometry.prototype.getVertexBuffer = function (kind) {
  26490. if (!this.isReady()) {
  26491. return null;
  26492. }
  26493. return this._vertexBuffers[kind];
  26494. };
  26495. Geometry.prototype.getVertexBuffers = function () {
  26496. if (!this.isReady()) {
  26497. return null;
  26498. }
  26499. return this._vertexBuffers;
  26500. };
  26501. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26502. if (!this._vertexBuffers) {
  26503. if (this._delayInfo) {
  26504. return this._delayInfo.indexOf(kind) !== -1;
  26505. }
  26506. return false;
  26507. }
  26508. return this._vertexBuffers[kind] !== undefined;
  26509. };
  26510. Geometry.prototype.getVerticesDataKinds = function () {
  26511. var result = [];
  26512. if (!this._vertexBuffers && this._delayInfo) {
  26513. for (var kind in this._delayInfo) {
  26514. result.push(kind);
  26515. }
  26516. }
  26517. else {
  26518. for (kind in this._vertexBuffers) {
  26519. result.push(kind);
  26520. }
  26521. }
  26522. return result;
  26523. };
  26524. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26525. if (this._indexBuffer) {
  26526. this._engine._releaseBuffer(this._indexBuffer);
  26527. }
  26528. this._indices = indices;
  26529. if (this._meshes.length !== 0 && this._indices) {
  26530. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26531. }
  26532. if (totalVertices !== undefined) {
  26533. this._totalVertices = totalVertices;
  26534. }
  26535. var meshes = this._meshes;
  26536. var numOfMeshes = meshes.length;
  26537. for (var index = 0; index < numOfMeshes; index++) {
  26538. meshes[index]._createGlobalSubMesh();
  26539. }
  26540. this.notifyUpdate();
  26541. };
  26542. Geometry.prototype.getTotalIndices = function () {
  26543. if (!this.isReady()) {
  26544. return 0;
  26545. }
  26546. return this._indices.length;
  26547. };
  26548. Geometry.prototype.getIndices = function (copyWhenShared) {
  26549. if (!this.isReady()) {
  26550. return null;
  26551. }
  26552. var orig = this._indices;
  26553. if (!copyWhenShared || this._meshes.length === 1) {
  26554. return orig;
  26555. }
  26556. else {
  26557. var len = orig.length;
  26558. var copy = [];
  26559. for (var i = 0; i < len; i++) {
  26560. copy.push(orig[i]);
  26561. }
  26562. return copy;
  26563. }
  26564. };
  26565. Geometry.prototype.getIndexBuffer = function () {
  26566. if (!this.isReady()) {
  26567. return null;
  26568. }
  26569. return this._indexBuffer;
  26570. };
  26571. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26572. var meshes = this._meshes;
  26573. var index = meshes.indexOf(mesh);
  26574. if (index === -1) {
  26575. return;
  26576. }
  26577. for (var kind in this._vertexBuffers) {
  26578. this._vertexBuffers[kind].dispose();
  26579. }
  26580. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26581. this._indexBuffer = null;
  26582. }
  26583. meshes.splice(index, 1);
  26584. mesh._geometry = null;
  26585. if (meshes.length === 0 && shouldDispose) {
  26586. this.dispose();
  26587. }
  26588. };
  26589. Geometry.prototype.applyToMesh = function (mesh) {
  26590. if (mesh._geometry === this) {
  26591. return;
  26592. }
  26593. var previousGeometry = mesh._geometry;
  26594. if (previousGeometry) {
  26595. previousGeometry.releaseForMesh(mesh);
  26596. }
  26597. var meshes = this._meshes;
  26598. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26599. mesh._geometry = this;
  26600. this._scene.pushGeometry(this);
  26601. meshes.push(mesh);
  26602. if (this.isReady()) {
  26603. this._applyToMesh(mesh);
  26604. }
  26605. else {
  26606. mesh._boundingInfo = this._boundingInfo;
  26607. }
  26608. };
  26609. Geometry.prototype._applyToMesh = function (mesh) {
  26610. var numOfMeshes = this._meshes.length;
  26611. // vertexBuffers
  26612. for (var kind in this._vertexBuffers) {
  26613. if (numOfMeshes === 1) {
  26614. this._vertexBuffers[kind].create();
  26615. }
  26616. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26617. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26618. mesh._resetPointsArrayCache();
  26619. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26620. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26621. mesh._createGlobalSubMesh();
  26622. //bounding info was just created again, world matrix should be applied again.
  26623. mesh._updateBoundingInfo();
  26624. }
  26625. }
  26626. // indexBuffer
  26627. if (numOfMeshes === 1 && this._indices) {
  26628. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26629. }
  26630. if (this._indexBuffer) {
  26631. this._indexBuffer.references = numOfMeshes;
  26632. }
  26633. };
  26634. Geometry.prototype.notifyUpdate = function (kind) {
  26635. if (this.onGeometryUpdated) {
  26636. this.onGeometryUpdated(this, kind);
  26637. }
  26638. };
  26639. Geometry.prototype.load = function (scene, onLoaded) {
  26640. var _this = this;
  26641. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26642. return;
  26643. }
  26644. if (this.isReady()) {
  26645. if (onLoaded) {
  26646. onLoaded();
  26647. }
  26648. return;
  26649. }
  26650. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26651. scene._addPendingData(this);
  26652. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26653. _this._delayLoadingFunction(JSON.parse(data), _this);
  26654. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26655. _this._delayInfo = [];
  26656. scene._removePendingData(_this);
  26657. var meshes = _this._meshes;
  26658. var numOfMeshes = meshes.length;
  26659. for (var index = 0; index < numOfMeshes; index++) {
  26660. _this._applyToMesh(meshes[index]);
  26661. }
  26662. if (onLoaded) {
  26663. onLoaded();
  26664. }
  26665. }, function () { }, scene.database);
  26666. };
  26667. Geometry.prototype.isDisposed = function () {
  26668. return this._isDisposed;
  26669. };
  26670. Geometry.prototype.dispose = function () {
  26671. var meshes = this._meshes;
  26672. var numOfMeshes = meshes.length;
  26673. var index;
  26674. for (index = 0; index < numOfMeshes; index++) {
  26675. this.releaseForMesh(meshes[index]);
  26676. }
  26677. this._meshes = [];
  26678. for (var kind in this._vertexBuffers) {
  26679. this._vertexBuffers[kind].dispose();
  26680. }
  26681. this._vertexBuffers = [];
  26682. this._totalVertices = 0;
  26683. if (this._indexBuffer) {
  26684. this._engine._releaseBuffer(this._indexBuffer);
  26685. }
  26686. this._indexBuffer = null;
  26687. this._indices = [];
  26688. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26689. this.delayLoadingFile = null;
  26690. this._delayLoadingFunction = null;
  26691. this._delayInfo = [];
  26692. this._boundingInfo = null; // todo: .dispose()
  26693. this._scene.removeGeometry(this);
  26694. this._isDisposed = true;
  26695. };
  26696. Geometry.prototype.copy = function (id) {
  26697. var vertexData = new BABYLON.VertexData();
  26698. vertexData.indices = [];
  26699. var indices = this.getIndices();
  26700. for (var index = 0; index < indices.length; index++) {
  26701. vertexData.indices.push(indices[index]);
  26702. }
  26703. var updatable = false;
  26704. var stopChecking = false;
  26705. for (var kind in this._vertexBuffers) {
  26706. // using slice() to make a copy of the array and not just reference it
  26707. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  26708. if (!stopChecking) {
  26709. updatable = this.getVertexBuffer(kind).isUpdatable();
  26710. stopChecking = !updatable;
  26711. }
  26712. }
  26713. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26714. geometry.delayLoadState = this.delayLoadState;
  26715. geometry.delayLoadingFile = this.delayLoadingFile;
  26716. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26717. for (kind in this._delayInfo) {
  26718. geometry._delayInfo = geometry._delayInfo || [];
  26719. geometry._delayInfo.push(kind);
  26720. }
  26721. // Bounding info
  26722. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  26723. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26724. return geometry;
  26725. };
  26726. // Statics
  26727. Geometry.ExtractFromMesh = function (mesh, id) {
  26728. var geometry = mesh._geometry;
  26729. if (!geometry) {
  26730. return null;
  26731. }
  26732. return geometry.copy(id);
  26733. };
  26734. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26735. // be aware Math.random() could cause collisions
  26736. Geometry.RandomId = function () {
  26737. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26738. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26739. return v.toString(16);
  26740. });
  26741. };
  26742. return Geometry;
  26743. })();
  26744. BABYLON.Geometry = Geometry;
  26745. /////// Primitives //////////////////////////////////////////////
  26746. var Geometry;
  26747. (function (Geometry) {
  26748. var Primitives;
  26749. (function (Primitives) {
  26750. /// Abstract class
  26751. var _Primitive = (function (_super) {
  26752. __extends(_Primitive, _super);
  26753. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26754. this._beingRegenerated = true;
  26755. this._canBeRegenerated = canBeRegenerated;
  26756. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26757. this._beingRegenerated = false;
  26758. }
  26759. _Primitive.prototype.canBeRegenerated = function () {
  26760. return this._canBeRegenerated;
  26761. };
  26762. _Primitive.prototype.regenerate = function () {
  26763. if (!this._canBeRegenerated) {
  26764. return;
  26765. }
  26766. this._beingRegenerated = true;
  26767. this.setAllVerticesData(this._regenerateVertexData(), false);
  26768. this._beingRegenerated = false;
  26769. };
  26770. _Primitive.prototype.asNewGeometry = function (id) {
  26771. return _super.prototype.copy.call(this, id);
  26772. };
  26773. // overrides
  26774. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26775. if (!this._beingRegenerated) {
  26776. return;
  26777. }
  26778. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26779. };
  26780. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26781. if (!this._beingRegenerated) {
  26782. return;
  26783. }
  26784. _super.prototype.setVerticesData.call(this, kind, data, false);
  26785. };
  26786. // to override
  26787. // protected
  26788. _Primitive.prototype._regenerateVertexData = function () {
  26789. throw new Error("Abstract method");
  26790. };
  26791. _Primitive.prototype.copy = function (id) {
  26792. throw new Error("Must be overriden in sub-classes.");
  26793. };
  26794. return _Primitive;
  26795. })(Geometry);
  26796. Primitives._Primitive = _Primitive;
  26797. var Ribbon = (function (_super) {
  26798. __extends(Ribbon, _super);
  26799. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26800. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26801. this.pathArray = pathArray;
  26802. this.closeArray = closeArray;
  26803. this.closePath = closePath;
  26804. this.offset = offset;
  26805. this.side = side;
  26806. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26807. }
  26808. Ribbon.prototype._regenerateVertexData = function () {
  26809. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  26810. };
  26811. Ribbon.prototype.copy = function (id) {
  26812. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26813. };
  26814. return Ribbon;
  26815. })(_Primitive);
  26816. Primitives.Ribbon = Ribbon;
  26817. var Box = (function (_super) {
  26818. __extends(Box, _super);
  26819. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26821. this.size = size;
  26822. this.side = side;
  26823. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26824. }
  26825. Box.prototype._regenerateVertexData = function () {
  26826. return BABYLON.VertexData.CreateBox(this.size, this.side);
  26827. };
  26828. Box.prototype.copy = function (id) {
  26829. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26830. };
  26831. return Box;
  26832. })(_Primitive);
  26833. Primitives.Box = Box;
  26834. var Sphere = (function (_super) {
  26835. __extends(Sphere, _super);
  26836. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26837. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26838. this.segments = segments;
  26839. this.diameter = diameter;
  26840. this.side = side;
  26841. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26842. }
  26843. Sphere.prototype._regenerateVertexData = function () {
  26844. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  26845. };
  26846. Sphere.prototype.copy = function (id) {
  26847. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26848. };
  26849. return Sphere;
  26850. })(_Primitive);
  26851. Primitives.Sphere = Sphere;
  26852. var Cylinder = (function (_super) {
  26853. __extends(Cylinder, _super);
  26854. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26855. if (subdivisions === void 0) { subdivisions = 1; }
  26856. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26857. this.height = height;
  26858. this.diameterTop = diameterTop;
  26859. this.diameterBottom = diameterBottom;
  26860. this.tessellation = tessellation;
  26861. this.subdivisions = subdivisions;
  26862. this.side = side;
  26863. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26864. }
  26865. Cylinder.prototype._regenerateVertexData = function () {
  26866. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  26867. };
  26868. Cylinder.prototype.copy = function (id) {
  26869. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26870. };
  26871. return Cylinder;
  26872. })(_Primitive);
  26873. Primitives.Cylinder = Cylinder;
  26874. var Torus = (function (_super) {
  26875. __extends(Torus, _super);
  26876. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26878. this.diameter = diameter;
  26879. this.thickness = thickness;
  26880. this.tessellation = tessellation;
  26881. this.side = side;
  26882. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26883. }
  26884. Torus.prototype._regenerateVertexData = function () {
  26885. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  26886. };
  26887. Torus.prototype.copy = function (id) {
  26888. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26889. };
  26890. return Torus;
  26891. })(_Primitive);
  26892. Primitives.Torus = Torus;
  26893. var Ground = (function (_super) {
  26894. __extends(Ground, _super);
  26895. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26896. this.width = width;
  26897. this.height = height;
  26898. this.subdivisions = subdivisions;
  26899. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26900. }
  26901. Ground.prototype._regenerateVertexData = function () {
  26902. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  26903. };
  26904. Ground.prototype.copy = function (id) {
  26905. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26906. };
  26907. return Ground;
  26908. })(_Primitive);
  26909. Primitives.Ground = Ground;
  26910. var TiledGround = (function (_super) {
  26911. __extends(TiledGround, _super);
  26912. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26913. this.xmin = xmin;
  26914. this.zmin = zmin;
  26915. this.xmax = xmax;
  26916. this.zmax = zmax;
  26917. this.subdivisions = subdivisions;
  26918. this.precision = precision;
  26919. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26920. }
  26921. TiledGround.prototype._regenerateVertexData = function () {
  26922. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  26923. };
  26924. TiledGround.prototype.copy = function (id) {
  26925. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26926. };
  26927. return TiledGround;
  26928. })(_Primitive);
  26929. Primitives.TiledGround = TiledGround;
  26930. var Plane = (function (_super) {
  26931. __extends(Plane, _super);
  26932. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26934. this.size = size;
  26935. this.side = side;
  26936. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26937. }
  26938. Plane.prototype._regenerateVertexData = function () {
  26939. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  26940. };
  26941. Plane.prototype.copy = function (id) {
  26942. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26943. };
  26944. return Plane;
  26945. })(_Primitive);
  26946. Primitives.Plane = Plane;
  26947. var TorusKnot = (function (_super) {
  26948. __extends(TorusKnot, _super);
  26949. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26950. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26951. this.radius = radius;
  26952. this.tube = tube;
  26953. this.radialSegments = radialSegments;
  26954. this.tubularSegments = tubularSegments;
  26955. this.p = p;
  26956. this.q = q;
  26957. this.side = side;
  26958. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26959. }
  26960. TorusKnot.prototype._regenerateVertexData = function () {
  26961. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  26962. };
  26963. TorusKnot.prototype.copy = function (id) {
  26964. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26965. };
  26966. return TorusKnot;
  26967. })(_Primitive);
  26968. Primitives.TorusKnot = TorusKnot;
  26969. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26970. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26971. })(BABYLON || (BABYLON = {}));
  26972. //# sourceMappingURL=babylon.geometry.js.map
  26973. var __extends = this.__extends || function (d, b) {
  26974. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26975. function __() { this.constructor = d; }
  26976. __.prototype = b.prototype;
  26977. d.prototype = new __();
  26978. };
  26979. var BABYLON;
  26980. (function (BABYLON) {
  26981. var GroundMesh = (function (_super) {
  26982. __extends(GroundMesh, _super);
  26983. function GroundMesh(name, scene) {
  26984. _super.call(this, name, scene);
  26985. this.generateOctree = false;
  26986. this._worldInverse = new BABYLON.Matrix();
  26987. }
  26988. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26989. get: function () {
  26990. return this._subdivisions;
  26991. },
  26992. enumerable: true,
  26993. configurable: true
  26994. });
  26995. GroundMesh.prototype.optimize = function (chunksCount) {
  26996. this.subdivide(this._subdivisions);
  26997. this.createOrUpdateSubmeshesOctree(32);
  26998. };
  26999. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27000. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27001. this.getWorldMatrix().invertToRef(this._worldInverse);
  27002. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27003. var pickInfo = this.intersects(ray);
  27004. if (pickInfo.hit) {
  27005. return pickInfo.pickedPoint.y;
  27006. }
  27007. return 0;
  27008. };
  27009. return GroundMesh;
  27010. })(BABYLON.Mesh);
  27011. BABYLON.GroundMesh = GroundMesh;
  27012. })(BABYLON || (BABYLON = {}));
  27013. //# sourceMappingURL=babylon.groundMesh.js.map
  27014. var __extends = this.__extends || function (d, b) {
  27015. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27016. function __() { this.constructor = d; }
  27017. __.prototype = b.prototype;
  27018. d.prototype = new __();
  27019. };
  27020. var BABYLON;
  27021. (function (BABYLON) {
  27022. var Gamepads = (function () {
  27023. function Gamepads(ongamedpadconnected) {
  27024. var _this = this;
  27025. this.babylonGamepads = [];
  27026. this.oneGamepadConnected = false;
  27027. this.isMonitoring = false;
  27028. this.gamepadEventSupported = 'GamepadEvent' in window;
  27029. this.gamepadSupportAvailable = (navigator.getGamepads ||
  27030. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  27031. 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=";
  27032. this._callbackGamepadConnected = ongamedpadconnected;
  27033. if (this.gamepadSupportAvailable) {
  27034. // Checking if the gamepad connected event is supported (like in Firefox)
  27035. if (this.gamepadEventSupported) {
  27036. window.addEventListener('gamepadconnected', function (evt) {
  27037. _this._onGamepadConnected(evt);
  27038. }, false);
  27039. window.addEventListener('gamepaddisconnected', function (evt) {
  27040. _this._onGamepadDisconnected(evt);
  27041. }, false);
  27042. }
  27043. else {
  27044. this._startMonitoringGamepads();
  27045. }
  27046. if (!this.oneGamepadConnected) {
  27047. this._insertGamepadDOMInstructions();
  27048. }
  27049. }
  27050. else {
  27051. this._insertGamepadDOMNotSupported();
  27052. }
  27053. }
  27054. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  27055. Gamepads.gamepadDOMInfo = document.createElement("div");
  27056. var buttonAImage = document.createElement("img");
  27057. buttonAImage.src = this.buttonADataURL;
  27058. var spanMessage = document.createElement("span");
  27059. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  27060. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  27061. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27062. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27063. Gamepads.gamepadDOMInfo.style.width = "100%";
  27064. Gamepads.gamepadDOMInfo.style.height = "48px";
  27065. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27066. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27067. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27068. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27069. buttonAImage.style.position = "relative";
  27070. buttonAImage.style.bottom = "8px";
  27071. spanMessage.style.position = "relative";
  27072. spanMessage.style.fontSize = "32px";
  27073. spanMessage.style.bottom = "32px";
  27074. spanMessage.style.color = "green";
  27075. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27076. };
  27077. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  27078. Gamepads.gamepadDOMInfo = document.createElement("div");
  27079. var spanMessage = document.createElement("span");
  27080. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  27081. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27082. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27083. Gamepads.gamepadDOMInfo.style.width = "100%";
  27084. Gamepads.gamepadDOMInfo.style.height = "40px";
  27085. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27086. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27087. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27088. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27089. spanMessage.style.position = "relative";
  27090. spanMessage.style.fontSize = "32px";
  27091. spanMessage.style.color = "red";
  27092. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27093. };
  27094. Gamepads.prototype.dispose = function () {
  27095. if (Gamepads.gamepadDOMInfo) {
  27096. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27097. }
  27098. };
  27099. Gamepads.prototype._onGamepadConnected = function (evt) {
  27100. var newGamepad = this._addNewGamepad(evt.gamepad);
  27101. if (this._callbackGamepadConnected)
  27102. this._callbackGamepadConnected(newGamepad);
  27103. this._startMonitoringGamepads();
  27104. };
  27105. Gamepads.prototype._addNewGamepad = function (gamepad) {
  27106. if (!this.oneGamepadConnected) {
  27107. this.oneGamepadConnected = true;
  27108. if (Gamepads.gamepadDOMInfo) {
  27109. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27110. Gamepads.gamepadDOMInfo = null;
  27111. }
  27112. }
  27113. var newGamepad;
  27114. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  27115. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  27116. }
  27117. else {
  27118. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  27119. }
  27120. this.babylonGamepads.push(newGamepad);
  27121. return newGamepad;
  27122. };
  27123. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  27124. // Remove the gamepad from the list of gamepads to monitor.
  27125. for (var i in this.babylonGamepads) {
  27126. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  27127. this.babylonGamepads.splice(i, 1);
  27128. break;
  27129. }
  27130. }
  27131. // If no gamepads are left, stop the polling loop.
  27132. if (this.babylonGamepads.length == 0) {
  27133. this._stopMonitoringGamepads();
  27134. }
  27135. };
  27136. Gamepads.prototype._startMonitoringGamepads = function () {
  27137. if (!this.isMonitoring) {
  27138. this.isMonitoring = true;
  27139. this._checkGamepadsStatus();
  27140. }
  27141. };
  27142. Gamepads.prototype._stopMonitoringGamepads = function () {
  27143. this.isMonitoring = false;
  27144. };
  27145. Gamepads.prototype._checkGamepadsStatus = function () {
  27146. var _this = this;
  27147. // updating gamepad objects
  27148. this._updateGamepadObjects();
  27149. for (var i in this.babylonGamepads) {
  27150. this.babylonGamepads[i].update();
  27151. }
  27152. if (this.isMonitoring) {
  27153. if (window.requestAnimationFrame) {
  27154. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  27155. }
  27156. else if (window.mozRequestAnimationFrame) {
  27157. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  27158. }
  27159. else if (window.webkitRequestAnimationFrame) {
  27160. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  27161. }
  27162. }
  27163. };
  27164. // This function is called only on Chrome, which does not yet support
  27165. // connection/disconnection events, but requires you to monitor
  27166. // an array for changes.
  27167. Gamepads.prototype._updateGamepadObjects = function () {
  27168. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  27169. for (var i = 0; i < gamepads.length; i++) {
  27170. if (gamepads[i]) {
  27171. if (!(gamepads[i].index in this.babylonGamepads)) {
  27172. var newGamepad = this._addNewGamepad(gamepads[i]);
  27173. if (this._callbackGamepadConnected) {
  27174. this._callbackGamepadConnected(newGamepad);
  27175. }
  27176. }
  27177. else {
  27178. this.babylonGamepads[i].browserGamepad = gamepads[i];
  27179. }
  27180. }
  27181. }
  27182. };
  27183. return Gamepads;
  27184. })();
  27185. BABYLON.Gamepads = Gamepads;
  27186. var StickValues = (function () {
  27187. function StickValues(x, y) {
  27188. this.x = x;
  27189. this.y = y;
  27190. }
  27191. return StickValues;
  27192. })();
  27193. BABYLON.StickValues = StickValues;
  27194. var Gamepad = (function () {
  27195. function Gamepad(id, index, browserGamepad) {
  27196. this.id = id;
  27197. this.index = index;
  27198. this.browserGamepad = browserGamepad;
  27199. if (this.browserGamepad.axes.length >= 2) {
  27200. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27201. }
  27202. if (this.browserGamepad.axes.length >= 4) {
  27203. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27204. }
  27205. }
  27206. Gamepad.prototype.onleftstickchanged = function (callback) {
  27207. this._onleftstickchanged = callback;
  27208. };
  27209. Gamepad.prototype.onrightstickchanged = function (callback) {
  27210. this._onrightstickchanged = callback;
  27211. };
  27212. Object.defineProperty(Gamepad.prototype, "leftStick", {
  27213. get: function () {
  27214. return this._leftStick;
  27215. },
  27216. set: function (newValues) {
  27217. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  27218. this._onleftstickchanged(newValues);
  27219. }
  27220. this._leftStick = newValues;
  27221. },
  27222. enumerable: true,
  27223. configurable: true
  27224. });
  27225. Object.defineProperty(Gamepad.prototype, "rightStick", {
  27226. get: function () {
  27227. return this._rightStick;
  27228. },
  27229. set: function (newValues) {
  27230. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  27231. this._onrightstickchanged(newValues);
  27232. }
  27233. this._rightStick = newValues;
  27234. },
  27235. enumerable: true,
  27236. configurable: true
  27237. });
  27238. Gamepad.prototype.update = function () {
  27239. if (this._leftStick) {
  27240. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27241. }
  27242. if (this._rightStick) {
  27243. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27244. }
  27245. };
  27246. return Gamepad;
  27247. })();
  27248. BABYLON.Gamepad = Gamepad;
  27249. var GenericPad = (function (_super) {
  27250. __extends(GenericPad, _super);
  27251. function GenericPad(id, index, gamepad) {
  27252. _super.call(this, id, index, gamepad);
  27253. this.id = id;
  27254. this.index = index;
  27255. this.gamepad = gamepad;
  27256. this._buttons = new Array(gamepad.buttons.length);
  27257. }
  27258. GenericPad.prototype.onbuttondown = function (callback) {
  27259. this._onbuttondown = callback;
  27260. };
  27261. GenericPad.prototype.onbuttonup = function (callback) {
  27262. this._onbuttonup = callback;
  27263. };
  27264. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  27265. if (newValue !== currentValue) {
  27266. if (this._onbuttondown && newValue === 1) {
  27267. this._onbuttondown(buttonIndex);
  27268. }
  27269. if (this._onbuttonup && newValue === 0) {
  27270. this._onbuttonup(buttonIndex);
  27271. }
  27272. }
  27273. return newValue;
  27274. };
  27275. GenericPad.prototype.update = function () {
  27276. _super.prototype.update.call(this);
  27277. for (var index = 0; index < this._buttons.length; index++) {
  27278. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  27279. }
  27280. };
  27281. return GenericPad;
  27282. })(Gamepad);
  27283. BABYLON.GenericPad = GenericPad;
  27284. (function (Xbox360Button) {
  27285. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  27286. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  27287. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  27288. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  27289. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  27290. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  27291. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  27292. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  27293. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  27294. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  27295. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  27296. var Xbox360Button = BABYLON.Xbox360Button;
  27297. (function (Xbox360Dpad) {
  27298. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  27299. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  27300. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  27301. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  27302. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  27303. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  27304. var Xbox360Pad = (function (_super) {
  27305. __extends(Xbox360Pad, _super);
  27306. function Xbox360Pad() {
  27307. _super.apply(this, arguments);
  27308. this._leftTrigger = 0;
  27309. this._rightTrigger = 0;
  27310. this._buttonA = 0;
  27311. this._buttonB = 0;
  27312. this._buttonX = 0;
  27313. this._buttonY = 0;
  27314. this._buttonBack = 0;
  27315. this._buttonStart = 0;
  27316. this._buttonLB = 0;
  27317. this._buttonRB = 0;
  27318. this._buttonLeftStick = 0;
  27319. this._buttonRightStick = 0;
  27320. this._dPadUp = 0;
  27321. this._dPadDown = 0;
  27322. this._dPadLeft = 0;
  27323. this._dPadRight = 0;
  27324. }
  27325. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  27326. this._onlefttriggerchanged = callback;
  27327. };
  27328. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  27329. this._onrighttriggerchanged = callback;
  27330. };
  27331. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  27332. get: function () {
  27333. return this._leftTrigger;
  27334. },
  27335. set: function (newValue) {
  27336. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  27337. this._onlefttriggerchanged(newValue);
  27338. }
  27339. this._leftTrigger = newValue;
  27340. },
  27341. enumerable: true,
  27342. configurable: true
  27343. });
  27344. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  27345. get: function () {
  27346. return this._rightTrigger;
  27347. },
  27348. set: function (newValue) {
  27349. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  27350. this._onrighttriggerchanged(newValue);
  27351. }
  27352. this._rightTrigger = newValue;
  27353. },
  27354. enumerable: true,
  27355. configurable: true
  27356. });
  27357. Xbox360Pad.prototype.onbuttondown = function (callback) {
  27358. this._onbuttondown = callback;
  27359. };
  27360. Xbox360Pad.prototype.onbuttonup = function (callback) {
  27361. this._onbuttonup = callback;
  27362. };
  27363. Xbox360Pad.prototype.ondpaddown = function (callback) {
  27364. this._ondpaddown = callback;
  27365. };
  27366. Xbox360Pad.prototype.ondpadup = function (callback) {
  27367. this._ondpadup = callback;
  27368. };
  27369. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  27370. if (newValue !== currentValue) {
  27371. if (this._onbuttondown && newValue === 1) {
  27372. this._onbuttondown(buttonType);
  27373. }
  27374. if (this._onbuttonup && newValue === 0) {
  27375. this._onbuttonup(buttonType);
  27376. }
  27377. }
  27378. return newValue;
  27379. };
  27380. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  27381. if (newValue !== currentValue) {
  27382. if (this._ondpaddown && newValue === 1) {
  27383. this._ondpaddown(buttonType);
  27384. }
  27385. if (this._ondpadup && newValue === 0) {
  27386. this._ondpadup(buttonType);
  27387. }
  27388. }
  27389. return newValue;
  27390. };
  27391. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  27392. get: function () {
  27393. return this._buttonA;
  27394. },
  27395. set: function (value) {
  27396. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  27397. },
  27398. enumerable: true,
  27399. configurable: true
  27400. });
  27401. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  27402. get: function () {
  27403. return this._buttonB;
  27404. },
  27405. set: function (value) {
  27406. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  27407. },
  27408. enumerable: true,
  27409. configurable: true
  27410. });
  27411. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  27412. get: function () {
  27413. return this._buttonX;
  27414. },
  27415. set: function (value) {
  27416. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  27417. },
  27418. enumerable: true,
  27419. configurable: true
  27420. });
  27421. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  27422. get: function () {
  27423. return this._buttonY;
  27424. },
  27425. set: function (value) {
  27426. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  27427. },
  27428. enumerable: true,
  27429. configurable: true
  27430. });
  27431. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  27432. get: function () {
  27433. return this._buttonStart;
  27434. },
  27435. set: function (value) {
  27436. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  27437. },
  27438. enumerable: true,
  27439. configurable: true
  27440. });
  27441. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  27442. get: function () {
  27443. return this._buttonBack;
  27444. },
  27445. set: function (value) {
  27446. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  27447. },
  27448. enumerable: true,
  27449. configurable: true
  27450. });
  27451. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  27452. get: function () {
  27453. return this._buttonLB;
  27454. },
  27455. set: function (value) {
  27456. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  27457. },
  27458. enumerable: true,
  27459. configurable: true
  27460. });
  27461. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  27462. get: function () {
  27463. return this._buttonRB;
  27464. },
  27465. set: function (value) {
  27466. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  27467. },
  27468. enumerable: true,
  27469. configurable: true
  27470. });
  27471. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  27472. get: function () {
  27473. return this._buttonLeftStick;
  27474. },
  27475. set: function (value) {
  27476. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  27477. },
  27478. enumerable: true,
  27479. configurable: true
  27480. });
  27481. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  27482. get: function () {
  27483. return this._buttonRightStick;
  27484. },
  27485. set: function (value) {
  27486. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  27487. },
  27488. enumerable: true,
  27489. configurable: true
  27490. });
  27491. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  27492. get: function () {
  27493. return this._dPadUp;
  27494. },
  27495. set: function (value) {
  27496. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  27497. },
  27498. enumerable: true,
  27499. configurable: true
  27500. });
  27501. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  27502. get: function () {
  27503. return this._dPadDown;
  27504. },
  27505. set: function (value) {
  27506. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  27507. },
  27508. enumerable: true,
  27509. configurable: true
  27510. });
  27511. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  27512. get: function () {
  27513. return this._dPadLeft;
  27514. },
  27515. set: function (value) {
  27516. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  27517. },
  27518. enumerable: true,
  27519. configurable: true
  27520. });
  27521. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  27522. get: function () {
  27523. return this._dPadRight;
  27524. },
  27525. set: function (value) {
  27526. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  27527. },
  27528. enumerable: true,
  27529. configurable: true
  27530. });
  27531. Xbox360Pad.prototype.update = function () {
  27532. _super.prototype.update.call(this);
  27533. this.buttonA = this.browserGamepad.buttons[0].value;
  27534. this.buttonB = this.browserGamepad.buttons[1].value;
  27535. this.buttonX = this.browserGamepad.buttons[2].value;
  27536. this.buttonY = this.browserGamepad.buttons[3].value;
  27537. this.buttonLB = this.browserGamepad.buttons[4].value;
  27538. this.buttonRB = this.browserGamepad.buttons[5].value;
  27539. this.leftTrigger = this.browserGamepad.buttons[6].value;
  27540. this.rightTrigger = this.browserGamepad.buttons[7].value;
  27541. this.buttonBack = this.browserGamepad.buttons[8].value;
  27542. this.buttonStart = this.browserGamepad.buttons[9].value;
  27543. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  27544. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  27545. this.dPadUp = this.browserGamepad.buttons[12].value;
  27546. this.dPadDown = this.browserGamepad.buttons[13].value;
  27547. this.dPadLeft = this.browserGamepad.buttons[14].value;
  27548. this.dPadRight = this.browserGamepad.buttons[15].value;
  27549. };
  27550. return Xbox360Pad;
  27551. })(Gamepad);
  27552. BABYLON.Xbox360Pad = Xbox360Pad;
  27553. })(BABYLON || (BABYLON = {}));
  27554. //# sourceMappingURL=babylon.gamepads.js.map
  27555. var __extends = this.__extends || function (d, b) {
  27556. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27557. function __() { this.constructor = d; }
  27558. __.prototype = b.prototype;
  27559. d.prototype = new __();
  27560. };
  27561. var BABYLON;
  27562. (function (BABYLON) {
  27563. // We're mainly based on the logic defined into the FreeCamera code
  27564. var GamepadCamera = (function (_super) {
  27565. __extends(GamepadCamera, _super);
  27566. function GamepadCamera(name, position, scene) {
  27567. var _this = this;
  27568. _super.call(this, name, position, scene);
  27569. this.angularSensibility = 200;
  27570. this.moveSensibility = 75;
  27571. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  27572. }
  27573. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  27574. // Only the first gamepad can control the camera
  27575. if (gamepad.index === 0) {
  27576. this._gamepad = gamepad;
  27577. }
  27578. };
  27579. GamepadCamera.prototype._checkInputs = function () {
  27580. if (!this._gamepad) {
  27581. return;
  27582. }
  27583. var LSValues = this._gamepad.leftStick;
  27584. var normalizedLX = LSValues.x / this.moveSensibility;
  27585. var normalizedLY = LSValues.y / this.moveSensibility;
  27586. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  27587. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  27588. var RSValues = this._gamepad.rightStick;
  27589. var normalizedRX = RSValues.x / this.angularSensibility;
  27590. var normalizedRY = RSValues.y / this.angularSensibility;
  27591. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  27592. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  27593. ;
  27594. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  27595. var speed = this._computeLocalCameraSpeed() * 50.0;
  27596. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  27597. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  27598. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  27599. };
  27600. GamepadCamera.prototype.dispose = function () {
  27601. this._gamepads.dispose();
  27602. _super.prototype.dispose.call(this);
  27603. };
  27604. return GamepadCamera;
  27605. })(BABYLON.FreeCamera);
  27606. BABYLON.GamepadCamera = GamepadCamera;
  27607. })(BABYLON || (BABYLON = {}));
  27608. //# sourceMappingURL=babylon.gamepadCamera.js.map
  27609. var __extends = this.__extends || function (d, b) {
  27610. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27611. function __() { this.constructor = d; }
  27612. __.prototype = b.prototype;
  27613. d.prototype = new __();
  27614. };
  27615. var BABYLON;
  27616. (function (BABYLON) {
  27617. var LinesMesh = (function (_super) {
  27618. __extends(LinesMesh, _super);
  27619. function LinesMesh(name, scene, updatable) {
  27620. if (updatable === void 0) { updatable = false; }
  27621. _super.call(this, name, scene);
  27622. this.color = new BABYLON.Color3(1, 1, 1);
  27623. this.alpha = 1;
  27624. this._indices = new Array();
  27625. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27626. attributes: ["position"],
  27627. uniforms: ["worldViewProjection", "color"],
  27628. needAlphaBlending: true
  27629. });
  27630. }
  27631. Object.defineProperty(LinesMesh.prototype, "material", {
  27632. get: function () {
  27633. return this._colorShader;
  27634. },
  27635. enumerable: true,
  27636. configurable: true
  27637. });
  27638. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27639. get: function () {
  27640. return false;
  27641. },
  27642. enumerable: true,
  27643. configurable: true
  27644. });
  27645. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27646. get: function () {
  27647. return false;
  27648. },
  27649. enumerable: true,
  27650. configurable: true
  27651. });
  27652. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27653. var engine = this.getScene().getEngine();
  27654. var indexToBind = this._geometry.getIndexBuffer();
  27655. // VBOs
  27656. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27657. // Color
  27658. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27659. };
  27660. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27661. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27662. return;
  27663. }
  27664. var engine = this.getScene().getEngine();
  27665. // Draw order
  27666. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27667. };
  27668. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27669. return null;
  27670. };
  27671. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27672. this._colorShader.dispose();
  27673. _super.prototype.dispose.call(this, doNotRecurse);
  27674. };
  27675. return LinesMesh;
  27676. })(BABYLON.Mesh);
  27677. BABYLON.LinesMesh = LinesMesh;
  27678. })(BABYLON || (BABYLON = {}));
  27679. //# sourceMappingURL=babylon.linesMesh.js.map
  27680. var BABYLON;
  27681. (function (BABYLON) {
  27682. var OutlineRenderer = (function () {
  27683. function OutlineRenderer(scene) {
  27684. this._scene = scene;
  27685. }
  27686. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27687. var _this = this;
  27688. if (useOverlay === void 0) { useOverlay = false; }
  27689. var scene = this._scene;
  27690. var engine = this._scene.getEngine();
  27691. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27692. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27693. return;
  27694. }
  27695. var mesh = subMesh.getRenderingMesh();
  27696. var material = subMesh.getMaterial();
  27697. engine.enableEffect(this._effect);
  27698. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27699. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27700. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27701. // Bones
  27702. if (mesh.useBones) {
  27703. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27704. }
  27705. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27706. // Alpha test
  27707. if (material && material.needAlphaTesting()) {
  27708. var alphaTexture = material.getAlphaTestTexture();
  27709. this._effect.setTexture("diffuseSampler", alphaTexture);
  27710. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27711. }
  27712. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  27713. };
  27714. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27715. var defines = [];
  27716. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27717. var mesh = subMesh.getMesh();
  27718. var material = subMesh.getMaterial();
  27719. // Alpha test
  27720. if (material && material.needAlphaTesting()) {
  27721. defines.push("#define ALPHATEST");
  27722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27723. attribs.push(BABYLON.VertexBuffer.UVKind);
  27724. defines.push("#define UV1");
  27725. }
  27726. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27727. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27728. defines.push("#define UV2");
  27729. }
  27730. }
  27731. // Bones
  27732. if (mesh.useBones) {
  27733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27735. defines.push("#define BONES");
  27736. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27737. }
  27738. // Instances
  27739. if (useInstances) {
  27740. defines.push("#define INSTANCES");
  27741. attribs.push("world0");
  27742. attribs.push("world1");
  27743. attribs.push("world2");
  27744. attribs.push("world3");
  27745. }
  27746. // Get correct effect
  27747. var join = defines.join("\n");
  27748. if (this._cachedDefines !== join) {
  27749. this._cachedDefines = join;
  27750. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  27751. }
  27752. return this._effect.isReady();
  27753. };
  27754. return OutlineRenderer;
  27755. })();
  27756. BABYLON.OutlineRenderer = OutlineRenderer;
  27757. })(BABYLON || (BABYLON = {}));
  27758. //# sourceMappingURL=babylon.outlineRenderer.js.map
  27759. var BABYLON;
  27760. (function (BABYLON) {
  27761. var MeshAssetTask = (function () {
  27762. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  27763. this.name = name;
  27764. this.meshesNames = meshesNames;
  27765. this.rootUrl = rootUrl;
  27766. this.sceneFilename = sceneFilename;
  27767. this.isCompleted = false;
  27768. }
  27769. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27770. var _this = this;
  27771. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  27772. _this.loadedMeshes = meshes;
  27773. _this.loadedParticleSystems = particleSystems;
  27774. _this.loadedSkeletons = skeletons;
  27775. _this.isCompleted = true;
  27776. if (_this.onSuccess) {
  27777. _this.onSuccess(_this);
  27778. }
  27779. onSuccess();
  27780. }, null, function () {
  27781. if (_this.onError) {
  27782. _this.onError(_this);
  27783. }
  27784. onError();
  27785. });
  27786. };
  27787. return MeshAssetTask;
  27788. })();
  27789. BABYLON.MeshAssetTask = MeshAssetTask;
  27790. var TextFileAssetTask = (function () {
  27791. function TextFileAssetTask(name, url) {
  27792. this.name = name;
  27793. this.url = url;
  27794. this.isCompleted = false;
  27795. }
  27796. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27797. var _this = this;
  27798. BABYLON.Tools.LoadFile(this.url, function (data) {
  27799. _this.text = data;
  27800. _this.isCompleted = true;
  27801. if (_this.onSuccess) {
  27802. _this.onSuccess(_this);
  27803. }
  27804. onSuccess();
  27805. }, null, scene.database, false, function () {
  27806. if (_this.onError) {
  27807. _this.onError(_this);
  27808. }
  27809. onError();
  27810. });
  27811. };
  27812. return TextFileAssetTask;
  27813. })();
  27814. BABYLON.TextFileAssetTask = TextFileAssetTask;
  27815. var BinaryFileAssetTask = (function () {
  27816. function BinaryFileAssetTask(name, url) {
  27817. this.name = name;
  27818. this.url = url;
  27819. this.isCompleted = false;
  27820. }
  27821. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27822. var _this = this;
  27823. BABYLON.Tools.LoadFile(this.url, function (data) {
  27824. _this.data = data;
  27825. _this.isCompleted = true;
  27826. if (_this.onSuccess) {
  27827. _this.onSuccess(_this);
  27828. }
  27829. onSuccess();
  27830. }, null, scene.database, true, function () {
  27831. if (_this.onError) {
  27832. _this.onError(_this);
  27833. }
  27834. onError();
  27835. });
  27836. };
  27837. return BinaryFileAssetTask;
  27838. })();
  27839. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  27840. var ImageAssetTask = (function () {
  27841. function ImageAssetTask(name, url) {
  27842. this.name = name;
  27843. this.url = url;
  27844. this.isCompleted = false;
  27845. }
  27846. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27847. var _this = this;
  27848. var img = new Image();
  27849. img.onload = function () {
  27850. _this.image = img;
  27851. _this.isCompleted = true;
  27852. if (_this.onSuccess) {
  27853. _this.onSuccess(_this);
  27854. }
  27855. onSuccess();
  27856. };
  27857. img.onerror = function () {
  27858. if (_this.onError) {
  27859. _this.onError(_this);
  27860. }
  27861. onError();
  27862. };
  27863. img.src = this.url;
  27864. };
  27865. return ImageAssetTask;
  27866. })();
  27867. BABYLON.ImageAssetTask = ImageAssetTask;
  27868. var TextureAssetTask = (function () {
  27869. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  27870. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27871. this.name = name;
  27872. this.url = url;
  27873. this.noMipmap = noMipmap;
  27874. this.invertY = invertY;
  27875. this.samplingMode = samplingMode;
  27876. this.isCompleted = false;
  27877. }
  27878. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27879. var _this = this;
  27880. var onload = function () {
  27881. _this.isCompleted = true;
  27882. if (_this.onSuccess) {
  27883. _this.onSuccess(_this);
  27884. }
  27885. onSuccess();
  27886. };
  27887. var onerror = function () {
  27888. if (_this.onError) {
  27889. _this.onError(_this);
  27890. }
  27891. onError();
  27892. };
  27893. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  27894. };
  27895. return TextureAssetTask;
  27896. })();
  27897. BABYLON.TextureAssetTask = TextureAssetTask;
  27898. var AssetsManager = (function () {
  27899. function AssetsManager(scene) {
  27900. this._tasks = new Array();
  27901. this._waitingTasksCount = 0;
  27902. this.useDefaultLoadingScreen = true;
  27903. this._scene = scene;
  27904. }
  27905. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  27906. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  27907. this._tasks.push(task);
  27908. return task;
  27909. };
  27910. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  27911. var task = new TextFileAssetTask(taskName, url);
  27912. this._tasks.push(task);
  27913. return task;
  27914. };
  27915. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  27916. var task = new BinaryFileAssetTask(taskName, url);
  27917. this._tasks.push(task);
  27918. return task;
  27919. };
  27920. AssetsManager.prototype.addImageTask = function (taskName, url) {
  27921. var task = new ImageAssetTask(taskName, url);
  27922. this._tasks.push(task);
  27923. return task;
  27924. };
  27925. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  27926. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27927. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  27928. this._tasks.push(task);
  27929. return task;
  27930. };
  27931. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  27932. this._waitingTasksCount--;
  27933. if (this._waitingTasksCount === 0) {
  27934. if (this.onFinish) {
  27935. this.onFinish(this._tasks);
  27936. }
  27937. this._scene.getEngine().hideLoadingUI();
  27938. }
  27939. };
  27940. AssetsManager.prototype._runTask = function (task) {
  27941. var _this = this;
  27942. task.run(this._scene, function () {
  27943. if (_this.onTaskSuccess) {
  27944. _this.onTaskSuccess(task);
  27945. }
  27946. _this._decreaseWaitingTasksCount();
  27947. }, function () {
  27948. if (_this.onTaskError) {
  27949. _this.onTaskError(task);
  27950. }
  27951. _this._decreaseWaitingTasksCount();
  27952. });
  27953. };
  27954. AssetsManager.prototype.reset = function () {
  27955. this._tasks = new Array();
  27956. return this;
  27957. };
  27958. AssetsManager.prototype.load = function () {
  27959. this._waitingTasksCount = this._tasks.length;
  27960. if (this._waitingTasksCount === 0) {
  27961. if (this.onFinish) {
  27962. this.onFinish(this._tasks);
  27963. }
  27964. return this;
  27965. }
  27966. if (this.useDefaultLoadingScreen) {
  27967. this._scene.getEngine().displayLoadingUI();
  27968. }
  27969. for (var index = 0; index < this._tasks.length; index++) {
  27970. var task = this._tasks[index];
  27971. this._runTask(task);
  27972. }
  27973. return this;
  27974. };
  27975. return AssetsManager;
  27976. })();
  27977. BABYLON.AssetsManager = AssetsManager;
  27978. })(BABYLON || (BABYLON = {}));
  27979. //# sourceMappingURL=babylon.assetsManager.js.map
  27980. var __extends = this.__extends || function (d, b) {
  27981. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27982. function __() { this.constructor = d; }
  27983. __.prototype = b.prototype;
  27984. d.prototype = new __();
  27985. };
  27986. var BABYLON;
  27987. (function (BABYLON) {
  27988. var VRDeviceOrientationCamera = (function (_super) {
  27989. __extends(VRDeviceOrientationCamera, _super);
  27990. function VRDeviceOrientationCamera(name, position, scene) {
  27991. _super.call(this, name, position, scene);
  27992. this._alpha = 0;
  27993. this._beta = 0;
  27994. this._gamma = 0;
  27995. }
  27996. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  27997. this._alpha = +evt.alpha | 0;
  27998. this._beta = +evt.beta | 0;
  27999. this._gamma = +evt.gamma | 0;
  28000. if (this._gamma < 0) {
  28001. this._gamma = 90 + this._gamma;
  28002. }
  28003. else {
  28004. // Incline it in the correct angle.
  28005. this._gamma = 270 - this._gamma;
  28006. }
  28007. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28008. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28009. this.rotation.z = this._beta / 180.0 * Math.PI;
  28010. };
  28011. return VRDeviceOrientationCamera;
  28012. })(BABYLON.VRCamera);
  28013. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  28014. })(BABYLON || (BABYLON = {}));
  28015. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28016. var __extends = this.__extends || function (d, b) {
  28017. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28018. function __() { this.constructor = d; }
  28019. __.prototype = b.prototype;
  28020. d.prototype = new __();
  28021. };
  28022. var BABYLON;
  28023. (function (BABYLON) {
  28024. var WebVRCamera = (function (_super) {
  28025. __extends(WebVRCamera, _super);
  28026. function WebVRCamera(name, position, scene) {
  28027. _super.call(this, name, position, scene);
  28028. this._hmdDevice = null;
  28029. this._sensorDevice = null;
  28030. this._cacheState = null;
  28031. this._cacheQuaternion = new BABYLON.Quaternion();
  28032. this._cacheRotation = BABYLON.Vector3.Zero();
  28033. this._vrEnabled = false;
  28034. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28035. }
  28036. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  28037. var size = devices.length;
  28038. var i = 0;
  28039. // Reset devices.
  28040. this._sensorDevice = null;
  28041. this._hmdDevice = null;
  28042. // Search for a HmdDevice.
  28043. while (i < size && this._hmdDevice === null) {
  28044. if (devices[i] instanceof HMDVRDevice) {
  28045. this._hmdDevice = devices[i];
  28046. }
  28047. i++;
  28048. }
  28049. i = 0;
  28050. while (i < size && this._sensorDevice === null) {
  28051. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28052. this._sensorDevice = devices[i];
  28053. }
  28054. i++;
  28055. }
  28056. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28057. };
  28058. WebVRCamera.prototype._update = function () {
  28059. if (this._vrEnabled) {
  28060. this._cacheState = this._sensorDevice.getState();
  28061. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28062. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28063. this.rotation.x = -this._cacheRotation.z;
  28064. this.rotation.y = -this._cacheRotation.y;
  28065. this.rotation.z = this._cacheRotation.x;
  28066. }
  28067. _super.prototype._update.call(this);
  28068. };
  28069. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  28070. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28071. if (navigator.getVRDevices) {
  28072. navigator.getVRDevices().then(this._getWebVRDevices);
  28073. }
  28074. else if (navigator.mozGetVRDevices) {
  28075. navigator.mozGetVRDevices(this._getWebVRDevices);
  28076. }
  28077. };
  28078. WebVRCamera.prototype.detachControl = function (element) {
  28079. _super.prototype.detachControl.call(this, element);
  28080. this._vrEnabled = false;
  28081. };
  28082. return WebVRCamera;
  28083. })(BABYLON.VRCamera);
  28084. BABYLON.WebVRCamera = WebVRCamera;
  28085. })(BABYLON || (BABYLON = {}));
  28086. //# sourceMappingURL=babylon.webVRCamera.js.map
  28087. var __extends = this.__extends || function (d, b) {
  28088. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28089. function __() { this.constructor = d; }
  28090. __.prototype = b.prototype;
  28091. d.prototype = new __();
  28092. };
  28093. var BABYLON;
  28094. (function (BABYLON) {
  28095. // Standard optimizations
  28096. var SceneOptimization = (function () {
  28097. function SceneOptimization(priority) {
  28098. if (priority === void 0) { priority = 0; }
  28099. this.priority = priority;
  28100. this.apply = function (scene) {
  28101. return true; // Return true if everything that can be done was applied
  28102. };
  28103. }
  28104. return SceneOptimization;
  28105. })();
  28106. BABYLON.SceneOptimization = SceneOptimization;
  28107. var TextureOptimization = (function (_super) {
  28108. __extends(TextureOptimization, _super);
  28109. function TextureOptimization(priority, maximumSize) {
  28110. var _this = this;
  28111. if (priority === void 0) { priority = 0; }
  28112. if (maximumSize === void 0) { maximumSize = 1024; }
  28113. _super.call(this, priority);
  28114. this.priority = priority;
  28115. this.maximumSize = maximumSize;
  28116. this.apply = function (scene) {
  28117. var allDone = true;
  28118. for (var index = 0; index < scene.textures.length; index++) {
  28119. var texture = scene.textures[index];
  28120. if (!texture.canRescale) {
  28121. continue;
  28122. }
  28123. var currentSize = texture.getSize();
  28124. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28125. if (maxDimension > _this.maximumSize) {
  28126. texture.scale(0.5);
  28127. allDone = false;
  28128. }
  28129. }
  28130. return allDone;
  28131. };
  28132. }
  28133. return TextureOptimization;
  28134. })(SceneOptimization);
  28135. BABYLON.TextureOptimization = TextureOptimization;
  28136. var HardwareScalingOptimization = (function (_super) {
  28137. __extends(HardwareScalingOptimization, _super);
  28138. function HardwareScalingOptimization(priority, maximumScale) {
  28139. var _this = this;
  28140. if (priority === void 0) { priority = 0; }
  28141. if (maximumScale === void 0) { maximumScale = 2; }
  28142. _super.call(this, priority);
  28143. this.priority = priority;
  28144. this.maximumScale = maximumScale;
  28145. this._currentScale = 1;
  28146. this.apply = function (scene) {
  28147. _this._currentScale++;
  28148. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28149. return _this._currentScale >= _this.maximumScale;
  28150. };
  28151. }
  28152. return HardwareScalingOptimization;
  28153. })(SceneOptimization);
  28154. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28155. var ShadowsOptimization = (function (_super) {
  28156. __extends(ShadowsOptimization, _super);
  28157. function ShadowsOptimization() {
  28158. _super.apply(this, arguments);
  28159. this.apply = function (scene) {
  28160. scene.shadowsEnabled = false;
  28161. return true;
  28162. };
  28163. }
  28164. return ShadowsOptimization;
  28165. })(SceneOptimization);
  28166. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28167. var PostProcessesOptimization = (function (_super) {
  28168. __extends(PostProcessesOptimization, _super);
  28169. function PostProcessesOptimization() {
  28170. _super.apply(this, arguments);
  28171. this.apply = function (scene) {
  28172. scene.postProcessesEnabled = false;
  28173. return true;
  28174. };
  28175. }
  28176. return PostProcessesOptimization;
  28177. })(SceneOptimization);
  28178. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28179. var LensFlaresOptimization = (function (_super) {
  28180. __extends(LensFlaresOptimization, _super);
  28181. function LensFlaresOptimization() {
  28182. _super.apply(this, arguments);
  28183. this.apply = function (scene) {
  28184. scene.lensFlaresEnabled = false;
  28185. return true;
  28186. };
  28187. }
  28188. return LensFlaresOptimization;
  28189. })(SceneOptimization);
  28190. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28191. var ParticlesOptimization = (function (_super) {
  28192. __extends(ParticlesOptimization, _super);
  28193. function ParticlesOptimization() {
  28194. _super.apply(this, arguments);
  28195. this.apply = function (scene) {
  28196. scene.particlesEnabled = false;
  28197. return true;
  28198. };
  28199. }
  28200. return ParticlesOptimization;
  28201. })(SceneOptimization);
  28202. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28203. var RenderTargetsOptimization = (function (_super) {
  28204. __extends(RenderTargetsOptimization, _super);
  28205. function RenderTargetsOptimization() {
  28206. _super.apply(this, arguments);
  28207. this.apply = function (scene) {
  28208. scene.renderTargetsEnabled = false;
  28209. return true;
  28210. };
  28211. }
  28212. return RenderTargetsOptimization;
  28213. })(SceneOptimization);
  28214. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28215. var MergeMeshesOptimization = (function (_super) {
  28216. __extends(MergeMeshesOptimization, _super);
  28217. function MergeMeshesOptimization() {
  28218. var _this = this;
  28219. _super.apply(this, arguments);
  28220. this._canBeMerged = function (abstractMesh) {
  28221. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28222. return false;
  28223. }
  28224. var mesh = abstractMesh;
  28225. if (!mesh.isVisible || !mesh.isEnabled()) {
  28226. return false;
  28227. }
  28228. if (mesh.instances.length > 0) {
  28229. return false;
  28230. }
  28231. if (mesh.skeleton || mesh.hasLODLevels) {
  28232. return false;
  28233. }
  28234. return true;
  28235. };
  28236. this.apply = function (scene) {
  28237. var globalPool = scene.meshes.slice(0);
  28238. var globalLength = globalPool.length;
  28239. for (var index = 0; index < globalLength; index++) {
  28240. var currentPool = new Array();
  28241. var current = globalPool[index];
  28242. // Checks
  28243. if (!_this._canBeMerged(current)) {
  28244. continue;
  28245. }
  28246. currentPool.push(current);
  28247. // Find compatible meshes
  28248. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28249. var otherMesh = globalPool[subIndex];
  28250. if (!_this._canBeMerged(otherMesh)) {
  28251. continue;
  28252. }
  28253. if (otherMesh.material !== current.material) {
  28254. continue;
  28255. }
  28256. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28257. continue;
  28258. }
  28259. currentPool.push(otherMesh);
  28260. globalLength--;
  28261. globalPool.splice(subIndex, 1);
  28262. subIndex--;
  28263. }
  28264. if (currentPool.length < 2) {
  28265. continue;
  28266. }
  28267. // Merge meshes
  28268. BABYLON.Mesh.MergeMeshes(currentPool);
  28269. }
  28270. return true;
  28271. };
  28272. }
  28273. return MergeMeshesOptimization;
  28274. })(SceneOptimization);
  28275. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28276. // Options
  28277. var SceneOptimizerOptions = (function () {
  28278. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28279. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28280. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28281. this.targetFrameRate = targetFrameRate;
  28282. this.trackerDuration = trackerDuration;
  28283. this.optimizations = new Array();
  28284. }
  28285. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28286. var result = new SceneOptimizerOptions(targetFrameRate);
  28287. var priority = 0;
  28288. result.optimizations.push(new MergeMeshesOptimization(priority));
  28289. result.optimizations.push(new ShadowsOptimization(priority));
  28290. result.optimizations.push(new LensFlaresOptimization(priority));
  28291. // Next priority
  28292. priority++;
  28293. result.optimizations.push(new PostProcessesOptimization(priority));
  28294. result.optimizations.push(new ParticlesOptimization(priority));
  28295. // Next priority
  28296. priority++;
  28297. result.optimizations.push(new TextureOptimization(priority, 1024));
  28298. return result;
  28299. };
  28300. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28301. var result = new SceneOptimizerOptions(targetFrameRate);
  28302. var priority = 0;
  28303. result.optimizations.push(new MergeMeshesOptimization(priority));
  28304. result.optimizations.push(new ShadowsOptimization(priority));
  28305. result.optimizations.push(new LensFlaresOptimization(priority));
  28306. // Next priority
  28307. priority++;
  28308. result.optimizations.push(new PostProcessesOptimization(priority));
  28309. result.optimizations.push(new ParticlesOptimization(priority));
  28310. // Next priority
  28311. priority++;
  28312. result.optimizations.push(new TextureOptimization(priority, 512));
  28313. // Next priority
  28314. priority++;
  28315. result.optimizations.push(new RenderTargetsOptimization(priority));
  28316. // Next priority
  28317. priority++;
  28318. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28319. return result;
  28320. };
  28321. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28322. var result = new SceneOptimizerOptions(targetFrameRate);
  28323. var priority = 0;
  28324. result.optimizations.push(new MergeMeshesOptimization(priority));
  28325. result.optimizations.push(new ShadowsOptimization(priority));
  28326. result.optimizations.push(new LensFlaresOptimization(priority));
  28327. // Next priority
  28328. priority++;
  28329. result.optimizations.push(new PostProcessesOptimization(priority));
  28330. result.optimizations.push(new ParticlesOptimization(priority));
  28331. // Next priority
  28332. priority++;
  28333. result.optimizations.push(new TextureOptimization(priority, 256));
  28334. // Next priority
  28335. priority++;
  28336. result.optimizations.push(new RenderTargetsOptimization(priority));
  28337. // Next priority
  28338. priority++;
  28339. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28340. return result;
  28341. };
  28342. return SceneOptimizerOptions;
  28343. })();
  28344. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28345. // Scene optimizer tool
  28346. var SceneOptimizer = (function () {
  28347. function SceneOptimizer() {
  28348. }
  28349. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28350. // TODO: add an epsilon
  28351. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28352. if (onSuccess) {
  28353. onSuccess();
  28354. }
  28355. return;
  28356. }
  28357. // Apply current level of optimizations
  28358. var allDone = true;
  28359. var noOptimizationApplied = true;
  28360. for (var index = 0; index < options.optimizations.length; index++) {
  28361. var optimization = options.optimizations[index];
  28362. if (optimization.priority === currentPriorityLevel) {
  28363. noOptimizationApplied = false;
  28364. allDone = allDone && optimization.apply(scene);
  28365. }
  28366. }
  28367. // If no optimization was applied, this is a failure :(
  28368. if (noOptimizationApplied) {
  28369. if (onFailure) {
  28370. onFailure();
  28371. }
  28372. return;
  28373. }
  28374. // If all optimizations were done, move to next level
  28375. if (allDone) {
  28376. currentPriorityLevel++;
  28377. }
  28378. // Let's the system running for a specific amount of time before checking FPS
  28379. scene.executeWhenReady(function () {
  28380. setTimeout(function () {
  28381. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28382. }, options.trackerDuration);
  28383. });
  28384. };
  28385. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28386. if (!options) {
  28387. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28388. }
  28389. // Let's the system running for a specific amount of time before checking FPS
  28390. scene.executeWhenReady(function () {
  28391. setTimeout(function () {
  28392. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28393. }, options.trackerDuration);
  28394. });
  28395. };
  28396. return SceneOptimizer;
  28397. })();
  28398. BABYLON.SceneOptimizer = SceneOptimizer;
  28399. })(BABYLON || (BABYLON = {}));
  28400. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28401. var BABYLON;
  28402. (function (BABYLON) {
  28403. var Internals;
  28404. (function (Internals) {
  28405. var MeshLODLevel = (function () {
  28406. function MeshLODLevel(distance, mesh) {
  28407. this.distance = distance;
  28408. this.mesh = mesh;
  28409. }
  28410. return MeshLODLevel;
  28411. })();
  28412. Internals.MeshLODLevel = MeshLODLevel;
  28413. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28414. })(BABYLON || (BABYLON = {}));
  28415. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28416. var BABYLON;
  28417. (function (BABYLON) {
  28418. var AudioEngine = (function () {
  28419. function AudioEngine() {
  28420. this._audioContext = null;
  28421. this._audioContextInitialized = false;
  28422. this.canUseWebAudio = false;
  28423. this.WarnedWebAudioUnsupported = false;
  28424. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28425. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28426. this.canUseWebAudio = true;
  28427. }
  28428. }
  28429. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28430. get: function () {
  28431. if (!this._audioContextInitialized) {
  28432. this._initializeAudioContext();
  28433. }
  28434. return this._audioContext;
  28435. },
  28436. enumerable: true,
  28437. configurable: true
  28438. });
  28439. AudioEngine.prototype._initializeAudioContext = function () {
  28440. try {
  28441. if (this.canUseWebAudio) {
  28442. this._audioContext = new AudioContext();
  28443. // create a global volume gain node
  28444. this.masterGain = this._audioContext.createGain();
  28445. this.masterGain.gain.value = 1;
  28446. this.masterGain.connect(this._audioContext.destination);
  28447. this._audioContextInitialized = true;
  28448. }
  28449. }
  28450. catch (e) {
  28451. this.canUseWebAudio = false;
  28452. BABYLON.Tools.Error("Web Audio: " + e.message);
  28453. }
  28454. };
  28455. AudioEngine.prototype.dispose = function () {
  28456. if (this.canUseWebAudio && this._audioContextInitialized) {
  28457. if (this._connectedAnalyser) {
  28458. this._connectedAnalyser.stopDebugCanvas();
  28459. this._connectedAnalyser.dispose();
  28460. this.masterGain.disconnect();
  28461. this.masterGain.connect(this._audioContext.destination);
  28462. this._connectedAnalyser = null;
  28463. }
  28464. this.masterGain.gain.value = 1;
  28465. }
  28466. this.WarnedWebAudioUnsupported = false;
  28467. };
  28468. AudioEngine.prototype.getGlobalVolume = function () {
  28469. if (this.canUseWebAudio && this._audioContextInitialized) {
  28470. return this.masterGain.gain.value;
  28471. }
  28472. else {
  28473. return -1;
  28474. }
  28475. };
  28476. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28477. if (this.canUseWebAudio && this._audioContextInitialized) {
  28478. this.masterGain.gain.value = newVolume;
  28479. }
  28480. };
  28481. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28482. if (this._connectedAnalyser) {
  28483. this._connectedAnalyser.stopDebugCanvas();
  28484. }
  28485. if (this.canUseWebAudio && this._audioContextInitialized) {
  28486. this._connectedAnalyser = analyser;
  28487. this.masterGain.disconnect();
  28488. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28489. }
  28490. };
  28491. return AudioEngine;
  28492. })();
  28493. BABYLON.AudioEngine = AudioEngine;
  28494. })(BABYLON || (BABYLON = {}));
  28495. //# sourceMappingURL=babylon.audioEngine.js.map
  28496. var BABYLON;
  28497. (function (BABYLON) {
  28498. var Sound = (function () {
  28499. /**
  28500. * Create a sound and attach it to a scene
  28501. * @param name Name of your sound
  28502. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28503. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28504. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28505. */
  28506. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28507. var _this = this;
  28508. this.autoplay = false;
  28509. this.loop = false;
  28510. this.useCustomAttenuation = false;
  28511. this.spatialSound = false;
  28512. this.refDistance = 1;
  28513. this.rolloffFactor = 1;
  28514. this.maxDistance = 100;
  28515. this.distanceModel = "linear";
  28516. this._panningModel = "equalpower";
  28517. this._playbackRate = 1;
  28518. this._startTime = 0;
  28519. this._startOffset = 0;
  28520. this._position = BABYLON.Vector3.Zero();
  28521. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28522. this._volume = 1;
  28523. this._isLoaded = false;
  28524. this._isReadyToPlay = false;
  28525. this.isPlaying = false;
  28526. this.isPaused = false;
  28527. this._isDirectional = false;
  28528. // Used if you'd like to create a directional sound.
  28529. // If not set, the sound will be omnidirectional
  28530. this._coneInnerAngle = 360;
  28531. this._coneOuterAngle = 360;
  28532. this._coneOuterGain = 0;
  28533. this.name = name;
  28534. this._scene = scene;
  28535. this._readyToPlayCallback = readyToPlayCallback;
  28536. // Default custom attenuation function is a linear attenuation
  28537. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28538. if (currentDistance < maxDistance) {
  28539. return currentVolume * (1 - currentDistance / maxDistance);
  28540. }
  28541. else {
  28542. return 0;
  28543. }
  28544. };
  28545. if (options) {
  28546. this.autoplay = options.autoplay || false;
  28547. this.loop = options.loop || false;
  28548. // if volume === 0, we need another way to check this option
  28549. if (options.volume !== undefined) {
  28550. this._volume = options.volume;
  28551. }
  28552. this.spatialSound = options.spatialSound || false;
  28553. this.maxDistance = options.maxDistance || 100;
  28554. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28555. this.rolloffFactor = options.rolloffFactor || 1;
  28556. this.refDistance = options.refDistance || 1;
  28557. this.distanceModel = options.distanceModel || "linear";
  28558. this._playbackRate = options.playbackRate || 1;
  28559. }
  28560. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28561. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28562. this._soundGain.gain.value = this._volume;
  28563. this._inputAudioNode = this._soundGain;
  28564. this._ouputAudioNode = this._soundGain;
  28565. if (this.spatialSound) {
  28566. this._createSpatialParameters();
  28567. }
  28568. this._scene.mainSoundTrack.AddSound(this);
  28569. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28570. if (urlOrArrayBuffer) {
  28571. // If it's an URL
  28572. if (typeof (urlOrArrayBuffer) === "string") {
  28573. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  28574. }
  28575. else {
  28576. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28577. this._soundLoaded(urlOrArrayBuffer);
  28578. }
  28579. else {
  28580. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28581. }
  28582. }
  28583. }
  28584. }
  28585. else {
  28586. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28587. this._scene.mainSoundTrack.AddSound(this);
  28588. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28589. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28590. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28591. }
  28592. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28593. if (this._readyToPlayCallback) {
  28594. window.setTimeout(function () {
  28595. _this._readyToPlayCallback();
  28596. }, 1000);
  28597. }
  28598. }
  28599. }
  28600. Sound.prototype.dispose = function () {
  28601. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28602. if (this.isPlaying) {
  28603. this.stop();
  28604. }
  28605. this._isReadyToPlay = false;
  28606. if (this.soundTrackId === -1) {
  28607. this._scene.mainSoundTrack.RemoveSound(this);
  28608. }
  28609. else {
  28610. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28611. }
  28612. if (this._soundGain) {
  28613. this._soundGain.disconnect();
  28614. this._soundGain = null;
  28615. }
  28616. if (this._soundPanner) {
  28617. this._soundPanner.disconnect();
  28618. this._soundPanner = null;
  28619. }
  28620. if (this._soundSource) {
  28621. this._soundSource.disconnect();
  28622. this._soundSource = null;
  28623. }
  28624. this._audioBuffer = null;
  28625. if (this._connectedMesh) {
  28626. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28627. this._connectedMesh = null;
  28628. }
  28629. }
  28630. };
  28631. Sound.prototype._soundLoaded = function (audioData) {
  28632. var _this = this;
  28633. this._isLoaded = true;
  28634. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28635. _this._audioBuffer = buffer;
  28636. _this._isReadyToPlay = true;
  28637. if (_this.autoplay) {
  28638. _this.play();
  28639. }
  28640. if (_this._readyToPlayCallback) {
  28641. _this._readyToPlayCallback();
  28642. }
  28643. }, function (error) { BABYLON.Tools.Error("Error while decoding audio data: " + error.err); });
  28644. };
  28645. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28646. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28647. this._audioBuffer = audioBuffer;
  28648. this._isReadyToPlay = true;
  28649. }
  28650. };
  28651. Sound.prototype.updateOptions = function (options) {
  28652. if (options) {
  28653. this.loop = options.loop || this.loop;
  28654. this.maxDistance = options.maxDistance || this.maxDistance;
  28655. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28656. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28657. this.refDistance = options.refDistance || this.refDistance;
  28658. this.distanceModel = options.distanceModel || this.distanceModel;
  28659. this._playbackRate = options.playbackRate || this._playbackRate;
  28660. }
  28661. };
  28662. Sound.prototype._createSpatialParameters = function () {
  28663. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28664. if (this._scene.headphone) {
  28665. this._panningModel = "HRTF";
  28666. }
  28667. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28668. if (this.useCustomAttenuation) {
  28669. // Tricks to disable in a way embedded Web Audio attenuation
  28670. this._soundPanner.distanceModel = "linear";
  28671. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28672. this._soundPanner.refDistance = 1;
  28673. this._soundPanner.rolloffFactor = 1;
  28674. this._soundPanner.panningModel = this._panningModel;
  28675. }
  28676. else {
  28677. this._soundPanner.distanceModel = this.distanceModel;
  28678. this._soundPanner.maxDistance = this.maxDistance;
  28679. this._soundPanner.refDistance = this.refDistance;
  28680. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28681. this._soundPanner.panningModel = this._panningModel;
  28682. }
  28683. this._soundPanner.connect(this._ouputAudioNode);
  28684. this._inputAudioNode = this._soundPanner;
  28685. }
  28686. };
  28687. Sound.prototype.switchPanningModelToHRTF = function () {
  28688. this._panningModel = "HRTF";
  28689. this._switchPanningModel();
  28690. };
  28691. Sound.prototype.switchPanningModelToEqualPower = function () {
  28692. this._panningModel = "equalpower";
  28693. this._switchPanningModel();
  28694. };
  28695. Sound.prototype._switchPanningModel = function () {
  28696. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28697. this._soundPanner.panningModel = this._panningModel;
  28698. }
  28699. };
  28700. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28701. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28702. this._ouputAudioNode.disconnect();
  28703. this._ouputAudioNode.connect(soundTrackAudioNode);
  28704. }
  28705. };
  28706. /**
  28707. * Transform this sound into a directional source
  28708. * @param coneInnerAngle Size of the inner cone in degree
  28709. * @param coneOuterAngle Size of the outer cone in degree
  28710. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  28711. */
  28712. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  28713. if (coneOuterAngle < coneInnerAngle) {
  28714. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  28715. return;
  28716. }
  28717. this._coneInnerAngle = coneInnerAngle;
  28718. this._coneOuterAngle = coneOuterAngle;
  28719. this._coneOuterGain = coneOuterGain;
  28720. this._isDirectional = true;
  28721. if (this.isPlaying && this.loop) {
  28722. this.stop();
  28723. this.play();
  28724. }
  28725. };
  28726. Sound.prototype.setPosition = function (newPosition) {
  28727. this._position = newPosition;
  28728. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28729. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28730. }
  28731. };
  28732. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  28733. this._localDirection = newLocalDirection;
  28734. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  28735. this._updateDirection();
  28736. }
  28737. };
  28738. Sound.prototype._updateDirection = function () {
  28739. var mat = this._connectedMesh.getWorldMatrix();
  28740. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  28741. direction.normalize();
  28742. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  28743. };
  28744. Sound.prototype.updateDistanceFromListener = function () {
  28745. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  28746. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  28747. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  28748. }
  28749. };
  28750. Sound.prototype.setAttenuationFunction = function (callback) {
  28751. this._customAttenuationFunction = callback;
  28752. };
  28753. /**
  28754. * Play the sound
  28755. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  28756. */
  28757. Sound.prototype.play = function (time) {
  28758. var _this = this;
  28759. if (this._isReadyToPlay && this._scene.audioEnabled) {
  28760. try {
  28761. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28762. if (!this._soundSource) {
  28763. if (this.spatialSound) {
  28764. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28765. if (this._isDirectional) {
  28766. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  28767. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  28768. this._soundPanner.coneOuterGain = this._coneOuterGain;
  28769. if (this._connectedMesh) {
  28770. this._updateDirection();
  28771. }
  28772. else {
  28773. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  28774. }
  28775. }
  28776. }
  28777. }
  28778. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  28779. this._soundSource.buffer = this._audioBuffer;
  28780. this._soundSource.connect(this._inputAudioNode);
  28781. this._soundSource.loop = this.loop;
  28782. this._soundSource.playbackRate.value = this._playbackRate;
  28783. this._startTime = startTime;
  28784. this._soundSource.onended = function () { _this._onended(); };
  28785. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  28786. this.isPlaying = true;
  28787. this.isPaused = false;
  28788. }
  28789. catch (ex) {
  28790. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  28791. }
  28792. }
  28793. };
  28794. Sound.prototype._onended = function () {
  28795. this.isPlaying = false;
  28796. if (this.onended) {
  28797. this.onended();
  28798. }
  28799. };
  28800. /**
  28801. * Stop the sound
  28802. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  28803. */
  28804. Sound.prototype.stop = function (time) {
  28805. if (this.isPlaying) {
  28806. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28807. this._soundSource.stop(stopTime);
  28808. this.isPlaying = false;
  28809. }
  28810. };
  28811. Sound.prototype.pause = function () {
  28812. if (this.isPlaying) {
  28813. this.stop(0);
  28814. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  28815. this.isPaused = true;
  28816. }
  28817. };
  28818. Sound.prototype.setVolume = function (newVolume, time) {
  28819. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  28820. if (time) {
  28821. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  28822. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  28823. }
  28824. else {
  28825. this._soundGain.gain.value = newVolume;
  28826. }
  28827. }
  28828. this._volume = newVolume;
  28829. };
  28830. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  28831. this._playbackRate = newPlaybackRate;
  28832. if (this.isPlaying) {
  28833. this._soundSource.playbackRate.value = this._playbackRate;
  28834. }
  28835. };
  28836. Sound.prototype.getVolume = function () {
  28837. return this._volume;
  28838. };
  28839. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  28840. var _this = this;
  28841. this._connectedMesh = meshToConnectTo;
  28842. if (!this.spatialSound) {
  28843. this._createSpatialParameters();
  28844. this.spatialSound = true;
  28845. if (this.isPlaying && this.loop) {
  28846. this.stop();
  28847. this.play();
  28848. }
  28849. }
  28850. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  28851. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  28852. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  28853. };
  28854. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  28855. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  28856. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  28857. this._updateDirection();
  28858. }
  28859. };
  28860. return Sound;
  28861. })();
  28862. BABYLON.Sound = Sound;
  28863. })(BABYLON || (BABYLON = {}));
  28864. //# sourceMappingURL=babylon.sound.js.map
  28865. var BABYLON;
  28866. (function (BABYLON) {
  28867. var SoundTrack = (function () {
  28868. function SoundTrack(scene, options) {
  28869. this.id = -1;
  28870. this._isMainTrack = false;
  28871. this._scene = scene;
  28872. this._audioEngine = BABYLON.Engine.audioEngine;
  28873. this.soundCollection = new Array();
  28874. if (this._audioEngine.canUseWebAudio) {
  28875. this._trackGain = this._audioEngine.audioContext.createGain();
  28876. this._trackGain.connect(this._audioEngine.masterGain);
  28877. if (options) {
  28878. if (options.volume) {
  28879. this._trackGain.gain.value = options.volume;
  28880. }
  28881. if (options.mainTrack) {
  28882. this._isMainTrack = options.mainTrack;
  28883. }
  28884. }
  28885. }
  28886. if (!this._isMainTrack) {
  28887. this._scene.soundTracks.push(this);
  28888. this.id = this._scene.soundTracks.length - 1;
  28889. }
  28890. }
  28891. SoundTrack.prototype.dispose = function () {
  28892. if (this._audioEngine.canUseWebAudio) {
  28893. if (this._connectedAnalyser) {
  28894. this._connectedAnalyser.stopDebugCanvas();
  28895. }
  28896. while (this.soundCollection.length) {
  28897. this.soundCollection[0].dispose();
  28898. }
  28899. this._trackGain.disconnect();
  28900. this._trackGain = null;
  28901. }
  28902. };
  28903. SoundTrack.prototype.AddSound = function (sound) {
  28904. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28905. sound.connectToSoundTrackAudioNode(this._trackGain);
  28906. }
  28907. if (sound.soundTrackId) {
  28908. if (sound.soundTrackId === -1) {
  28909. this._scene.mainSoundTrack.RemoveSound(sound);
  28910. }
  28911. else {
  28912. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  28913. }
  28914. }
  28915. this.soundCollection.push(sound);
  28916. sound.soundTrackId = this.id;
  28917. };
  28918. SoundTrack.prototype.RemoveSound = function (sound) {
  28919. var index = this.soundCollection.indexOf(sound);
  28920. if (index !== -1) {
  28921. this.soundCollection.splice(index, 1);
  28922. }
  28923. };
  28924. SoundTrack.prototype.setVolume = function (newVolume) {
  28925. if (this._audioEngine.canUseWebAudio) {
  28926. this._trackGain.gain.value = newVolume;
  28927. }
  28928. };
  28929. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  28930. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28931. for (var i = 0; i < this.soundCollection.length; i++) {
  28932. this.soundCollection[i].switchPanningModelToHRTF();
  28933. }
  28934. }
  28935. };
  28936. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  28937. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28938. for (var i = 0; i < this.soundCollection.length; i++) {
  28939. this.soundCollection[i].switchPanningModelToEqualPower();
  28940. }
  28941. }
  28942. };
  28943. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  28944. if (this._connectedAnalyser) {
  28945. this._connectedAnalyser.stopDebugCanvas();
  28946. }
  28947. this._connectedAnalyser = analyser;
  28948. if (this._audioEngine.canUseWebAudio) {
  28949. this._trackGain.disconnect();
  28950. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  28951. }
  28952. };
  28953. return SoundTrack;
  28954. })();
  28955. BABYLON.SoundTrack = SoundTrack;
  28956. })(BABYLON || (BABYLON = {}));
  28957. //# sourceMappingURL=babylon.soundtrack.js.map
  28958. var BABYLON;
  28959. (function (BABYLON) {
  28960. var DebugLayer = (function () {
  28961. function DebugLayer(scene) {
  28962. var _this = this;
  28963. this._transformationMatrix = BABYLON.Matrix.Identity();
  28964. this._enabled = false;
  28965. this._labelsEnabled = false;
  28966. this._displayStatistics = true;
  28967. this._displayTree = false;
  28968. this._displayLogs = false;
  28969. this._identityMatrix = BABYLON.Matrix.Identity();
  28970. this.axisRatio = 0.02;
  28971. this.accentColor = "orange";
  28972. this._scene = scene;
  28973. this._syncPositions = function () {
  28974. var engine = _this._scene.getEngine();
  28975. var canvasRect = engine.getRenderingCanvasClientRect();
  28976. if (_this._showUI) {
  28977. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28978. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28979. _this._statsDiv.style.width = "400px";
  28980. _this._statsDiv.style.height = "auto";
  28981. _this._statsSubsetDiv.style.maxHeight = "240px";
  28982. _this._optionsDiv.style.left = "0px";
  28983. _this._optionsDiv.style.top = "10px";
  28984. _this._optionsDiv.style.width = "200px";
  28985. _this._optionsDiv.style.height = "auto";
  28986. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28987. _this._logDiv.style.left = "0px";
  28988. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28989. _this._logDiv.style.width = "600px";
  28990. _this._logDiv.style.height = "160px";
  28991. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28992. _this._treeDiv.style.top = "10px";
  28993. _this._treeDiv.style.width = "300px";
  28994. _this._treeDiv.style.height = "auto";
  28995. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28996. }
  28997. _this._globalDiv.style.left = canvasRect.left + "px";
  28998. _this._globalDiv.style.top = canvasRect.top + "px";
  28999. _this._drawingCanvas.style.left = "0px";
  29000. _this._drawingCanvas.style.top = "0px";
  29001. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29002. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29003. var devicePixelRatio = window.devicePixelRatio || 1;
  29004. var context = _this._drawingContext;
  29005. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29006. context.mozBackingStorePixelRatio ||
  29007. context.msBackingStorePixelRatio ||
  29008. context.oBackingStorePixelRatio ||
  29009. context.backingStorePixelRatio || 1;
  29010. _this._ratio = devicePixelRatio / backingStoreRatio;
  29011. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29012. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29013. };
  29014. this._onCanvasClick = function (evt) {
  29015. _this._clickPosition = {
  29016. x: evt.clientX * _this._ratio,
  29017. y: evt.clientY * _this._ratio
  29018. };
  29019. };
  29020. this._syncUI = function () {
  29021. if (_this._showUI) {
  29022. if (_this._displayStatistics) {
  29023. _this._displayStats();
  29024. _this._statsDiv.style.display = "";
  29025. }
  29026. else {
  29027. _this._statsDiv.style.display = "none";
  29028. }
  29029. if (_this._displayLogs) {
  29030. _this._logDiv.style.display = "";
  29031. }
  29032. else {
  29033. _this._logDiv.style.display = "none";
  29034. }
  29035. if (_this._displayTree) {
  29036. _this._treeDiv.style.display = "";
  29037. if (_this._needToRefreshMeshesTree) {
  29038. _this._needToRefreshMeshesTree = false;
  29039. _this._refreshMeshesTreeContent();
  29040. }
  29041. }
  29042. else {
  29043. _this._treeDiv.style.display = "none";
  29044. }
  29045. }
  29046. };
  29047. this._syncData = function () {
  29048. if (_this._labelsEnabled || !_this._showUI) {
  29049. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29050. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29051. var engine = _this._scene.getEngine();
  29052. var viewport = _this._camera.viewport;
  29053. var globalViewport = viewport.toGlobal(engine);
  29054. // Meshes
  29055. var meshes = _this._camera.getActiveMeshes();
  29056. for (var index = 0; index < meshes.length; index++) {
  29057. var mesh = meshes.data[index];
  29058. var position = mesh.getBoundingInfo().boundingSphere.center;
  29059. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29060. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29061. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29062. }
  29063. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29064. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29065. }
  29066. }
  29067. // Cameras
  29068. var cameras = _this._scene.cameras;
  29069. for (index = 0; index < cameras.length; index++) {
  29070. var camera = cameras[index];
  29071. if (camera === _this._camera) {
  29072. continue;
  29073. }
  29074. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29075. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29076. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29077. _this._camera.detachControl(engine.getRenderingCanvas());
  29078. _this._camera = camera;
  29079. _this._camera.attachControl(engine.getRenderingCanvas());
  29080. }, function () { return "purple"; });
  29081. }
  29082. }
  29083. // Lights
  29084. var lights = _this._scene.lights;
  29085. for (index = 0; index < lights.length; index++) {
  29086. var light = lights[index];
  29087. if (light.position) {
  29088. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29089. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29090. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29091. light.setEnabled(!light.isEnabled());
  29092. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29093. }
  29094. }
  29095. }
  29096. }
  29097. _this._clickPosition = undefined;
  29098. };
  29099. }
  29100. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29101. while (this._treeSubsetDiv.hasChildNodes()) {
  29102. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29103. }
  29104. // Add meshes
  29105. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29106. sortedArray.sort(function (a, b) {
  29107. if (a.name === b.name) {
  29108. return 0;
  29109. }
  29110. return (a.name > b.name) ? 1 : -1;
  29111. });
  29112. for (var index = 0; index < sortedArray.length; index++) {
  29113. var mesh = sortedArray[index];
  29114. if (!mesh.isEnabled()) {
  29115. continue;
  29116. }
  29117. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29118. m.isVisible = element.checked;
  29119. }, mesh);
  29120. }
  29121. };
  29122. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29123. this._drawingContext.beginPath();
  29124. this._drawingContext.moveTo(zero.x, zero.y);
  29125. this._drawingContext.lineTo(unit.x, unit.y);
  29126. this._drawingContext.strokeStyle = color;
  29127. this._drawingContext.lineWidth = 4;
  29128. this._drawingContext.stroke();
  29129. this._drawingContext.font = "normal 14px Segoe UI";
  29130. this._drawingContext.fillStyle = color;
  29131. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29132. };
  29133. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29134. var position = mesh.getBoundingInfo().boundingSphere.center;
  29135. var worldMatrix = mesh.getWorldMatrix();
  29136. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29137. var unit = (unprojectedVector.subtract(position)).length();
  29138. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29139. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29140. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29141. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29142. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29143. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29144. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29145. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29146. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29147. };
  29148. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29149. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29150. this._drawingContext.font = "normal 12px Segoe UI";
  29151. var textMetrics = this._drawingContext.measureText(text);
  29152. var centerX = projectedPosition.x - textMetrics.width / 2;
  29153. var centerY = projectedPosition.y;
  29154. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29155. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29156. onClick();
  29157. }
  29158. this._drawingContext.beginPath();
  29159. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29160. this._drawingContext.fillStyle = getFillStyle();
  29161. this._drawingContext.globalAlpha = 0.5;
  29162. this._drawingContext.fill();
  29163. this._drawingContext.globalAlpha = 1.0;
  29164. this._drawingContext.strokeStyle = '#FFFFFF';
  29165. this._drawingContext.lineWidth = 1;
  29166. this._drawingContext.stroke();
  29167. this._drawingContext.fillStyle = "#FFFFFF";
  29168. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29169. this._drawingContext.beginPath();
  29170. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29171. this._drawingContext.fill();
  29172. }
  29173. };
  29174. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29175. if (!this._clickPosition) {
  29176. return false;
  29177. }
  29178. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29179. return false;
  29180. }
  29181. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29182. return false;
  29183. }
  29184. return true;
  29185. };
  29186. DebugLayer.prototype.isVisible = function () {
  29187. return this._enabled;
  29188. };
  29189. DebugLayer.prototype.hide = function () {
  29190. if (!this._enabled) {
  29191. return;
  29192. }
  29193. this._enabled = false;
  29194. var engine = this._scene.getEngine();
  29195. this._scene.unregisterBeforeRender(this._syncData);
  29196. this._scene.unregisterAfterRender(this._syncUI);
  29197. document.body.removeChild(this._globalDiv);
  29198. window.removeEventListener("resize", this._syncPositions);
  29199. this._scene.forceShowBoundingBoxes = false;
  29200. this._scene.forceWireframe = false;
  29201. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29202. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29203. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29204. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29205. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29206. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29207. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29208. this._scene.shadowsEnabled = true;
  29209. this._scene.particlesEnabled = true;
  29210. this._scene.postProcessesEnabled = true;
  29211. this._scene.collisionsEnabled = true;
  29212. this._scene.lightsEnabled = true;
  29213. this._scene.texturesEnabled = true;
  29214. this._scene.lensFlaresEnabled = true;
  29215. this._scene.proceduralTexturesEnabled = true;
  29216. this._scene.renderTargetsEnabled = true;
  29217. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29218. };
  29219. DebugLayer.prototype.show = function (showUI, camera) {
  29220. if (showUI === void 0) { showUI = true; }
  29221. if (camera === void 0) { camera = null; }
  29222. if (this._enabled) {
  29223. return;
  29224. }
  29225. this._enabled = true;
  29226. if (camera) {
  29227. this._camera = camera;
  29228. }
  29229. else {
  29230. this._camera = this._scene.activeCamera;
  29231. }
  29232. this._showUI = showUI;
  29233. var engine = this._scene.getEngine();
  29234. this._globalDiv = document.createElement("div");
  29235. document.body.appendChild(this._globalDiv);
  29236. this._generateDOMelements();
  29237. window.addEventListener("resize", this._syncPositions);
  29238. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29239. this._syncPositions();
  29240. this._scene.registerBeforeRender(this._syncData);
  29241. this._scene.registerAfterRender(this._syncUI);
  29242. };
  29243. DebugLayer.prototype._clearLabels = function () {
  29244. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29245. for (var index = 0; index < this._scene.meshes.length; index++) {
  29246. var mesh = this._scene.meshes[index];
  29247. mesh.renderOverlay = false;
  29248. }
  29249. };
  29250. DebugLayer.prototype._generateheader = function (root, text) {
  29251. var header = document.createElement("div");
  29252. header.innerHTML = text + "&nbsp;";
  29253. header.style.textAlign = "right";
  29254. header.style.width = "100%";
  29255. header.style.color = "white";
  29256. header.style.backgroundColor = "Black";
  29257. header.style.padding = "5px 5px 4px 0px";
  29258. header.style.marginLeft = "-5px";
  29259. header.style.fontWeight = "bold";
  29260. root.appendChild(header);
  29261. };
  29262. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29263. var label = document.createElement("label");
  29264. label.innerHTML = title;
  29265. label.style.color = color;
  29266. root.appendChild(label);
  29267. root.appendChild(document.createElement("br"));
  29268. };
  29269. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29270. if (tag === void 0) { tag = null; }
  29271. var label = document.createElement("label");
  29272. var boundingBoxesCheckbox = document.createElement("input");
  29273. boundingBoxesCheckbox.type = "checkbox";
  29274. boundingBoxesCheckbox.checked = initialState;
  29275. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29276. task(evt.target, tag);
  29277. });
  29278. label.appendChild(boundingBoxesCheckbox);
  29279. var container = document.createElement("span");
  29280. var leftPart = document.createElement("span");
  29281. var rightPart = document.createElement("span");
  29282. rightPart.style.cssFloat = "right";
  29283. leftPart.innerHTML = leftTitle;
  29284. rightPart.innerHTML = rightTitle;
  29285. rightPart.style.fontSize = "12px";
  29286. rightPart.style.maxWidth = "200px";
  29287. container.appendChild(leftPart);
  29288. container.appendChild(rightPart);
  29289. label.appendChild(container);
  29290. root.appendChild(label);
  29291. root.appendChild(document.createElement("br"));
  29292. };
  29293. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29294. if (tag === void 0) { tag = null; }
  29295. var label = document.createElement("label");
  29296. var checkBox = document.createElement("input");
  29297. checkBox.type = "checkbox";
  29298. checkBox.checked = initialState;
  29299. checkBox.addEventListener("change", function (evt) {
  29300. task(evt.target, tag);
  29301. });
  29302. label.appendChild(checkBox);
  29303. label.appendChild(document.createTextNode(title));
  29304. root.appendChild(label);
  29305. root.appendChild(document.createElement("br"));
  29306. };
  29307. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29308. if (tag === void 0) { tag = null; }
  29309. var button = document.createElement("button");
  29310. button.innerHTML = title;
  29311. button.style.height = "24px";
  29312. button.style.color = "#444444";
  29313. button.style.border = "1px solid white";
  29314. button.className = "debugLayerButton";
  29315. button.addEventListener("click", function (evt) {
  29316. task(evt.target, tag);
  29317. });
  29318. root.appendChild(button);
  29319. root.appendChild(document.createElement("br"));
  29320. };
  29321. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29322. if (tag === void 0) { tag = null; }
  29323. var label = document.createElement("label");
  29324. var boundingBoxesRadio = document.createElement("input");
  29325. boundingBoxesRadio.type = "radio";
  29326. boundingBoxesRadio.name = name;
  29327. boundingBoxesRadio.checked = initialState;
  29328. boundingBoxesRadio.addEventListener("change", function (evt) {
  29329. task(evt.target, tag);
  29330. });
  29331. label.appendChild(boundingBoxesRadio);
  29332. label.appendChild(document.createTextNode(title));
  29333. root.appendChild(label);
  29334. root.appendChild(document.createElement("br"));
  29335. };
  29336. DebugLayer.prototype._generateDOMelements = function () {
  29337. var _this = this;
  29338. this._globalDiv.id = "DebugLayer";
  29339. this._globalDiv.style.position = "absolute";
  29340. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29341. this._globalDiv.style.fontSize = "14px";
  29342. this._globalDiv.style.color = "white";
  29343. // Drawing canvas
  29344. this._drawingCanvas = document.createElement("canvas");
  29345. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29346. this._drawingCanvas.style.position = "absolute";
  29347. this._drawingCanvas.style.pointerEvents = "none";
  29348. this._drawingContext = this._drawingCanvas.getContext("2d");
  29349. this._globalDiv.appendChild(this._drawingCanvas);
  29350. if (this._showUI) {
  29351. var background = "rgba(128, 128, 128, 0.4)";
  29352. var border = "rgb(180, 180, 180) solid 1px";
  29353. // Stats
  29354. this._statsDiv = document.createElement("div");
  29355. this._statsDiv.id = "DebugLayerStats";
  29356. this._statsDiv.style.border = border;
  29357. this._statsDiv.style.position = "absolute";
  29358. this._statsDiv.style.background = background;
  29359. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29360. this._generateheader(this._statsDiv, "STATISTICS");
  29361. this._statsSubsetDiv = document.createElement("div");
  29362. this._statsSubsetDiv.style.paddingTop = "5px";
  29363. this._statsSubsetDiv.style.paddingBottom = "5px";
  29364. this._statsSubsetDiv.style.overflowY = "auto";
  29365. this._statsDiv.appendChild(this._statsSubsetDiv);
  29366. // Tree
  29367. this._treeDiv = document.createElement("div");
  29368. this._treeDiv.id = "DebugLayerTree";
  29369. this._treeDiv.style.border = border;
  29370. this._treeDiv.style.position = "absolute";
  29371. this._treeDiv.style.background = background;
  29372. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29373. this._treeDiv.style.display = "none";
  29374. this._generateheader(this._treeDiv, "MESHES TREE");
  29375. this._treeSubsetDiv = document.createElement("div");
  29376. this._treeSubsetDiv.style.paddingTop = "5px";
  29377. this._treeSubsetDiv.style.paddingRight = "5px";
  29378. this._treeSubsetDiv.style.overflowY = "auto";
  29379. this._treeSubsetDiv.style.maxHeight = "300px";
  29380. this._treeDiv.appendChild(this._treeSubsetDiv);
  29381. this._needToRefreshMeshesTree = true;
  29382. // Logs
  29383. this._logDiv = document.createElement("div");
  29384. this._logDiv.style.border = border;
  29385. this._logDiv.id = "DebugLayerLogs";
  29386. this._logDiv.style.position = "absolute";
  29387. this._logDiv.style.background = background;
  29388. this._logDiv.style.padding = "0px 0px 0px 5px";
  29389. this._logDiv.style.display = "none";
  29390. this._generateheader(this._logDiv, "LOGS");
  29391. this._logSubsetDiv = document.createElement("div");
  29392. this._logSubsetDiv.style.height = "127px";
  29393. this._logSubsetDiv.style.paddingTop = "5px";
  29394. this._logSubsetDiv.style.overflowY = "auto";
  29395. this._logSubsetDiv.style.fontSize = "12px";
  29396. this._logSubsetDiv.style.fontFamily = "consolas";
  29397. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29398. this._logDiv.appendChild(this._logSubsetDiv);
  29399. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29400. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29401. };
  29402. // Options
  29403. this._optionsDiv = document.createElement("div");
  29404. this._optionsDiv.id = "DebugLayerOptions";
  29405. this._optionsDiv.style.border = border;
  29406. this._optionsDiv.style.position = "absolute";
  29407. this._optionsDiv.style.background = background;
  29408. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29409. this._optionsDiv.style.overflowY = "auto";
  29410. this._generateheader(this._optionsDiv, "OPTIONS");
  29411. this._optionsSubsetDiv = document.createElement("div");
  29412. this._optionsSubsetDiv.style.paddingTop = "5px";
  29413. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29414. this._optionsSubsetDiv.style.overflowY = "auto";
  29415. this._optionsSubsetDiv.style.maxHeight = "200px";
  29416. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29417. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29418. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29419. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29420. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29421. _this._displayTree = element.checked;
  29422. _this._needToRefreshMeshesTree = true;
  29423. });
  29424. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29425. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29426. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29427. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29428. _this._labelsEnabled = element.checked;
  29429. if (!_this._labelsEnabled) {
  29430. _this._clearLabels();
  29431. }
  29432. });
  29433. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29434. if (element.checked) {
  29435. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29436. }
  29437. else {
  29438. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29439. }
  29440. });
  29441. ;
  29442. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29443. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29444. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29445. if (element.checked) {
  29446. _this._scene.forceWireframe = false;
  29447. _this._scene.forcePointsCloud = false;
  29448. }
  29449. });
  29450. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29451. if (element.checked) {
  29452. _this._scene.forceWireframe = true;
  29453. _this._scene.forcePointsCloud = false;
  29454. }
  29455. });
  29456. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29457. if (element.checked) {
  29458. _this._scene.forceWireframe = false;
  29459. _this._scene.forcePointsCloud = true;
  29460. }
  29461. });
  29462. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29463. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29464. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29465. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29466. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29467. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29468. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29469. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29470. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29471. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29472. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29473. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29474. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29475. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29476. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29477. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29478. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29479. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29480. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29481. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29482. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29483. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29484. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29485. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29486. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29487. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29488. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29489. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29490. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29491. if (element.checked) {
  29492. _this._scene.headphone = true;
  29493. }
  29494. });
  29495. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29496. if (element.checked) {
  29497. _this._scene.headphone = false;
  29498. }
  29499. });
  29500. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29501. _this._scene.audioEnabled = !element.checked;
  29502. });
  29503. }
  29504. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29505. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29506. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29507. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29508. this._globalDiv.appendChild(this._statsDiv);
  29509. this._globalDiv.appendChild(this._logDiv);
  29510. this._globalDiv.appendChild(this._optionsDiv);
  29511. this._globalDiv.appendChild(this._treeDiv);
  29512. }
  29513. };
  29514. DebugLayer.prototype._displayStats = function () {
  29515. var scene = this._scene;
  29516. var engine = scene.getEngine();
  29517. var glInfo = engine.getGlInfo();
  29518. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29519. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29520. + "<b>Count</b><br>"
  29521. + "Total meshes: " + scene.meshes.length + "<br>"
  29522. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29523. + "Total materials: " + scene.materials.length + "<br>"
  29524. + "Total textures: " + scene.textures.length + "<br>"
  29525. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29526. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29527. + "Active bones: " + scene.getActiveBones() + "<br>"
  29528. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29529. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  29530. + "<b>Duration</b><br>"
  29531. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29532. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29533. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29534. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29535. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29536. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29537. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  29538. + "</div>"
  29539. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29540. + "<b>Extensions</b><br>"
  29541. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29542. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29543. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29544. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  29545. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29546. + "<b>Caps.</b><br>"
  29547. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29548. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29549. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  29550. + "</div><br>"
  29551. + "<b>Info</b><br>"
  29552. + glInfo.version + "<br>"
  29553. + glInfo.renderer + "<br>";
  29554. if (this.customStatsFunction) {
  29555. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29556. }
  29557. };
  29558. return DebugLayer;
  29559. })();
  29560. BABYLON.DebugLayer = DebugLayer;
  29561. })(BABYLON || (BABYLON = {}));
  29562. //# sourceMappingURL=babylon.debugLayer.js.map
  29563. var __extends = this.__extends || function (d, b) {
  29564. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29565. function __() { this.constructor = d; }
  29566. __.prototype = b.prototype;
  29567. d.prototype = new __();
  29568. };
  29569. var BABYLON;
  29570. (function (BABYLON) {
  29571. var RawTexture = (function (_super) {
  29572. __extends(RawTexture, _super);
  29573. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29574. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29575. if (invertY === void 0) { invertY = false; }
  29576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29577. _super.call(this, null, scene, !generateMipMaps, invertY);
  29578. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29579. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29580. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29581. }
  29582. // Statics
  29583. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29584. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29585. if (invertY === void 0) { invertY = false; }
  29586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29587. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29588. };
  29589. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29590. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29591. if (invertY === void 0) { invertY = false; }
  29592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29593. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29594. };
  29595. RawTexture.CreateAlphaTexture = function (data, width, height, 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. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29600. };
  29601. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29602. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29603. if (invertY === void 0) { invertY = false; }
  29604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29605. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29606. };
  29607. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29608. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29609. if (invertY === void 0) { invertY = false; }
  29610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29611. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29612. };
  29613. return RawTexture;
  29614. })(BABYLON.Texture);
  29615. BABYLON.RawTexture = RawTexture;
  29616. })(BABYLON || (BABYLON = {}));
  29617. //# sourceMappingURL=babylon.rawTexture.js.map
  29618. var __extends = this.__extends || function (d, b) {
  29619. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29620. function __() { this.constructor = d; }
  29621. __.prototype = b.prototype;
  29622. d.prototype = new __();
  29623. };
  29624. var BABYLON;
  29625. (function (BABYLON) {
  29626. var IndexedVector2 = (function (_super) {
  29627. __extends(IndexedVector2, _super);
  29628. function IndexedVector2(original, index) {
  29629. _super.call(this, original.x, original.y);
  29630. this.index = index;
  29631. }
  29632. return IndexedVector2;
  29633. })(BABYLON.Vector2);
  29634. var PolygonPoints = (function () {
  29635. function PolygonPoints() {
  29636. this.elements = new Array();
  29637. }
  29638. PolygonPoints.prototype.add = function (originalPoints) {
  29639. var _this = this;
  29640. var result = new Array();
  29641. originalPoints.forEach(function (point) {
  29642. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  29643. var newPoint = new IndexedVector2(point, _this.elements.length);
  29644. result.push(newPoint);
  29645. _this.elements.push(newPoint);
  29646. }
  29647. });
  29648. return result;
  29649. };
  29650. PolygonPoints.prototype.computeBounds = function () {
  29651. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29652. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29653. this.elements.forEach(function (point) {
  29654. // x
  29655. if (point.x < lmin.x) {
  29656. lmin.x = point.x;
  29657. }
  29658. else if (point.x > lmax.x) {
  29659. lmax.x = point.x;
  29660. }
  29661. // y
  29662. if (point.y < lmin.y) {
  29663. lmin.y = point.y;
  29664. }
  29665. else if (point.y > lmax.y) {
  29666. lmax.y = point.y;
  29667. }
  29668. });
  29669. return {
  29670. min: lmin,
  29671. max: lmax,
  29672. width: lmax.x - lmin.x,
  29673. height: lmax.y - lmin.y
  29674. };
  29675. };
  29676. return PolygonPoints;
  29677. })();
  29678. var Polygon = (function () {
  29679. function Polygon() {
  29680. }
  29681. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29682. return [
  29683. new BABYLON.Vector2(xmin, ymin),
  29684. new BABYLON.Vector2(xmax, ymin),
  29685. new BABYLON.Vector2(xmax, ymax),
  29686. new BABYLON.Vector2(xmin, ymax)
  29687. ];
  29688. };
  29689. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29690. if (cx === void 0) { cx = 0; }
  29691. if (cy === void 0) { cy = 0; }
  29692. if (numberOfSides === void 0) { numberOfSides = 32; }
  29693. var result = new Array();
  29694. var angle = 0;
  29695. var increment = (Math.PI * 2) / numberOfSides;
  29696. for (var i = 0; i < numberOfSides; i++) {
  29697. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29698. angle -= increment;
  29699. }
  29700. return result;
  29701. };
  29702. Polygon.Parse = function (input) {
  29703. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29704. var i, result = [];
  29705. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29706. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  29707. }
  29708. return result;
  29709. };
  29710. Polygon.StartingAt = function (x, y) {
  29711. return BABYLON.Path2.StartingAt(x, y);
  29712. };
  29713. return Polygon;
  29714. })();
  29715. BABYLON.Polygon = Polygon;
  29716. var PolygonMeshBuilder = (function () {
  29717. function PolygonMeshBuilder(name, contours, scene) {
  29718. this._points = new PolygonPoints();
  29719. if (!("poly2tri" in window)) {
  29720. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  29721. }
  29722. this._name = name;
  29723. this._scene = scene;
  29724. var points;
  29725. if (contours instanceof BABYLON.Path2) {
  29726. points = contours.getPoints();
  29727. }
  29728. else {
  29729. points = contours;
  29730. }
  29731. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  29732. }
  29733. PolygonMeshBuilder.prototype.addHole = function (hole) {
  29734. this._swctx.addHole(this._points.add(hole));
  29735. return this;
  29736. };
  29737. PolygonMeshBuilder.prototype.build = function (updatable) {
  29738. if (updatable === void 0) { updatable = false; }
  29739. var result = new BABYLON.Mesh(this._name, this._scene);
  29740. var normals = [];
  29741. var positions = [];
  29742. var uvs = [];
  29743. var bounds = this._points.computeBounds();
  29744. this._points.elements.forEach(function (p) {
  29745. normals.push(0, 1.0, 0);
  29746. positions.push(p.x, 0, p.y);
  29747. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  29748. });
  29749. var indices = [];
  29750. this._swctx.triangulate();
  29751. this._swctx.getTriangles().forEach(function (triangle) {
  29752. triangle.getPoints().forEach(function (point) {
  29753. indices.push(point.index);
  29754. });
  29755. });
  29756. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  29757. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  29758. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  29759. result.setIndices(indices);
  29760. return result;
  29761. };
  29762. return PolygonMeshBuilder;
  29763. })();
  29764. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  29765. })(BABYLON || (BABYLON = {}));
  29766. //# sourceMappingURL=babylon.polygonMesh.js.map
  29767. var BABYLON;
  29768. (function (BABYLON) {
  29769. var SimplificationSettings = (function () {
  29770. function SimplificationSettings(quality, distance, optimizeMesh) {
  29771. this.quality = quality;
  29772. this.distance = distance;
  29773. this.optimizeMesh = optimizeMesh;
  29774. }
  29775. return SimplificationSettings;
  29776. })();
  29777. BABYLON.SimplificationSettings = SimplificationSettings;
  29778. var SimplificationQueue = (function () {
  29779. function SimplificationQueue() {
  29780. this.running = false;
  29781. this._simplificationArray = [];
  29782. }
  29783. SimplificationQueue.prototype.addTask = function (task) {
  29784. this._simplificationArray.push(task);
  29785. };
  29786. SimplificationQueue.prototype.executeNext = function () {
  29787. var task = this._simplificationArray.pop();
  29788. if (task) {
  29789. this.running = true;
  29790. this.runSimplification(task);
  29791. }
  29792. else {
  29793. this.running = false;
  29794. }
  29795. };
  29796. SimplificationQueue.prototype.runSimplification = function (task) {
  29797. var _this = this;
  29798. if (task.parallelProcessing) {
  29799. //parallel simplifier
  29800. task.settings.forEach(function (setting) {
  29801. var simplifier = _this.getSimplifier(task);
  29802. simplifier.simplify(setting, function (newMesh) {
  29803. task.mesh.addLODLevel(setting.distance, newMesh);
  29804. newMesh.isVisible = true;
  29805. //check if it is the last
  29806. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29807. //all done, run the success callback.
  29808. task.successCallback();
  29809. }
  29810. _this.executeNext();
  29811. });
  29812. });
  29813. }
  29814. else {
  29815. //single simplifier.
  29816. var simplifier = this.getSimplifier(task);
  29817. var runDecimation = function (setting, callback) {
  29818. simplifier.simplify(setting, function (newMesh) {
  29819. task.mesh.addLODLevel(setting.distance, newMesh);
  29820. newMesh.isVisible = true;
  29821. //run the next quality level
  29822. callback();
  29823. });
  29824. };
  29825. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29826. runDecimation(task.settings[loop.index], function () {
  29827. loop.executeNext();
  29828. });
  29829. }, function () {
  29830. //execution ended, run the success callback.
  29831. if (task.successCallback) {
  29832. task.successCallback();
  29833. }
  29834. _this.executeNext();
  29835. });
  29836. }
  29837. };
  29838. SimplificationQueue.prototype.getSimplifier = function (task) {
  29839. switch (task.simplificationType) {
  29840. case SimplificationType.QUADRATIC:
  29841. default:
  29842. return new QuadraticErrorSimplification(task.mesh);
  29843. }
  29844. };
  29845. return SimplificationQueue;
  29846. })();
  29847. BABYLON.SimplificationQueue = SimplificationQueue;
  29848. /**
  29849. * The implemented types of simplification.
  29850. * At the moment only Quadratic Error Decimation is implemented.
  29851. */
  29852. (function (SimplificationType) {
  29853. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29854. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29855. var SimplificationType = BABYLON.SimplificationType;
  29856. var DecimationTriangle = (function () {
  29857. function DecimationTriangle(vertices) {
  29858. this.vertices = vertices;
  29859. this.error = new Array(4);
  29860. this.deleted = false;
  29861. this.isDirty = false;
  29862. this.deletePending = false;
  29863. this.borderFactor = 0;
  29864. }
  29865. return DecimationTriangle;
  29866. })();
  29867. BABYLON.DecimationTriangle = DecimationTriangle;
  29868. var DecimationVertex = (function () {
  29869. function DecimationVertex(position, id) {
  29870. this.position = position;
  29871. this.id = id;
  29872. this.isBorder = true;
  29873. this.q = new QuadraticMatrix();
  29874. this.triangleCount = 0;
  29875. this.triangleStart = 0;
  29876. this.originalOffsets = [];
  29877. }
  29878. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29879. this.position.copyFrom(newPosition);
  29880. };
  29881. return DecimationVertex;
  29882. })();
  29883. BABYLON.DecimationVertex = DecimationVertex;
  29884. var QuadraticMatrix = (function () {
  29885. function QuadraticMatrix(data) {
  29886. this.data = new Array(10);
  29887. for (var i = 0; i < 10; ++i) {
  29888. if (data && data[i]) {
  29889. this.data[i] = data[i];
  29890. }
  29891. else {
  29892. this.data[i] = 0;
  29893. }
  29894. }
  29895. }
  29896. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29897. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  29898. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  29899. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29900. return det;
  29901. };
  29902. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29903. for (var i = 0; i < 10; ++i) {
  29904. this.data[i] += matrix.data[i];
  29905. }
  29906. };
  29907. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29908. for (var i = 0; i < 10; ++i) {
  29909. this.data[i] += data[i];
  29910. }
  29911. };
  29912. QuadraticMatrix.prototype.add = function (matrix) {
  29913. var m = new QuadraticMatrix();
  29914. for (var i = 0; i < 10; ++i) {
  29915. m.data[i] = this.data[i] + matrix.data[i];
  29916. }
  29917. return m;
  29918. };
  29919. QuadraticMatrix.FromData = function (a, b, c, d) {
  29920. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29921. };
  29922. //returning an array to avoid garbage collection
  29923. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29924. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29925. };
  29926. return QuadraticMatrix;
  29927. })();
  29928. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29929. var Reference = (function () {
  29930. function Reference(vertexId, triangleId) {
  29931. this.vertexId = vertexId;
  29932. this.triangleId = triangleId;
  29933. }
  29934. return Reference;
  29935. })();
  29936. BABYLON.Reference = Reference;
  29937. /**
  29938. * An implementation of the Quadratic Error simplification algorithm.
  29939. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29940. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29941. * @author RaananW
  29942. */
  29943. var QuadraticErrorSimplification = (function () {
  29944. function QuadraticErrorSimplification(_mesh) {
  29945. this._mesh = _mesh;
  29946. this.initialized = false;
  29947. this.syncIterations = 5000;
  29948. this.aggressiveness = 7;
  29949. this.decimationIterations = 100;
  29950. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29951. }
  29952. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29953. var _this = this;
  29954. this.initDecimatedMesh();
  29955. //iterating through the submeshes array, one after the other.
  29956. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29957. _this.initWithMesh(loop.index, function () {
  29958. _this.runDecimation(settings, loop.index, function () {
  29959. loop.executeNext();
  29960. });
  29961. }, settings.optimizeMesh);
  29962. }, function () {
  29963. setTimeout(function () {
  29964. successCallback(_this._reconstructedMesh);
  29965. }, 0);
  29966. });
  29967. };
  29968. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29969. var _this = this;
  29970. var gCount = 0;
  29971. triangle.vertices.forEach(function (vertex) {
  29972. var count = 0;
  29973. var vPos = vertex.position;
  29974. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29975. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29976. ++count;
  29977. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  29978. ++count;
  29979. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  29980. ++count;
  29981. if (count > 1) {
  29982. ++gCount;
  29983. }
  29984. ;
  29985. });
  29986. if (gCount > 1) {
  29987. console.log(triangle, gCount);
  29988. }
  29989. return gCount > 1;
  29990. };
  29991. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29992. var _this = this;
  29993. var targetCount = ~~(this.triangles.length * settings.quality);
  29994. var deletedTriangles = 0;
  29995. var triangleCount = this.triangles.length;
  29996. var iterationFunction = function (iteration, callback) {
  29997. setTimeout(function () {
  29998. if (iteration % 5 === 0) {
  29999. _this.updateMesh(iteration === 0);
  30000. }
  30001. for (var i = 0; i < _this.triangles.length; ++i) {
  30002. _this.triangles[i].isDirty = false;
  30003. }
  30004. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30005. var trianglesIterator = function (i) {
  30006. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30007. var t = _this.triangles[tIdx];
  30008. if (!t)
  30009. return;
  30010. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30011. return;
  30012. }
  30013. for (var j = 0; j < 3; ++j) {
  30014. if (t.error[j] < threshold) {
  30015. var deleted0 = [];
  30016. var deleted1 = [];
  30017. var v0 = t.vertices[j];
  30018. var v1 = t.vertices[(j + 1) % 3];
  30019. if (v0.isBorder !== v1.isBorder)
  30020. continue;
  30021. var p = BABYLON.Vector3.Zero();
  30022. var n = BABYLON.Vector3.Zero();
  30023. var uv = BABYLON.Vector2.Zero();
  30024. var color = new BABYLON.Color4(0, 0, 0, 1);
  30025. _this.calculateError(v0, v1, p, n, uv, color);
  30026. var delTr = [];
  30027. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30028. continue;
  30029. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30030. continue;
  30031. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30032. continue;
  30033. var uniqueArray = [];
  30034. delTr.forEach(function (deletedT) {
  30035. if (uniqueArray.indexOf(deletedT) === -1) {
  30036. deletedT.deletePending = true;
  30037. uniqueArray.push(deletedT);
  30038. }
  30039. });
  30040. if (uniqueArray.length % 2 != 0) {
  30041. continue;
  30042. }
  30043. v0.q = v1.q.add(v0.q);
  30044. v0.updatePosition(p);
  30045. var tStart = _this.references.length;
  30046. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30047. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30048. var tCount = _this.references.length - tStart;
  30049. if (tCount <= v0.triangleCount) {
  30050. if (tCount) {
  30051. for (var c = 0; c < tCount; c++) {
  30052. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30053. }
  30054. }
  30055. }
  30056. else {
  30057. v0.triangleStart = tStart;
  30058. }
  30059. v0.triangleCount = tCount;
  30060. break;
  30061. }
  30062. }
  30063. };
  30064. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30065. }, 0);
  30066. };
  30067. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30068. if (triangleCount - deletedTriangles <= targetCount)
  30069. loop.breakLoop();
  30070. else {
  30071. iterationFunction(loop.index, function () {
  30072. loop.executeNext();
  30073. });
  30074. }
  30075. }, function () {
  30076. setTimeout(function () {
  30077. //reconstruct this part of the mesh
  30078. _this.reconstructMesh(submeshIndex);
  30079. successCallback();
  30080. }, 0);
  30081. });
  30082. };
  30083. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30084. var _this = this;
  30085. this.vertices = [];
  30086. this.triangles = [];
  30087. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30088. var indices = this._mesh.getIndices();
  30089. var submesh = this._mesh.subMeshes[submeshIndex];
  30090. var findInVertices = function (positionToSearch) {
  30091. if (optimizeMesh) {
  30092. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30093. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30094. return _this.vertices[ii];
  30095. }
  30096. }
  30097. }
  30098. return null;
  30099. };
  30100. var vertexReferences = [];
  30101. var vertexInit = function (i) {
  30102. var offset = i + submesh.verticesStart;
  30103. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30104. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30105. vertex.originalOffsets.push(offset);
  30106. if (vertex.id == _this.vertices.length) {
  30107. _this.vertices.push(vertex);
  30108. }
  30109. vertexReferences.push(vertex.id);
  30110. };
  30111. //var totalVertices = mesh.getTotalVertices();
  30112. var totalVertices = submesh.verticesCount;
  30113. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30114. var indicesInit = function (i) {
  30115. var offset = (submesh.indexStart / 3) + i;
  30116. var pos = (offset * 3);
  30117. var i0 = indices[pos + 0];
  30118. var i1 = indices[pos + 1];
  30119. var i2 = indices[pos + 2];
  30120. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30121. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30122. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30123. var triangle = new DecimationTriangle([v0, v1, v2]);
  30124. triangle.originalOffset = pos;
  30125. _this.triangles.push(triangle);
  30126. };
  30127. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30128. _this.init(callback);
  30129. });
  30130. });
  30131. };
  30132. QuadraticErrorSimplification.prototype.init = function (callback) {
  30133. var _this = this;
  30134. var triangleInit1 = function (i) {
  30135. var t = _this.triangles[i];
  30136. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30137. for (var j = 0; j < 3; j++) {
  30138. 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))));
  30139. }
  30140. };
  30141. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30142. var triangleInit2 = function (i) {
  30143. var t = _this.triangles[i];
  30144. for (var j = 0; j < 3; ++j) {
  30145. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30146. }
  30147. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30148. };
  30149. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30150. _this.initialized = true;
  30151. callback();
  30152. });
  30153. });
  30154. };
  30155. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30156. var newTriangles = [];
  30157. var i;
  30158. for (i = 0; i < this.vertices.length; ++i) {
  30159. this.vertices[i].triangleCount = 0;
  30160. }
  30161. var t;
  30162. var j;
  30163. for (i = 0; i < this.triangles.length; ++i) {
  30164. if (!this.triangles[i].deleted) {
  30165. t = this.triangles[i];
  30166. for (j = 0; j < 3; ++j) {
  30167. t.vertices[j].triangleCount = 1;
  30168. }
  30169. newTriangles.push(t);
  30170. }
  30171. }
  30172. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30173. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30174. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30175. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30176. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30177. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30178. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30179. var vertexCount = 0;
  30180. for (i = 0; i < this.vertices.length; ++i) {
  30181. var vertex = this.vertices[i];
  30182. vertex.id = vertexCount;
  30183. if (vertex.triangleCount) {
  30184. vertex.originalOffsets.forEach(function (originalOffset) {
  30185. newPositionData.push(vertex.position.x);
  30186. newPositionData.push(vertex.position.y);
  30187. newPositionData.push(vertex.position.z);
  30188. newNormalData.push(normalData[originalOffset * 3]);
  30189. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30190. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30191. if (uvs && uvs.length) {
  30192. newUVsData.push(uvs[(originalOffset * 2)]);
  30193. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30194. }
  30195. else if (colorsData && colorsData.length) {
  30196. newColorsData.push(colorsData[(originalOffset * 4)]);
  30197. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30198. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30199. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30200. }
  30201. ++vertexCount;
  30202. });
  30203. }
  30204. }
  30205. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30206. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30207. var submeshesArray = this._reconstructedMesh.subMeshes;
  30208. this._reconstructedMesh.subMeshes = [];
  30209. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30210. var originalIndices = this._mesh.getIndices();
  30211. for (i = 0; i < newTriangles.length; ++i) {
  30212. var t = newTriangles[i];
  30213. //now get the new referencing point for each vertex
  30214. [0, 1, 2].forEach(function (idx) {
  30215. var id = originalIndices[t.originalOffset + idx];
  30216. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30217. if (offset < 0)
  30218. offset = 0;
  30219. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30220. });
  30221. }
  30222. //overwriting the old vertex buffers and indices.
  30223. this._reconstructedMesh.setIndices(newIndicesArray);
  30224. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30225. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30226. if (newUVsData.length > 0)
  30227. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30228. if (newColorsData.length > 0)
  30229. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30230. //create submesh
  30231. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30232. if (submeshIndex > 0) {
  30233. this._reconstructedMesh.subMeshes = [];
  30234. submeshesArray.forEach(function (submesh) {
  30235. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30236. });
  30237. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30238. }
  30239. };
  30240. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30241. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30242. this._reconstructedMesh.material = this._mesh.material;
  30243. this._reconstructedMesh.parent = this._mesh.parent;
  30244. this._reconstructedMesh.isVisible = false;
  30245. };
  30246. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30247. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30248. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30249. if (t.deleted)
  30250. continue;
  30251. var s = this.references[vertex1.triangleStart + i].vertexId;
  30252. var v1 = t.vertices[(s + 1) % 3];
  30253. var v2 = t.vertices[(s + 2) % 3];
  30254. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30255. deletedArray[i] = true;
  30256. delTr.push(t);
  30257. continue;
  30258. }
  30259. var d1 = v1.position.subtract(point);
  30260. d1 = d1.normalize();
  30261. var d2 = v2.position.subtract(point);
  30262. d2 = d2.normalize();
  30263. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30264. return true;
  30265. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30266. deletedArray[i] = false;
  30267. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30268. return true;
  30269. }
  30270. return false;
  30271. };
  30272. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30273. var newDeleted = deletedTriangles;
  30274. for (var i = 0; i < vertex.triangleCount; ++i) {
  30275. var ref = this.references[vertex.triangleStart + i];
  30276. var t = this.triangles[ref.triangleId];
  30277. if (t.deleted)
  30278. continue;
  30279. if (deletedArray[i] && t.deletePending) {
  30280. t.deleted = true;
  30281. newDeleted++;
  30282. continue;
  30283. }
  30284. t.vertices[ref.vertexId] = origVertex;
  30285. t.isDirty = true;
  30286. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30287. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30288. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30289. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30290. this.references.push(ref);
  30291. }
  30292. return newDeleted;
  30293. };
  30294. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30295. for (var i = 0; i < this.vertices.length; ++i) {
  30296. var vCount = [];
  30297. var vId = [];
  30298. var v = this.vertices[i];
  30299. var j;
  30300. for (j = 0; j < v.triangleCount; ++j) {
  30301. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30302. for (var ii = 0; ii < 3; ii++) {
  30303. var ofs = 0;
  30304. var vv = triangle.vertices[ii];
  30305. while (ofs < vCount.length) {
  30306. if (vId[ofs] === vv.id)
  30307. break;
  30308. ++ofs;
  30309. }
  30310. if (ofs === vCount.length) {
  30311. vCount.push(1);
  30312. vId.push(vv.id);
  30313. }
  30314. else {
  30315. vCount[ofs]++;
  30316. }
  30317. }
  30318. }
  30319. for (j = 0; j < vCount.length; ++j) {
  30320. if (vCount[j] === 1) {
  30321. this.vertices[vId[j]].isBorder = true;
  30322. }
  30323. else {
  30324. this.vertices[vId[j]].isBorder = false;
  30325. }
  30326. }
  30327. }
  30328. };
  30329. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30330. if (identifyBorders === void 0) { identifyBorders = false; }
  30331. var i;
  30332. if (!identifyBorders) {
  30333. var newTrianglesVector = [];
  30334. for (i = 0; i < this.triangles.length; ++i) {
  30335. if (!this.triangles[i].deleted) {
  30336. newTrianglesVector.push(this.triangles[i]);
  30337. }
  30338. }
  30339. this.triangles = newTrianglesVector;
  30340. }
  30341. for (i = 0; i < this.vertices.length; ++i) {
  30342. this.vertices[i].triangleCount = 0;
  30343. this.vertices[i].triangleStart = 0;
  30344. }
  30345. var t;
  30346. var j;
  30347. var v;
  30348. for (i = 0; i < this.triangles.length; ++i) {
  30349. t = this.triangles[i];
  30350. for (j = 0; j < 3; ++j) {
  30351. v = t.vertices[j];
  30352. v.triangleCount++;
  30353. }
  30354. }
  30355. var tStart = 0;
  30356. for (i = 0; i < this.vertices.length; ++i) {
  30357. this.vertices[i].triangleStart = tStart;
  30358. tStart += this.vertices[i].triangleCount;
  30359. this.vertices[i].triangleCount = 0;
  30360. }
  30361. var newReferences = new Array(this.triangles.length * 3);
  30362. for (i = 0; i < this.triangles.length; ++i) {
  30363. t = this.triangles[i];
  30364. for (j = 0; j < 3; ++j) {
  30365. v = t.vertices[j];
  30366. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30367. v.triangleCount++;
  30368. }
  30369. }
  30370. this.references = newReferences;
  30371. if (identifyBorders) {
  30372. this.identifyBorder();
  30373. }
  30374. };
  30375. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30376. var x = point.x;
  30377. var y = point.y;
  30378. var z = point.z;
  30379. 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
  30380. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30381. };
  30382. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30383. var q = vertex1.q.add(vertex2.q);
  30384. var border = vertex1.isBorder && vertex2.isBorder;
  30385. var error = 0;
  30386. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30387. if (qDet !== 0 && !border) {
  30388. if (!pointResult) {
  30389. pointResult = BABYLON.Vector3.Zero();
  30390. }
  30391. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30392. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30393. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30394. error = this.vertexError(q, pointResult);
  30395. }
  30396. else {
  30397. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30398. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30399. var error1 = this.vertexError(q, vertex1.position);
  30400. var error2 = this.vertexError(q, vertex2.position);
  30401. var error3 = this.vertexError(q, p3);
  30402. error = Math.min(error1, error2, error3);
  30403. if (error === error1) {
  30404. if (pointResult) {
  30405. pointResult.copyFrom(vertex1.position);
  30406. }
  30407. }
  30408. else if (error === error2) {
  30409. if (pointResult) {
  30410. pointResult.copyFrom(vertex2.position);
  30411. }
  30412. }
  30413. else {
  30414. if (pointResult) {
  30415. pointResult.copyFrom(p3);
  30416. }
  30417. }
  30418. }
  30419. return error;
  30420. };
  30421. return QuadraticErrorSimplification;
  30422. })();
  30423. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30424. })(BABYLON || (BABYLON = {}));
  30425. //# sourceMappingURL=babylon.meshSimplification.js.map
  30426. var BABYLON;
  30427. (function (BABYLON) {
  30428. var Analyser = (function () {
  30429. function Analyser(scene) {
  30430. this.SMOOTHING = 0.75;
  30431. this.FFT_SIZE = 512;
  30432. this.BARGRAPHAMPLITUDE = 256;
  30433. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30434. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30435. this._scene = scene;
  30436. this._audioEngine = BABYLON.Engine.audioEngine;
  30437. if (this._audioEngine.canUseWebAudio) {
  30438. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30439. this._webAudioAnalyser.minDecibels = -140;
  30440. this._webAudioAnalyser.maxDecibels = 0;
  30441. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30442. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30443. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30444. }
  30445. }
  30446. Analyser.prototype.getFrequencyBinCount = function () {
  30447. if (this._audioEngine.canUseWebAudio) {
  30448. return this._webAudioAnalyser.frequencyBinCount;
  30449. }
  30450. else {
  30451. return 0;
  30452. }
  30453. };
  30454. Analyser.prototype.getByteFrequencyData = function () {
  30455. if (this._audioEngine.canUseWebAudio) {
  30456. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30457. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30458. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30459. }
  30460. return this._byteFreqs;
  30461. };
  30462. Analyser.prototype.getByteTimeDomainData = function () {
  30463. if (this._audioEngine.canUseWebAudio) {
  30464. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30465. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30466. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30467. }
  30468. return this._byteTime;
  30469. };
  30470. Analyser.prototype.getFloatFrequencyData = function () {
  30471. if (this._audioEngine.canUseWebAudio) {
  30472. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30473. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30474. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30475. }
  30476. return this._floatFreqs;
  30477. };
  30478. Analyser.prototype.drawDebugCanvas = function () {
  30479. var _this = this;
  30480. if (this._audioEngine.canUseWebAudio) {
  30481. if (!this._debugCanvas) {
  30482. this._debugCanvas = document.createElement("canvas");
  30483. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30484. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30485. this._debugCanvas.style.position = "absolute";
  30486. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30487. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30488. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30489. document.body.appendChild(this._debugCanvas);
  30490. this._registerFunc = function () {
  30491. _this.drawDebugCanvas();
  30492. };
  30493. this._scene.registerBeforeRender(this._registerFunc);
  30494. }
  30495. if (this._registerFunc) {
  30496. var workingArray = this.getByteFrequencyData();
  30497. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30498. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30499. // Draw the frequency domain chart.
  30500. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30501. var value = workingArray[i];
  30502. var percent = value / this.BARGRAPHAMPLITUDE;
  30503. var height = this.DEBUGCANVASSIZE.height * percent;
  30504. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30505. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30506. var hue = i / this.getFrequencyBinCount() * 360;
  30507. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30508. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30509. }
  30510. }
  30511. }
  30512. };
  30513. Analyser.prototype.stopDebugCanvas = function () {
  30514. if (this._debugCanvas) {
  30515. this._scene.unregisterBeforeRender(this._registerFunc);
  30516. this._registerFunc = null;
  30517. document.body.removeChild(this._debugCanvas);
  30518. this._debugCanvas = null;
  30519. this._debugCanvasContext = null;
  30520. }
  30521. };
  30522. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30523. if (this._audioEngine.canUseWebAudio) {
  30524. inputAudioNode.connect(this._webAudioAnalyser);
  30525. this._webAudioAnalyser.connect(outputAudioNode);
  30526. }
  30527. };
  30528. Analyser.prototype.dispose = function () {
  30529. if (this._audioEngine.canUseWebAudio) {
  30530. this._webAudioAnalyser.disconnect();
  30531. }
  30532. };
  30533. return Analyser;
  30534. })();
  30535. BABYLON.Analyser = Analyser;
  30536. })(BABYLON || (BABYLON = {}));
  30537. //# sourceMappingURL=babylon.analyser.js.map
  30538. var BABYLON;
  30539. (function (BABYLON) {
  30540. var DepthRenderer = (function () {
  30541. function DepthRenderer(scene, type) {
  30542. var _this = this;
  30543. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30544. this._viewMatrix = BABYLON.Matrix.Zero();
  30545. this._projectionMatrix = BABYLON.Matrix.Zero();
  30546. this._transformMatrix = BABYLON.Matrix.Zero();
  30547. this._worldViewProjection = BABYLON.Matrix.Zero();
  30548. this._scene = scene;
  30549. var engine = scene.getEngine();
  30550. // Render target
  30551. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30552. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30553. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30554. this._depthMap.refreshRate = 1;
  30555. this._depthMap.renderParticles = false;
  30556. this._depthMap.renderList = null;
  30557. // set default depth value to 1.0 (far away)
  30558. this._depthMap.onClear = function (engine) {
  30559. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30560. };
  30561. // Custom render function
  30562. var renderSubMesh = function (subMesh) {
  30563. var mesh = subMesh.getRenderingMesh();
  30564. var scene = _this._scene;
  30565. var engine = scene.getEngine();
  30566. // Culling
  30567. engine.setState(subMesh.getMaterial().backFaceCulling);
  30568. // Managing instances
  30569. var batch = mesh._getInstancesRenderList(subMesh._id);
  30570. if (batch.mustReturn) {
  30571. return;
  30572. }
  30573. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30574. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30575. engine.enableEffect(_this._effect);
  30576. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30577. var material = subMesh.getMaterial();
  30578. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30579. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30580. // Alpha test
  30581. if (material && material.needAlphaTesting()) {
  30582. var alphaTexture = material.getAlphaTestTexture();
  30583. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30584. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30585. }
  30586. // Bones
  30587. if (mesh.useBones) {
  30588. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30589. }
  30590. // Draw
  30591. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30592. }
  30593. };
  30594. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30595. var index;
  30596. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30597. renderSubMesh(opaqueSubMeshes.data[index]);
  30598. }
  30599. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30600. renderSubMesh(alphaTestSubMeshes.data[index]);
  30601. }
  30602. };
  30603. }
  30604. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30605. var defines = [];
  30606. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30607. var mesh = subMesh.getMesh();
  30608. var scene = mesh.getScene();
  30609. var material = subMesh.getMaterial();
  30610. // Alpha test
  30611. if (material && material.needAlphaTesting()) {
  30612. defines.push("#define ALPHATEST");
  30613. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30614. attribs.push(BABYLON.VertexBuffer.UVKind);
  30615. defines.push("#define UV1");
  30616. }
  30617. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30618. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30619. defines.push("#define UV2");
  30620. }
  30621. }
  30622. // Bones
  30623. if (mesh.useBones) {
  30624. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30625. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30626. defines.push("#define BONES");
  30627. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30628. }
  30629. // Instances
  30630. if (useInstances) {
  30631. defines.push("#define INSTANCES");
  30632. attribs.push("world0");
  30633. attribs.push("world1");
  30634. attribs.push("world2");
  30635. attribs.push("world3");
  30636. }
  30637. // Get correct effect
  30638. var join = defines.join("\n");
  30639. if (this._cachedDefines !== join) {
  30640. this._cachedDefines = join;
  30641. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  30642. }
  30643. return this._effect.isReady();
  30644. };
  30645. DepthRenderer.prototype.getDepthMap = function () {
  30646. return this._depthMap;
  30647. };
  30648. // Methods
  30649. DepthRenderer.prototype.dispose = function () {
  30650. this._depthMap.dispose();
  30651. };
  30652. return DepthRenderer;
  30653. })();
  30654. BABYLON.DepthRenderer = DepthRenderer;
  30655. })(BABYLON || (BABYLON = {}));
  30656. //# sourceMappingURL=babylon.depthRenderer.js.map
  30657. var __extends = this.__extends || function (d, b) {
  30658. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30659. function __() { this.constructor = d; }
  30660. __.prototype = b.prototype;
  30661. d.prototype = new __();
  30662. };
  30663. var BABYLON;
  30664. (function (BABYLON) {
  30665. var SSAORenderingPipeline = (function (_super) {
  30666. __extends(SSAORenderingPipeline, _super);
  30667. /**
  30668. * @constructor
  30669. * @param {string} name - The rendering pipeline name
  30670. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30671. * @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 }
  30672. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30673. */
  30674. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  30675. var _this = this;
  30676. _super.call(this, scene.getEngine(), name);
  30677. // Members
  30678. /**
  30679. * The PassPostProcess id in the pipeline that contains the original scene color
  30680. * @type {string}
  30681. */
  30682. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  30683. /**
  30684. * The SSAO PostProcess id in the pipeline
  30685. * @type {string}
  30686. */
  30687. this.SSAORenderEffect = "SSAORenderEffect";
  30688. /**
  30689. * The horizontal blur PostProcess id in the pipeline
  30690. * @type {string}
  30691. */
  30692. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  30693. /**
  30694. * The vertical blur PostProcess id in the pipeline
  30695. * @type {string}
  30696. */
  30697. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  30698. /**
  30699. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  30700. * @type {string}
  30701. */
  30702. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  30703. /**
  30704. * The output strength of the SSAO post-process. Default value is 1.0.
  30705. * @type {number}
  30706. */
  30707. this.totalStrength = 1.0;
  30708. /**
  30709. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  30710. * @type {number}
  30711. */
  30712. this.radius = 0.0002;
  30713. /**
  30714. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  30715. * Must not be equal to fallOff and superior to fallOff.
  30716. * Default value is 0.0075
  30717. * @type {number}
  30718. */
  30719. this.area = 0.0075;
  30720. /**
  30721. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  30722. * Must not be equal to area and inferior to area.
  30723. * Default value is 0.0002
  30724. * @type {number}
  30725. */
  30726. this.fallOff = 0.0002;
  30727. this._firstUpdate = true;
  30728. this._scene = scene;
  30729. // Set up assets
  30730. this._createRandomTexture();
  30731. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30732. var ssaoRatio = ratio.ssaoRatio || ratio;
  30733. var combineRatio = ratio.combineRatio || ratio;
  30734. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30735. this._createSSAOPostProcess(ssaoRatio);
  30736. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30737. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30738. this._createSSAOCombinePostProcess(combineRatio);
  30739. // Set up pipeline
  30740. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  30741. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  30742. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  30743. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  30744. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  30745. // Finish
  30746. scene.postProcessRenderPipelineManager.addPipeline(this);
  30747. if (cameras)
  30748. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30749. }
  30750. // Public Methods
  30751. /**
  30752. * Returns the horizontal blur PostProcess
  30753. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  30754. */
  30755. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  30756. return this._blurHPostProcess;
  30757. };
  30758. /**
  30759. * Returns the vertical blur PostProcess
  30760. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  30761. */
  30762. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  30763. return this._blurVPostProcess;
  30764. };
  30765. /**
  30766. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  30767. */
  30768. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30769. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30770. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30771. this._originalColorPostProcess = undefined;
  30772. this._ssaoPostProcess = undefined;
  30773. this._blurHPostProcess = undefined;
  30774. this._blurVPostProcess = undefined;
  30775. this._ssaoCombinePostProcess = undefined;
  30776. this._randomTexture.dispose();
  30777. if (disableDepthRender)
  30778. this._scene.disableDepthRenderer();
  30779. };
  30780. // Private Methods
  30781. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  30782. var _this = this;
  30783. var sampleSphere = [
  30784. 0.5381, 0.1856, -0.4319,
  30785. 0.1379, 0.2486, 0.4430,
  30786. 0.3371, 0.5679, -0.0057,
  30787. -0.6999, -0.0451, -0.0019,
  30788. 0.0689, -0.1598, -0.8547,
  30789. 0.0560, 0.0069, -0.1843,
  30790. -0.0146, 0.1402, 0.0762,
  30791. 0.0100, -0.1924, -0.0344,
  30792. -0.3577, -0.5301, -0.4358,
  30793. -0.3169, 0.1063, 0.0158,
  30794. 0.0103, -0.5869, 0.0046,
  30795. -0.0897, -0.4940, 0.3287,
  30796. 0.7119, -0.0154, -0.0918,
  30797. -0.0533, 0.0596, -0.5411,
  30798. 0.0352, -0.0631, 0.5460,
  30799. -0.4776, 0.2847, -0.0271
  30800. ];
  30801. var samplesFactor = 1.0 / 16.0;
  30802. 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);
  30803. this._ssaoPostProcess.onApply = function (effect) {
  30804. if (_this._firstUpdate) {
  30805. effect.setArray3("sampleSphere", sampleSphere);
  30806. effect.setFloat("samplesFactor", samplesFactor);
  30807. effect.setFloat("randTextureTiles", 4.0 / ratio);
  30808. _this._firstUpdate = false;
  30809. }
  30810. effect.setFloat("totalStrength", _this.totalStrength);
  30811. effect.setFloat("radius", _this.radius);
  30812. effect.setFloat("area", _this.area);
  30813. effect.setFloat("fallOff", _this.fallOff);
  30814. effect.setTexture("textureSampler", _this._depthTexture);
  30815. effect.setTexture("randomSampler", _this._randomTexture);
  30816. };
  30817. };
  30818. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  30819. var _this = this;
  30820. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30821. this._ssaoCombinePostProcess.onApply = function (effect) {
  30822. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  30823. };
  30824. };
  30825. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  30826. var size = 512;
  30827. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30828. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30829. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30830. var context = this._randomTexture.getContext();
  30831. var rand = function (min, max) {
  30832. return Math.random() * (max - min) + min;
  30833. };
  30834. for (var x = 0; x < size; x++) {
  30835. for (var y = 0; y < size; y++) {
  30836. var randVector = BABYLON.Vector3.Zero();
  30837. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  30838. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  30839. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  30840. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  30841. context.fillRect(x, y, 1, 1);
  30842. }
  30843. }
  30844. this._randomTexture.update(false);
  30845. };
  30846. return SSAORenderingPipeline;
  30847. })(BABYLON.PostProcessRenderPipeline);
  30848. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  30849. })(BABYLON || (BABYLON = {}));
  30850. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  30851. var __extends = this.__extends || function (d, b) {
  30852. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30853. function __() { this.constructor = d; }
  30854. __.prototype = b.prototype;
  30855. d.prototype = new __();
  30856. };
  30857. var BABYLON;
  30858. (function (BABYLON) {
  30859. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  30860. var VolumetricLightScatteringPostProcess = (function (_super) {
  30861. __extends(VolumetricLightScatteringPostProcess, _super);
  30862. /**
  30863. * @constructor
  30864. * @param {string} name - The post-process name
  30865. * @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)
  30866. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  30867. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  30868. * @param {number} samples - The post-process quality, default 100
  30869. * @param {number} samplingMode - The post-process filtering mode
  30870. * @param {BABYLON.Engine} engine - The babylon engine
  30871. * @param {boolean} reusable - If the post-process is reusable
  30872. */
  30873. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  30874. var _this = this;
  30875. if (samples === void 0) { samples = 100; }
  30876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  30877. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  30878. this._screenCoordinates = BABYLON.Vector2.Zero();
  30879. /**
  30880. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  30881. * @type {boolean}
  30882. */
  30883. this.useCustomMeshPosition = false;
  30884. /**
  30885. * If the post-process should inverse the light scattering direction
  30886. * @type {boolean}
  30887. */
  30888. this.invert = true;
  30889. /**
  30890. * Array containing the excluded meshes not rendered in the internal pass
  30891. */
  30892. this.excludedMeshes = new Array();
  30893. this.exposure = 0.3;
  30894. this.decay = 0.96815;
  30895. this.weight = 0.58767;
  30896. this.density = 0.926;
  30897. var scene = camera.getScene();
  30898. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  30899. // Configure mesh
  30900. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  30901. // Configure
  30902. this._createPass(scene, ratio.passRatio || ratio);
  30903. this.onApply = function (effect) {
  30904. _this._updateMeshScreenCoordinates(scene);
  30905. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  30906. effect.setFloat("exposure", _this.exposure);
  30907. effect.setFloat("decay", _this.decay);
  30908. effect.setFloat("weight", _this.weight);
  30909. effect.setFloat("density", _this.density);
  30910. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  30911. };
  30912. }
  30913. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  30914. var mesh = subMesh.getMesh();
  30915. var defines = [];
  30916. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30917. var material = subMesh.getMaterial();
  30918. var needUV = false;
  30919. // Render this.mesh as default
  30920. if (mesh === this.mesh) {
  30921. defines.push("#define BASIC_RENDER");
  30922. defines.push("#define NEED_UV");
  30923. needUV = true;
  30924. }
  30925. // Alpha test
  30926. if (material) {
  30927. if (material.needAlphaTesting() || mesh === this.mesh)
  30928. defines.push("#define ALPHATEST");
  30929. if (material.opacityTexture !== undefined) {
  30930. defines.push("#define OPACITY");
  30931. if (material.opacityTexture.getAlphaFromRGB)
  30932. defines.push("#define OPACITYRGB");
  30933. if (!needUV)
  30934. defines.push("#define NEED_UV");
  30935. }
  30936. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30937. attribs.push(BABYLON.VertexBuffer.UVKind);
  30938. defines.push("#define UV1");
  30939. }
  30940. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30941. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30942. defines.push("#define UV2");
  30943. }
  30944. }
  30945. // Bones
  30946. if (mesh.useBones) {
  30947. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30948. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30949. defines.push("#define BONES");
  30950. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30951. }
  30952. // Instances
  30953. if (useInstances) {
  30954. defines.push("#define INSTANCES");
  30955. attribs.push("world0");
  30956. attribs.push("world1");
  30957. attribs.push("world2");
  30958. attribs.push("world3");
  30959. }
  30960. // Get correct effect
  30961. var join = defines.join("\n");
  30962. if (this._cachedDefines !== join) {
  30963. this._cachedDefines = join;
  30964. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  30965. }
  30966. return this._volumetricLightScatteringPass.isReady();
  30967. };
  30968. /**
  30969. * Sets the new light position for light scattering effect
  30970. * @param {BABYLON.Vector3} The new custom light position
  30971. */
  30972. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  30973. this._customMeshPosition = position;
  30974. };
  30975. /**
  30976. * Returns the light position for light scattering effect
  30977. * @return {BABYLON.Vector3} The custom light position
  30978. */
  30979. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  30980. return this._customMeshPosition;
  30981. };
  30982. /**
  30983. * Disposes the internal assets and detaches the post-process from the camera
  30984. */
  30985. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  30986. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  30987. if (rttIndex !== -1) {
  30988. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  30989. }
  30990. this._volumetricLightScatteringRTT.dispose();
  30991. _super.prototype.dispose.call(this, camera);
  30992. };
  30993. /**
  30994. * Returns the render target texture used by the post-process
  30995. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  30996. */
  30997. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  30998. return this._volumetricLightScatteringRTT;
  30999. };
  31000. // Private methods
  31001. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31002. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31003. return true;
  31004. }
  31005. return false;
  31006. };
  31007. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31008. var _this = this;
  31009. var engine = scene.getEngine();
  31010. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31011. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31012. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31013. this._volumetricLightScatteringRTT.renderList = null;
  31014. this._volumetricLightScatteringRTT.renderParticles = false;
  31015. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31016. // Custom render function for submeshes
  31017. var renderSubMesh = function (subMesh) {
  31018. var mesh = subMesh.getRenderingMesh();
  31019. if (_this._meshExcluded(mesh)) {
  31020. return;
  31021. }
  31022. var scene = mesh.getScene();
  31023. var engine = scene.getEngine();
  31024. // Culling
  31025. engine.setState(subMesh.getMaterial().backFaceCulling);
  31026. // Managing instances
  31027. var batch = mesh._getInstancesRenderList(subMesh._id);
  31028. if (batch.mustReturn) {
  31029. return;
  31030. }
  31031. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31032. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31033. engine.enableEffect(_this._volumetricLightScatteringPass);
  31034. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31035. var material = subMesh.getMaterial();
  31036. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31037. // Alpha test
  31038. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31039. var alphaTexture = material.getAlphaTestTexture();
  31040. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31041. if (alphaTexture) {
  31042. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31043. }
  31044. if (material.opacityTexture !== undefined) {
  31045. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31046. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31047. }
  31048. }
  31049. // Bones
  31050. if (mesh.useBones) {
  31051. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31052. }
  31053. // Draw
  31054. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31055. }
  31056. };
  31057. // Render target texture callbacks
  31058. var savedSceneClearColor;
  31059. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31060. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31061. savedSceneClearColor = scene.clearColor;
  31062. scene.clearColor = sceneClearColor;
  31063. };
  31064. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31065. scene.clearColor = savedSceneClearColor;
  31066. };
  31067. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31068. var engine = scene.getEngine();
  31069. var index;
  31070. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31071. renderSubMesh(opaqueSubMeshes.data[index]);
  31072. }
  31073. engine.setAlphaTesting(true);
  31074. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31075. renderSubMesh(alphaTestSubMeshes.data[index]);
  31076. }
  31077. engine.setAlphaTesting(false);
  31078. if (transparentSubMeshes.length) {
  31079. // Sort sub meshes
  31080. for (index = 0; index < transparentSubMeshes.length; index++) {
  31081. var submesh = transparentSubMeshes.data[index];
  31082. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31083. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31084. }
  31085. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31086. sortedArray.sort(function (a, b) {
  31087. // Alpha index first
  31088. if (a._alphaIndex > b._alphaIndex) {
  31089. return 1;
  31090. }
  31091. if (a._alphaIndex < b._alphaIndex) {
  31092. return -1;
  31093. }
  31094. // Then distance to camera
  31095. if (a._distanceToCamera < b._distanceToCamera) {
  31096. return 1;
  31097. }
  31098. if (a._distanceToCamera > b._distanceToCamera) {
  31099. return -1;
  31100. }
  31101. return 0;
  31102. });
  31103. // Render sub meshes
  31104. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31105. for (index = 0; index < sortedArray.length; index++) {
  31106. renderSubMesh(sortedArray[index]);
  31107. }
  31108. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31109. }
  31110. };
  31111. };
  31112. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31113. var transform = scene.getTransformMatrix();
  31114. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31115. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31116. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31117. if (this.invert)
  31118. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31119. };
  31120. // Static methods
  31121. /**
  31122. * Creates a default mesh for the Volumeric Light Scattering post-process
  31123. * @param {string} The mesh name
  31124. * @param {BABYLON.Scene} The scene where to create the mesh
  31125. * @return {BABYLON.Mesh} the default mesh
  31126. */
  31127. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31128. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31129. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31130. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31131. return mesh;
  31132. };
  31133. return VolumetricLightScatteringPostProcess;
  31134. })(BABYLON.PostProcess);
  31135. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31136. })(BABYLON || (BABYLON = {}));
  31137. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31138. var __extends = this.__extends || function (d, b) {
  31139. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31140. function __() { this.constructor = d; }
  31141. __.prototype = b.prototype;
  31142. d.prototype = new __();
  31143. };
  31144. var BABYLON;
  31145. (function (BABYLON) {
  31146. var LensRenderingPipeline = (function (_super) {
  31147. __extends(LensRenderingPipeline, _super);
  31148. /**
  31149. * @constructor
  31150. *
  31151. * Effect parameters are as follow:
  31152. * {
  31153. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31154. * edge_blur: number; // from 0 to x (1 for realism)
  31155. * distortion: number; // from 0 to x (1 for realism)
  31156. * grain_amount: number; // from 0 to 1
  31157. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31158. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31159. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31160. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31161. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31162. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31163. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31164. * }
  31165. * Note: if an effect parameter is unset, effect is disabled
  31166. *
  31167. * @param {string} name - The rendering pipeline name
  31168. * @param {object} parameters - An object containing all parameters (see above)
  31169. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31170. * @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)
  31171. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31172. */
  31173. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31174. var _this = this;
  31175. if (ratio === void 0) { ratio = 1.0; }
  31176. _super.call(this, scene.getEngine(), name);
  31177. // Lens effects can be of the following:
  31178. // - chromatic aberration (slight shift of RGB colors)
  31179. // - blur on the edge of the lens
  31180. // - lens distortion
  31181. // - depth-of-field blur & highlights enhancing
  31182. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31183. // - grain effect (noise or custom texture)
  31184. // Two additional texture samplers are needed:
  31185. // - depth map (for depth-of-field)
  31186. // - grain texture
  31187. /**
  31188. * The chromatic aberration PostProcess id in the pipeline
  31189. * @type {string}
  31190. */
  31191. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31192. /**
  31193. * The highlights enhancing PostProcess id in the pipeline
  31194. * @type {string}
  31195. */
  31196. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31197. /**
  31198. * The depth-of-field PostProcess id in the pipeline
  31199. * @type {string}
  31200. */
  31201. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31202. this._scene = scene;
  31203. // Fetch texture samplers
  31204. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31205. if (parameters.grain_texture) {
  31206. this._grainTexture = parameters.grain_texture;
  31207. }
  31208. else {
  31209. this._createGrainTexture();
  31210. }
  31211. // save parameters
  31212. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31213. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31214. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31215. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31216. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31217. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31218. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31219. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31220. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31221. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31222. // Create effects
  31223. this._createChromaticAberrationPostProcess(ratio);
  31224. this._createHighlightsPostProcess(ratio);
  31225. this._createDepthOfFieldPostProcess(ratio);
  31226. // Set up pipeline
  31227. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  31228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  31229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  31230. if (this._highlightsGain == -1) {
  31231. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31232. }
  31233. // Finish
  31234. scene.postProcessRenderPipelineManager.addPipeline(this);
  31235. if (cameras) {
  31236. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31237. }
  31238. }
  31239. // public methods (self explanatory)
  31240. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  31241. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  31242. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  31243. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  31244. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  31245. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  31246. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  31247. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  31248. LensRenderingPipeline.prototype.setFocusDepth = function (amount) { this._dofDepth = amount; };
  31249. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDepth = -1; };
  31250. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  31251. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  31252. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  31253. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  31254. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  31255. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31256. this._highlightsGain = amount;
  31257. };
  31258. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31259. if (this._highlightsGain == -1) {
  31260. this._highlightsGain = 1.0;
  31261. }
  31262. this._highlightsThreshold = amount;
  31263. };
  31264. LensRenderingPipeline.prototype.disableHighlights = function () {
  31265. this._highlightsGain = -1;
  31266. };
  31267. /**
  31268. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31269. */
  31270. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31271. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31272. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31273. this._chromaticAberrationPostProcess = undefined;
  31274. this._highlightsPostProcess = undefined;
  31275. this._depthOfFieldPostProcess = undefined;
  31276. this._grainTexture.dispose();
  31277. if (disableDepthRender)
  31278. this._scene.disableDepthRenderer();
  31279. };
  31280. // colors shifting and distortion
  31281. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31282. var _this = this;
  31283. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31284. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31285. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31286. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31287. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31288. };
  31289. };
  31290. // highlights enhancing
  31291. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31292. var _this = this;
  31293. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31294. this._highlightsPostProcess.onApply = function (effect) {
  31295. effect.setFloat('gain', _this._highlightsGain);
  31296. effect.setFloat('threshold', _this._highlightsThreshold);
  31297. effect.setBool('pentagon', _this._dofPentagon);
  31298. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31299. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31300. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31301. };
  31302. };
  31303. // colors shifting and distortion
  31304. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31305. var _this = this;
  31306. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31307. "focus_depth", "aperture", "pentagon", "maxZ", "edge_blur", "chromatic_aberration",
  31308. "distortion", "blur_noise", "grain_amount", "screen_width", "screen_height", "highlights"
  31309. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31310. this._depthOfFieldPostProcess.onApply = function (effect) {
  31311. effect.setBool('blur_noise', _this._blurNoise);
  31312. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31313. effect.setFloat('grain_amount', _this._grainAmount);
  31314. effect.setTexture("depthSampler", _this._depthTexture);
  31315. effect.setTexture("grainSampler", _this._grainTexture);
  31316. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31317. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31318. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31319. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31320. effect.setFloat('distortion', _this._distortion);
  31321. effect.setFloat('focus_depth', _this._dofDepth);
  31322. effect.setFloat('aperture', _this._dofAperture);
  31323. effect.setFloat('edge_blur', _this._edgeBlur);
  31324. effect.setBool('highlights', (_this._highlightsGain != -1));
  31325. };
  31326. };
  31327. // creates a black and white random noise texture, 512x512
  31328. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31329. var size = 512;
  31330. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31331. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31332. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31333. var context = this._grainTexture.getContext();
  31334. var rand = function (min, max) {
  31335. return Math.random() * (max - min) + min;
  31336. };
  31337. var value;
  31338. for (var x = 0; x < size; x++) {
  31339. for (var y = 0; y < size; y++) {
  31340. value = Math.floor(rand(0.42, 0.58) * 255);
  31341. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31342. context.fillRect(x, y, 1, 1);
  31343. }
  31344. }
  31345. this._grainTexture.update(false);
  31346. };
  31347. return LensRenderingPipeline;
  31348. })(BABYLON.PostProcessRenderPipeline);
  31349. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31350. })(BABYLON || (BABYLON = {}));
  31351. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31352. //
  31353. // This post-process allows the modification of rendered colors by using
  31354. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31355. //
  31356. // The object needs to be provided an url to a texture containing the color
  31357. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31358. // Use an image editing software to tweak the LUT to match your needs.
  31359. //
  31360. // For an example of a color LUT, see here:
  31361. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31362. // For explanations on color grading, see here:
  31363. // http://udn.epicgames.com/Three/ColorGrading.html
  31364. //
  31365. var __extends = this.__extends || function (d, b) {
  31366. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31367. function __() { this.constructor = d; }
  31368. __.prototype = b.prototype;
  31369. d.prototype = new __();
  31370. };
  31371. var BABYLON;
  31372. (function (BABYLON) {
  31373. var ColorCorrectionPostProcess = (function (_super) {
  31374. __extends(ColorCorrectionPostProcess, _super);
  31375. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31376. var _this = this;
  31377. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31378. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31379. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31380. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31381. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31382. this.onApply = function (effect) {
  31383. effect.setTexture("colorTable", _this._colorTableTexture);
  31384. };
  31385. }
  31386. return ColorCorrectionPostProcess;
  31387. })(BABYLON.PostProcess);
  31388. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31389. })(BABYLON || (BABYLON = {}));
  31390. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31391. 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}","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","vrDistortionCorrectionPixelShader":"#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}","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}"};
  31392. 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 e=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=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,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!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||this.collideForSubMesh(l,o,t)}},e.prototype.collideForSubMesh=function(e,i,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(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,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(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE: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={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.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}},t.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()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=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=r}(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,c=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=c;var p=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=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=c.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?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-m:m-h)}return t}();t.Arc2=p;var z=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=z;var M=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 p(a,h,u),l=m.angle.radians()/e;m.orientation===y.CW&&(l*=-1);for(var f=m.startAngle.radians()+l,x=0;e>x;x++){var c=Math.cos(f)*m.radius+m.centerPoint.x,z=Math.sin(f)*m.radius+m.centerPoint.y;this.addLineTo(c,z),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=M;var w=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.y?s=new r(0,-1,0):1!==i.x?s=new r(1,0,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=w;var d=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=d;var I=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=I;var D=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=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function i(){}return Object.defineProperty(i,\"IsEnabled\",{get:function(){return i._isEnabled},enumerable:!0,configurable:!0}),i.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,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=_,void 0!==window.SIMD&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&_.EnableSIMD()}(BABYLON||(BABYLON={}));";