babylon.2.1-beta.debug.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  589. var d0 = Vector3.Dot(vector0, axis) - size;
  590. var d1 = Vector3.Dot(vector1, axis) - size;
  591. var s = d0 / (d0 - d1);
  592. return s;
  593. };
  594. Vector3.FromArray = function (array, offset) {
  595. if (!offset) {
  596. offset = 0;
  597. }
  598. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  599. };
  600. Vector3.FromArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  606. result.x = array[offset];
  607. result.y = array[offset + 1];
  608. result.z = array[offset + 2];
  609. };
  610. Vector3.FromFloatsToRef = function (x, y, z, result) {
  611. result.x = x;
  612. result.y = y;
  613. result.z = z;
  614. };
  615. Vector3.Zero = function () {
  616. return new Vector3(0, 0, 0);
  617. };
  618. Vector3.Up = function () {
  619. return new Vector3(0, 1.0, 0);
  620. };
  621. Vector3.TransformCoordinates = function (vector, transformation) {
  622. var result = Vector3.Zero();
  623. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  624. return result;
  625. };
  626. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  627. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  628. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  629. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  630. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  631. result.x = x / w;
  632. result.y = y / w;
  633. result.z = z / w;
  634. };
  635. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  636. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  637. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  638. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  639. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  640. result.x = rx / rw;
  641. result.y = ry / rw;
  642. result.z = rz / rw;
  643. };
  644. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  645. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  646. var m0 = SIMD.float32x4.load(transformation.m, 0);
  647. var m1 = SIMD.float32x4.load(transformation.m, 4);
  648. var m2 = SIMD.float32x4.load(transformation.m, 8);
  649. var m3 = SIMD.float32x4.load(transformation.m, 12);
  650. 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));
  651. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  652. SIMD.float32x4.storeXYZ(result._data, 0, r);
  653. };
  654. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  655. var v0 = SIMD.float32x4.splat(x);
  656. var v1 = SIMD.float32x4.splat(y);
  657. var v2 = SIMD.float32x4.splat(z);
  658. var m0 = SIMD.float32x4.load(transformation.m, 0);
  659. var m1 = SIMD.float32x4.load(transformation.m, 4);
  660. var m2 = SIMD.float32x4.load(transformation.m, 8);
  661. var m3 = SIMD.float32x4.load(transformation.m, 12);
  662. 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));
  663. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  664. SIMD.float32x4.storeXYZ(result._data, 0, r);
  665. };
  666. Vector3.TransformNormal = function (vector, transformation) {
  667. var result = Vector3.Zero();
  668. Vector3.TransformNormalToRef(vector, transformation, result);
  669. return result;
  670. };
  671. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  672. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  673. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  674. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  675. };
  676. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  677. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  678. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  679. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  680. };
  681. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  682. var squared = amount * amount;
  683. var cubed = amount * squared;
  684. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  685. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  686. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  687. return new Vector3(x, y, z);
  688. };
  689. Vector3.Clamp = function (value, min, max) {
  690. var x = value.x;
  691. x = (x > max.x) ? max.x : x;
  692. x = (x < min.x) ? min.x : x;
  693. var y = value.y;
  694. y = (y > max.y) ? max.y : y;
  695. y = (y < min.y) ? min.y : y;
  696. var z = value.z;
  697. z = (z > max.z) ? max.z : z;
  698. z = (z < min.z) ? min.z : z;
  699. return new Vector3(x, y, z);
  700. };
  701. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  702. var squared = amount * amount;
  703. var cubed = amount * squared;
  704. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  705. var part2 = (-2.0 * cubed) + (3.0 * squared);
  706. var part3 = (cubed - (2.0 * squared)) + amount;
  707. var part4 = cubed - squared;
  708. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  709. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  710. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Lerp = function (start, end, amount) {
  714. var x = start.x + ((end.x - start.x) * amount);
  715. var y = start.y + ((end.y - start.y) * amount);
  716. var z = start.z + ((end.z - start.z) * amount);
  717. return new Vector3(x, y, z);
  718. };
  719. Vector3.Dot = function (left, right) {
  720. return (left.x * right.x + left.y * right.y + left.z * right.z);
  721. };
  722. Vector3.Cross = function (left, right) {
  723. var result = Vector3.Zero();
  724. Vector3.CrossToRef(left, right, result);
  725. return result;
  726. };
  727. Vector3.CrossToRef = function (left, right, result) {
  728. result.x = left.y * right.z - left.z * right.y;
  729. result.y = left.z * right.x - left.x * right.z;
  730. result.z = left.x * right.y - left.y * right.x;
  731. };
  732. Vector3.Normalize = function (vector) {
  733. var result = Vector3.Zero();
  734. Vector3.NormalizeToRef(vector, result);
  735. return result;
  736. };
  737. Vector3.NormalizeToRef = function (vector, result) {
  738. result.copyFrom(vector);
  739. result.normalize();
  740. };
  741. Vector3.Project = function (vector, world, transform, viewport) {
  742. var cw = viewport.width;
  743. var ch = viewport.height;
  744. var cx = viewport.x;
  745. var cy = viewport.y;
  746. 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);
  747. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  748. return Vector3.TransformCoordinates(vector, finalMatrix);
  749. };
  750. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  751. var matrix = world.multiply(transform);
  752. matrix.invert();
  753. source.x = source.x / viewportWidth * 2 - 1;
  754. source.y = -(source.y / viewportHeight * 2 - 1);
  755. var vector = Vector3.TransformCoordinates(source, matrix);
  756. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  757. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  758. vector = vector.scale(1.0 / num);
  759. }
  760. return vector;
  761. };
  762. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  763. var matrix = world.multiply(view).multiply(projection);
  764. matrix.invert();
  765. source.x = source.x / viewportWidth * 2 - 1;
  766. source.y = -(source.y / viewportHeight * 2 - 1);
  767. var vector = Vector3.TransformCoordinates(source, matrix);
  768. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  769. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  770. vector = vector.scale(1.0 / num);
  771. }
  772. return vector;
  773. };
  774. Vector3.Minimize = function (left, right) {
  775. var min = left.clone();
  776. min.MinimizeInPlace(right);
  777. return min;
  778. };
  779. Vector3.Maximize = function (left, right) {
  780. var max = left.clone();
  781. max.MaximizeInPlace(right);
  782. return max;
  783. };
  784. Vector3.Distance = function (value1, value2) {
  785. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  786. };
  787. Vector3.DistanceSquared = function (value1, value2) {
  788. var x = value1.x - value2.x;
  789. var y = value1.y - value2.y;
  790. var z = value1.z - value2.z;
  791. return (x * x) + (y * y) + (z * z);
  792. };
  793. Vector3.Center = function (value1, value2) {
  794. var center = value1.add(value2);
  795. center.scaleInPlace(0.5);
  796. return center;
  797. };
  798. return Vector3;
  799. })();
  800. BABYLON.Vector3 = Vector3;
  801. //Vector4 class created for EulerAngle class conversion to Quaternion
  802. var Vector4 = (function () {
  803. function Vector4(x, y, z, w) {
  804. this.x = x;
  805. this.y = y;
  806. this.z = z;
  807. this.w = w;
  808. }
  809. Vector4.prototype.toString = function () {
  810. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  811. };
  812. // Operators
  813. Vector4.prototype.asArray = function () {
  814. var result = [];
  815. this.toArray(result, 0);
  816. return result;
  817. };
  818. Vector4.prototype.toArray = function (array, index) {
  819. if (index === undefined) {
  820. index = 0;
  821. }
  822. array[index] = this.x;
  823. array[index + 1] = this.y;
  824. array[index + 2] = this.z;
  825. array[index + 3] = this.w;
  826. return this;
  827. };
  828. Vector4.prototype.addInPlace = function (otherVector) {
  829. this.x += otherVector.x;
  830. this.y += otherVector.y;
  831. this.z += otherVector.z;
  832. this.w += otherVector.w;
  833. return this;
  834. };
  835. Vector4.prototype.add = function (otherVector) {
  836. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  837. };
  838. Vector4.prototype.addToRef = function (otherVector, result) {
  839. result.x = this.x + otherVector.x;
  840. result.y = this.y + otherVector.y;
  841. result.z = this.z + otherVector.z;
  842. result.w = this.w + otherVector.w;
  843. return this;
  844. };
  845. Vector4.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. this.z -= otherVector.z;
  849. this.w -= otherVector.w;
  850. return this;
  851. };
  852. Vector4.prototype.subtract = function (otherVector) {
  853. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  854. };
  855. Vector4.prototype.subtractToRef = function (otherVector, result) {
  856. result.x = this.x - otherVector.x;
  857. result.y = this.y - otherVector.y;
  858. result.z = this.z - otherVector.z;
  859. result.w = this.w - otherVector.w;
  860. return this;
  861. };
  862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  864. };
  865. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  866. result.x = this.x - x;
  867. result.y = this.y - y;
  868. result.z = this.z - z;
  869. result.w = this.w - w;
  870. return this;
  871. };
  872. Vector4.prototype.negate = function () {
  873. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  874. };
  875. Vector4.prototype.scaleInPlace = function (scale) {
  876. this.x *= scale;
  877. this.y *= scale;
  878. this.z *= scale;
  879. this.w *= scale;
  880. return this;
  881. };
  882. Vector4.prototype.scale = function (scale) {
  883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  884. };
  885. Vector4.prototype.scaleToRef = function (scale, result) {
  886. result.x = this.x * scale;
  887. result.y = this.y * scale;
  888. result.z = this.z * scale;
  889. result.w = this.w * scale;
  890. };
  891. Vector4.prototype.equals = function (otherVector) {
  892. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  893. };
  894. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  895. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  896. };
  897. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  898. return this.x === x && this.y === y && this.z === z && this.w === w;
  899. };
  900. Vector4.prototype.multiplyInPlace = function (otherVector) {
  901. this.x *= otherVector.x;
  902. this.y *= otherVector.y;
  903. this.z *= otherVector.z;
  904. this.w *= otherVector.w;
  905. return this;
  906. };
  907. Vector4.prototype.multiply = function (otherVector) {
  908. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  909. };
  910. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  911. result.x = this.x * otherVector.x;
  912. result.y = this.y * otherVector.y;
  913. result.z = this.z * otherVector.z;
  914. result.w = this.w * otherVector.w;
  915. return this;
  916. };
  917. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  918. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  919. };
  920. Vector4.prototype.divide = function (otherVector) {
  921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  922. };
  923. Vector4.prototype.divideToRef = function (otherVector, result) {
  924. result.x = this.x / otherVector.x;
  925. result.y = this.y / otherVector.y;
  926. result.z = this.z / otherVector.z;
  927. result.w = this.w / otherVector.w;
  928. return this;
  929. };
  930. Vector4.prototype.MinimizeInPlace = function (other) {
  931. if (other.x < this.x)
  932. this.x = other.x;
  933. if (other.y < this.y)
  934. this.y = other.y;
  935. if (other.z < this.z)
  936. this.z = other.z;
  937. if (other.w < this.w)
  938. this.w = other.w;
  939. return this;
  940. };
  941. Vector4.prototype.MaximizeInPlace = function (other) {
  942. if (other.x > this.x)
  943. this.x = other.x;
  944. if (other.y > this.y)
  945. this.y = other.y;
  946. if (other.z > this.z)
  947. this.z = other.z;
  948. if (other.w > this.w)
  949. this.w = other.w;
  950. return this;
  951. };
  952. // Properties
  953. Vector4.prototype.length = function () {
  954. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  955. };
  956. Vector4.prototype.lengthSquared = function () {
  957. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  958. };
  959. // Methods
  960. Vector4.prototype.normalize = function () {
  961. var len = this.length();
  962. if (len === 0)
  963. return this;
  964. var num = 1.0 / len;
  965. this.x *= num;
  966. this.y *= num;
  967. this.z *= num;
  968. this.w *= num;
  969. return this;
  970. };
  971. Vector4.prototype.clone = function () {
  972. return new Vector4(this.x, this.y, this.z, this.w);
  973. };
  974. Vector4.prototype.copyFrom = function (source) {
  975. this.x = source.x;
  976. this.y = source.y;
  977. this.z = source.z;
  978. this.w = source.w;
  979. return this;
  980. };
  981. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. this.w = w;
  986. return this;
  987. };
  988. // Statics
  989. Vector4.FromArray = function (array, offset) {
  990. if (!offset) {
  991. offset = 0;
  992. }
  993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  994. };
  995. Vector4.FromArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1002. result.x = array[offset];
  1003. result.y = array[offset + 1];
  1004. result.z = array[offset + 2];
  1005. result.w = array[offset + 3];
  1006. };
  1007. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1008. result.x = x;
  1009. result.y = y;
  1010. result.z = z;
  1011. result.w = w;
  1012. };
  1013. Vector4.Zero = function () {
  1014. return new Vector4(0, 0, 0, 0);
  1015. };
  1016. Vector4.Normalize = function (vector) {
  1017. var result = Vector4.Zero();
  1018. Vector4.NormalizeToRef(vector, result);
  1019. return result;
  1020. };
  1021. Vector4.NormalizeToRef = function (vector, result) {
  1022. result.copyFrom(vector);
  1023. result.normalize();
  1024. };
  1025. Vector4.Minimize = function (left, right) {
  1026. var min = left.clone();
  1027. min.MinimizeInPlace(right);
  1028. return min;
  1029. };
  1030. Vector4.Maximize = function (left, right) {
  1031. var max = left.clone();
  1032. max.MaximizeInPlace(right);
  1033. return max;
  1034. };
  1035. Vector4.Distance = function (value1, value2) {
  1036. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1037. };
  1038. Vector4.DistanceSquared = function (value1, value2) {
  1039. var x = value1.x - value2.x;
  1040. var y = value1.y - value2.y;
  1041. var z = value1.z - value2.z;
  1042. var w = value1.w - value2.w;
  1043. return (x * x) + (y * y) + (z * z) + (w * w);
  1044. };
  1045. Vector4.Center = function (value1, value2) {
  1046. var center = value1.add(value2);
  1047. center.scaleInPlace(0.5);
  1048. return center;
  1049. };
  1050. return Vector4;
  1051. })();
  1052. BABYLON.Vector4 = Vector4;
  1053. var Quaternion = (function () {
  1054. function Quaternion(x, y, z, w) {
  1055. if (x === void 0) { x = 0; }
  1056. if (y === void 0) { y = 0; }
  1057. if (z === void 0) { z = 0; }
  1058. if (w === void 0) { w = 1; }
  1059. this.x = x;
  1060. this.y = y;
  1061. this.z = z;
  1062. this.w = w;
  1063. }
  1064. Quaternion.prototype.toString = function () {
  1065. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1066. };
  1067. Quaternion.prototype.asArray = function () {
  1068. return [this.x, this.y, this.z, this.w];
  1069. };
  1070. Quaternion.prototype.equals = function (otherQuaternion) {
  1071. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1072. };
  1073. Quaternion.prototype.clone = function () {
  1074. return new Quaternion(this.x, this.y, this.z, this.w);
  1075. };
  1076. Quaternion.prototype.copyFrom = function (other) {
  1077. this.x = other.x;
  1078. this.y = other.y;
  1079. this.z = other.z;
  1080. this.w = other.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1084. this.x = x;
  1085. this.y = y;
  1086. this.z = z;
  1087. this.w = w;
  1088. return this;
  1089. };
  1090. Quaternion.prototype.add = function (other) {
  1091. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1092. };
  1093. Quaternion.prototype.subtract = function (other) {
  1094. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1095. };
  1096. Quaternion.prototype.scale = function (value) {
  1097. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1098. };
  1099. Quaternion.prototype.multiply = function (q1) {
  1100. var result = new Quaternion(0, 0, 0, 1.0);
  1101. this.multiplyToRef(q1, result);
  1102. return result;
  1103. };
  1104. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1105. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1106. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1107. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1108. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1109. return this;
  1110. };
  1111. Quaternion.prototype.length = function () {
  1112. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1113. };
  1114. Quaternion.prototype.normalize = function () {
  1115. var length = 1.0 / this.length();
  1116. this.x *= length;
  1117. this.y *= length;
  1118. this.z *= length;
  1119. this.w *= length;
  1120. return this;
  1121. };
  1122. Quaternion.prototype.toEulerAngles = function () {
  1123. var result = Vector3.Zero();
  1124. this.toEulerAnglesToRef(result);
  1125. return result;
  1126. };
  1127. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1128. //result is an EulerAngles in the in the z-x-z convention
  1129. var qx = this.x;
  1130. var qy = this.y;
  1131. var qz = this.z;
  1132. var qw = this.w;
  1133. var qxy = qx * qy;
  1134. var qxz = qx * qz;
  1135. var qwy = qw * qy;
  1136. var qwz = qw * qz;
  1137. var qwx = qw * qx;
  1138. var qyz = qy * qz;
  1139. var sqx = qx * qx;
  1140. var sqy = qy * qy;
  1141. var determinant = sqx + sqy;
  1142. if (determinant !== 0.000 && determinant !== 1.000) {
  1143. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1144. result.y = Math.acos(1 - 2 * determinant);
  1145. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1146. }
  1147. else {
  1148. if (determinant === 0.0) {
  1149. result.x = 0.0;
  1150. result.y = 0.0;
  1151. 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)
  1152. }
  1153. else {
  1154. 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)
  1155. result.y = Math.PI;
  1156. result.z = 0.0;
  1157. }
  1158. }
  1159. return this;
  1160. };
  1161. Quaternion.prototype.toRotationMatrix = function (result) {
  1162. var xx = this.x * this.x;
  1163. var yy = this.y * this.y;
  1164. var zz = this.z * this.z;
  1165. var xy = this.x * this.y;
  1166. var zw = this.z * this.w;
  1167. var zx = this.z * this.x;
  1168. var yw = this.y * this.w;
  1169. var yz = this.y * this.z;
  1170. var xw = this.x * this.w;
  1171. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1172. result.m[1] = 2.0 * (xy + zw);
  1173. result.m[2] = 2.0 * (zx - yw);
  1174. result.m[3] = 0;
  1175. result.m[4] = 2.0 * (xy - zw);
  1176. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1177. result.m[6] = 2.0 * (yz + xw);
  1178. result.m[7] = 0;
  1179. result.m[8] = 2.0 * (zx + yw);
  1180. result.m[9] = 2.0 * (yz - xw);
  1181. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1182. result.m[11] = 0;
  1183. result.m[12] = 0;
  1184. result.m[13] = 0;
  1185. result.m[14] = 0;
  1186. result.m[15] = 1.0;
  1187. return this;
  1188. };
  1189. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1190. Quaternion.FromRotationMatrixToRef(matrix, this);
  1191. return this;
  1192. };
  1193. // Statics
  1194. Quaternion.FromRotationMatrix = function (matrix) {
  1195. var result = new Quaternion();
  1196. Quaternion.FromRotationMatrixToRef(matrix, result);
  1197. return result;
  1198. };
  1199. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1200. var data = matrix.m;
  1201. var m11 = data[0], m12 = data[4], m13 = data[8];
  1202. var m21 = data[1], m22 = data[5], m23 = data[9];
  1203. var m31 = data[2], m32 = data[6], m33 = data[10];
  1204. var trace = m11 + m22 + m33;
  1205. var s;
  1206. if (trace > 0) {
  1207. s = 0.5 / Math.sqrt(trace + 1.0);
  1208. result.w = 0.25 / s;
  1209. result.x = (m32 - m23) * s;
  1210. result.y = (m13 - m31) * s;
  1211. result.z = (m21 - m12) * s;
  1212. }
  1213. else if (m11 > m22 && m11 > m33) {
  1214. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1215. result.w = (m32 - m23) / s;
  1216. result.x = 0.25 * s;
  1217. result.y = (m12 + m21) / s;
  1218. result.z = (m13 + m31) / s;
  1219. }
  1220. else if (m22 > m33) {
  1221. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1222. result.w = (m13 - m31) / s;
  1223. result.x = (m12 + m21) / s;
  1224. result.y = 0.25 * s;
  1225. result.z = (m23 + m32) / s;
  1226. }
  1227. else {
  1228. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1229. result.w = (m21 - m12) / s;
  1230. result.x = (m13 + m31) / s;
  1231. result.y = (m23 + m32) / s;
  1232. result.z = 0.25 * s;
  1233. }
  1234. };
  1235. Quaternion.Inverse = function (q) {
  1236. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1237. };
  1238. Quaternion.Identity = function () {
  1239. return new Quaternion(0, 0, 0, 1);
  1240. };
  1241. Quaternion.RotationAxis = function (axis, angle) {
  1242. var result = new Quaternion();
  1243. var sin = Math.sin(angle / 2);
  1244. result.w = Math.cos(angle / 2);
  1245. result.x = axis.x * sin;
  1246. result.y = axis.y * sin;
  1247. result.z = axis.z * sin;
  1248. return result;
  1249. };
  1250. Quaternion.FromArray = function (array, offset) {
  1251. if (!offset) {
  1252. offset = 0;
  1253. }
  1254. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1255. };
  1256. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1257. var result = new Quaternion();
  1258. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1259. return result;
  1260. };
  1261. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1262. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1263. var halfRoll = roll * 0.5;
  1264. var halfPitch = pitch * 0.5;
  1265. var halfYaw = yaw * 0.5;
  1266. var sinRoll = Math.sin(halfRoll);
  1267. var cosRoll = Math.cos(halfRoll);
  1268. var sinPitch = Math.sin(halfPitch);
  1269. var cosPitch = Math.cos(halfPitch);
  1270. var sinYaw = Math.sin(halfYaw);
  1271. var cosYaw = Math.cos(halfYaw);
  1272. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1273. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1274. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1275. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1276. };
  1277. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1278. var result = new Quaternion();
  1279. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1280. return result;
  1281. };
  1282. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1283. // Produces a quaternion from Euler angles in the z-x-z orientation
  1284. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1285. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1286. var halfBeta = beta * 0.5;
  1287. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1288. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1289. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1290. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1291. };
  1292. Quaternion.Slerp = function (left, right, amount) {
  1293. var num2;
  1294. var num3;
  1295. var num = amount;
  1296. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1297. var flag = false;
  1298. if (num4 < 0) {
  1299. flag = true;
  1300. num4 = -num4;
  1301. }
  1302. if (num4 > 0.999999) {
  1303. num3 = 1 - num;
  1304. num2 = flag ? -num : num;
  1305. }
  1306. else {
  1307. var num5 = Math.acos(num4);
  1308. var num6 = (1.0 / Math.sin(num5));
  1309. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1310. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1311. }
  1312. 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));
  1313. };
  1314. return Quaternion;
  1315. })();
  1316. BABYLON.Quaternion = Quaternion;
  1317. var Matrix = (function () {
  1318. function Matrix() {
  1319. this.m = new Float32Array(16);
  1320. }
  1321. // Properties
  1322. Matrix.prototype.isIdentity = function () {
  1323. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1324. return false;
  1325. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1326. return false;
  1327. return true;
  1328. };
  1329. Matrix.prototype.determinant = function () {
  1330. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1331. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1332. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1333. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1334. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1335. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1336. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1337. };
  1338. // Methods
  1339. Matrix.prototype.toArray = function () {
  1340. return this.m;
  1341. };
  1342. Matrix.prototype.asArray = function () {
  1343. return this.toArray();
  1344. };
  1345. Matrix.prototype.invert = function () {
  1346. this.invertToRef(this);
  1347. return this;
  1348. };
  1349. Matrix.prototype.invertToRef = function (other) {
  1350. var l1 = this.m[0];
  1351. var l2 = this.m[1];
  1352. var l3 = this.m[2];
  1353. var l4 = this.m[3];
  1354. var l5 = this.m[4];
  1355. var l6 = this.m[5];
  1356. var l7 = this.m[6];
  1357. var l8 = this.m[7];
  1358. var l9 = this.m[8];
  1359. var l10 = this.m[9];
  1360. var l11 = this.m[10];
  1361. var l12 = this.m[11];
  1362. var l13 = this.m[12];
  1363. var l14 = this.m[13];
  1364. var l15 = this.m[14];
  1365. var l16 = this.m[15];
  1366. var l17 = (l11 * l16) - (l12 * l15);
  1367. var l18 = (l10 * l16) - (l12 * l14);
  1368. var l19 = (l10 * l15) - (l11 * l14);
  1369. var l20 = (l9 * l16) - (l12 * l13);
  1370. var l21 = (l9 * l15) - (l11 * l13);
  1371. var l22 = (l9 * l14) - (l10 * l13);
  1372. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1373. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1374. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1375. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1376. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1377. var l28 = (l7 * l16) - (l8 * l15);
  1378. var l29 = (l6 * l16) - (l8 * l14);
  1379. var l30 = (l6 * l15) - (l7 * l14);
  1380. var l31 = (l5 * l16) - (l8 * l13);
  1381. var l32 = (l5 * l15) - (l7 * l13);
  1382. var l33 = (l5 * l14) - (l6 * l13);
  1383. var l34 = (l7 * l12) - (l8 * l11);
  1384. var l35 = (l6 * l12) - (l8 * l10);
  1385. var l36 = (l6 * l11) - (l7 * l10);
  1386. var l37 = (l5 * l12) - (l8 * l9);
  1387. var l38 = (l5 * l11) - (l7 * l9);
  1388. var l39 = (l5 * l10) - (l6 * l9);
  1389. other.m[0] = l23 * l27;
  1390. other.m[4] = l24 * l27;
  1391. other.m[8] = l25 * l27;
  1392. other.m[12] = l26 * l27;
  1393. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1394. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1395. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1396. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1397. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1398. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1399. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1400. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1401. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1402. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1403. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1404. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1405. return this;
  1406. };
  1407. Matrix.prototype.invertToRefSIMD = function (other) {
  1408. var src = this.m;
  1409. var dest = other.m;
  1410. var row0, row1, row2, row3;
  1411. var tmp1;
  1412. var minor0, minor1, minor2, minor3;
  1413. var det;
  1414. // Load the 4 rows
  1415. var src0 = SIMD.float32x4.load(src, 0);
  1416. var src1 = SIMD.float32x4.load(src, 4);
  1417. var src2 = SIMD.float32x4.load(src, 8);
  1418. var src3 = SIMD.float32x4.load(src, 12);
  1419. // Transpose the source matrix. Sort of. Not a true transpose operation
  1420. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1421. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1422. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1423. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1424. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1425. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1426. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1427. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1428. // This is a true transposition, but it will lead to an incorrect result
  1429. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1430. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1431. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1432. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1433. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1434. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1435. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1436. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1437. // ----
  1438. tmp1 = SIMD.float32x4.mul(row2, row3);
  1439. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1440. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1441. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1443. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1444. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1445. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. // ----
  1447. tmp1 = SIMD.float32x4.mul(row1, row2);
  1448. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1449. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1450. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1452. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1453. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1454. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1455. // ----
  1456. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1457. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1458. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1460. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1462. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1463. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1464. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1465. // ----
  1466. tmp1 = SIMD.float32x4.mul(row0, row1);
  1467. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1468. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1469. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1471. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1472. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1473. // ----
  1474. tmp1 = SIMD.float32x4.mul(row0, row3);
  1475. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1476. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1477. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1480. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1481. // ----
  1482. tmp1 = SIMD.float32x4.mul(row0, row2);
  1483. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1484. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1485. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1486. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1487. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1488. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1489. // Compute determinant
  1490. det = SIMD.float32x4.mul(row0, minor0);
  1491. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1492. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1493. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1494. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1495. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1496. // These shuffles aren't necessary if the faulty transposition is done
  1497. // up at the top of this function.
  1498. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1499. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1500. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1501. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1502. // Compute final values by multiplying with 1/det
  1503. minor0 = SIMD.float32x4.mul(det, minor0);
  1504. minor1 = SIMD.float32x4.mul(det, minor1);
  1505. minor2 = SIMD.float32x4.mul(det, minor2);
  1506. minor3 = SIMD.float32x4.mul(det, minor3);
  1507. SIMD.float32x4.store(dest, 0, minor0);
  1508. SIMD.float32x4.store(dest, 4, minor1);
  1509. SIMD.float32x4.store(dest, 8, minor2);
  1510. SIMD.float32x4.store(dest, 12, minor3);
  1511. return this;
  1512. };
  1513. Matrix.prototype.setTranslation = function (vector3) {
  1514. this.m[12] = vector3.x;
  1515. this.m[13] = vector3.y;
  1516. this.m[14] = vector3.z;
  1517. return this;
  1518. };
  1519. Matrix.prototype.multiply = function (other) {
  1520. var result = new Matrix();
  1521. this.multiplyToRef(other, result);
  1522. return result;
  1523. };
  1524. Matrix.prototype.copyFrom = function (other) {
  1525. for (var index = 0; index < 16; index++) {
  1526. this.m[index] = other.m[index];
  1527. }
  1528. return this;
  1529. };
  1530. Matrix.prototype.copyToArray = function (array, offset) {
  1531. if (offset === void 0) { offset = 0; }
  1532. for (var index = 0; index < 16; index++) {
  1533. array[offset + index] = this.m[index];
  1534. }
  1535. return this;
  1536. };
  1537. Matrix.prototype.multiplyToRef = function (other, result) {
  1538. this.multiplyToArray(other, result.m, 0);
  1539. return this;
  1540. };
  1541. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1542. var tm0 = this.m[0];
  1543. var tm1 = this.m[1];
  1544. var tm2 = this.m[2];
  1545. var tm3 = this.m[3];
  1546. var tm4 = this.m[4];
  1547. var tm5 = this.m[5];
  1548. var tm6 = this.m[6];
  1549. var tm7 = this.m[7];
  1550. var tm8 = this.m[8];
  1551. var tm9 = this.m[9];
  1552. var tm10 = this.m[10];
  1553. var tm11 = this.m[11];
  1554. var tm12 = this.m[12];
  1555. var tm13 = this.m[13];
  1556. var tm14 = this.m[14];
  1557. var tm15 = this.m[15];
  1558. var om0 = other.m[0];
  1559. var om1 = other.m[1];
  1560. var om2 = other.m[2];
  1561. var om3 = other.m[3];
  1562. var om4 = other.m[4];
  1563. var om5 = other.m[5];
  1564. var om6 = other.m[6];
  1565. var om7 = other.m[7];
  1566. var om8 = other.m[8];
  1567. var om9 = other.m[9];
  1568. var om10 = other.m[10];
  1569. var om11 = other.m[11];
  1570. var om12 = other.m[12];
  1571. var om13 = other.m[13];
  1572. var om14 = other.m[14];
  1573. var om15 = other.m[15];
  1574. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1575. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1576. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1577. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1578. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1579. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1580. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1581. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1582. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1583. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1584. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1585. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1586. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1587. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1588. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1589. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1590. return this;
  1591. };
  1592. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1593. if (offset === void 0) { offset = 0; }
  1594. var tm = this.m;
  1595. var om = other.m;
  1596. var om0 = SIMD.float32x4.load(om, 0);
  1597. var om1 = SIMD.float32x4.load(om, 4);
  1598. var om2 = SIMD.float32x4.load(om, 8);
  1599. var om3 = SIMD.float32x4.load(om, 12);
  1600. var tm0 = SIMD.float32x4.load(tm, 0);
  1601. 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)))));
  1602. var tm1 = SIMD.float32x4.load(tm, 4);
  1603. 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)))));
  1604. var tm2 = SIMD.float32x4.load(tm, 8);
  1605. 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)))));
  1606. var tm3 = SIMD.float32x4.load(tm, 12);
  1607. 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)))));
  1608. };
  1609. Matrix.prototype.equals = function (value) {
  1610. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1611. };
  1612. Matrix.prototype.clone = function () {
  1613. 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]);
  1614. };
  1615. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1616. translation.x = this.m[12];
  1617. translation.y = this.m[13];
  1618. translation.z = this.m[14];
  1619. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1620. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1621. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1622. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1623. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1624. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1625. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1626. rotation.x = 0;
  1627. rotation.y = 0;
  1628. rotation.z = 0;
  1629. rotation.w = 1;
  1630. return false;
  1631. }
  1632. 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);
  1633. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1634. return true;
  1635. };
  1636. // Statics
  1637. Matrix.FromArray = function (array, offset) {
  1638. var result = new Matrix();
  1639. if (!offset) {
  1640. offset = 0;
  1641. }
  1642. Matrix.FromArrayToRef(array, offset, result);
  1643. return result;
  1644. };
  1645. Matrix.FromArrayToRef = function (array, offset, result) {
  1646. for (var index = 0; index < 16; index++) {
  1647. result.m[index] = array[index + offset];
  1648. }
  1649. };
  1650. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1651. result.m[0] = initialM11;
  1652. result.m[1] = initialM12;
  1653. result.m[2] = initialM13;
  1654. result.m[3] = initialM14;
  1655. result.m[4] = initialM21;
  1656. result.m[5] = initialM22;
  1657. result.m[6] = initialM23;
  1658. result.m[7] = initialM24;
  1659. result.m[8] = initialM31;
  1660. result.m[9] = initialM32;
  1661. result.m[10] = initialM33;
  1662. result.m[11] = initialM34;
  1663. result.m[12] = initialM41;
  1664. result.m[13] = initialM42;
  1665. result.m[14] = initialM43;
  1666. result.m[15] = initialM44;
  1667. };
  1668. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1669. var result = new Matrix();
  1670. result.m[0] = initialM11;
  1671. result.m[1] = initialM12;
  1672. result.m[2] = initialM13;
  1673. result.m[3] = initialM14;
  1674. result.m[4] = initialM21;
  1675. result.m[5] = initialM22;
  1676. result.m[6] = initialM23;
  1677. result.m[7] = initialM24;
  1678. result.m[8] = initialM31;
  1679. result.m[9] = initialM32;
  1680. result.m[10] = initialM33;
  1681. result.m[11] = initialM34;
  1682. result.m[12] = initialM41;
  1683. result.m[13] = initialM42;
  1684. result.m[14] = initialM43;
  1685. result.m[15] = initialM44;
  1686. return result;
  1687. };
  1688. Matrix.Compose = function (scale, rotation, translation) {
  1689. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1690. var rotationMatrix = Matrix.Identity();
  1691. rotation.toRotationMatrix(rotationMatrix);
  1692. result = result.multiply(rotationMatrix);
  1693. result.setTranslation(translation);
  1694. return result;
  1695. };
  1696. Matrix.Identity = function () {
  1697. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1698. };
  1699. Matrix.IdentityToRef = function (result) {
  1700. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1701. };
  1702. Matrix.Zero = function () {
  1703. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1704. };
  1705. Matrix.RotationX = function (angle) {
  1706. var result = new Matrix();
  1707. Matrix.RotationXToRef(angle, result);
  1708. return result;
  1709. };
  1710. Matrix.Invert = function (source) {
  1711. var result = new Matrix();
  1712. source.invertToRef(result);
  1713. return result;
  1714. };
  1715. Matrix.RotationXToRef = function (angle, result) {
  1716. var s = Math.sin(angle);
  1717. var c = Math.cos(angle);
  1718. result.m[0] = 1.0;
  1719. result.m[15] = 1.0;
  1720. result.m[5] = c;
  1721. result.m[10] = c;
  1722. result.m[9] = -s;
  1723. result.m[6] = s;
  1724. result.m[1] = 0;
  1725. result.m[2] = 0;
  1726. result.m[3] = 0;
  1727. result.m[4] = 0;
  1728. result.m[7] = 0;
  1729. result.m[8] = 0;
  1730. result.m[11] = 0;
  1731. result.m[12] = 0;
  1732. result.m[13] = 0;
  1733. result.m[14] = 0;
  1734. };
  1735. Matrix.RotationY = function (angle) {
  1736. var result = new Matrix();
  1737. Matrix.RotationYToRef(angle, result);
  1738. return result;
  1739. };
  1740. Matrix.RotationYToRef = function (angle, result) {
  1741. var s = Math.sin(angle);
  1742. var c = Math.cos(angle);
  1743. result.m[5] = 1.0;
  1744. result.m[15] = 1.0;
  1745. result.m[0] = c;
  1746. result.m[2] = -s;
  1747. result.m[8] = s;
  1748. result.m[10] = c;
  1749. result.m[1] = 0;
  1750. result.m[3] = 0;
  1751. result.m[4] = 0;
  1752. result.m[6] = 0;
  1753. result.m[7] = 0;
  1754. result.m[9] = 0;
  1755. result.m[11] = 0;
  1756. result.m[12] = 0;
  1757. result.m[13] = 0;
  1758. result.m[14] = 0;
  1759. };
  1760. Matrix.RotationZ = function (angle) {
  1761. var result = new Matrix();
  1762. Matrix.RotationZToRef(angle, result);
  1763. return result;
  1764. };
  1765. Matrix.RotationZToRef = function (angle, result) {
  1766. var s = Math.sin(angle);
  1767. var c = Math.cos(angle);
  1768. result.m[10] = 1.0;
  1769. result.m[15] = 1.0;
  1770. result.m[0] = c;
  1771. result.m[1] = s;
  1772. result.m[4] = -s;
  1773. result.m[5] = c;
  1774. result.m[2] = 0;
  1775. result.m[3] = 0;
  1776. result.m[6] = 0;
  1777. result.m[7] = 0;
  1778. result.m[8] = 0;
  1779. result.m[9] = 0;
  1780. result.m[11] = 0;
  1781. result.m[12] = 0;
  1782. result.m[13] = 0;
  1783. result.m[14] = 0;
  1784. };
  1785. Matrix.RotationAxis = function (axis, angle) {
  1786. var s = Math.sin(-angle);
  1787. var c = Math.cos(-angle);
  1788. var c1 = 1 - c;
  1789. axis.normalize();
  1790. var result = Matrix.Zero();
  1791. result.m[0] = (axis.x * axis.x) * c1 + c;
  1792. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1793. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1794. result.m[3] = 0.0;
  1795. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1796. result.m[5] = (axis.y * axis.y) * c1 + c;
  1797. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1798. result.m[7] = 0.0;
  1799. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1800. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1801. result.m[10] = (axis.z * axis.z) * c1 + c;
  1802. result.m[11] = 0.0;
  1803. result.m[15] = 1.0;
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1807. var result = new Matrix();
  1808. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1809. return result;
  1810. };
  1811. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1812. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1813. this._tempQuaternion.toRotationMatrix(result);
  1814. };
  1815. Matrix.Scaling = function (x, y, z) {
  1816. var result = Matrix.Zero();
  1817. Matrix.ScalingToRef(x, y, z, result);
  1818. return result;
  1819. };
  1820. Matrix.ScalingToRef = function (x, y, z, result) {
  1821. result.m[0] = x;
  1822. result.m[1] = 0;
  1823. result.m[2] = 0;
  1824. result.m[3] = 0;
  1825. result.m[4] = 0;
  1826. result.m[5] = y;
  1827. result.m[6] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[9] = 0;
  1831. result.m[10] = z;
  1832. result.m[11] = 0;
  1833. result.m[12] = 0;
  1834. result.m[13] = 0;
  1835. result.m[14] = 0;
  1836. result.m[15] = 1.0;
  1837. };
  1838. Matrix.Translation = function (x, y, z) {
  1839. var result = Matrix.Identity();
  1840. Matrix.TranslationToRef(x, y, z, result);
  1841. return result;
  1842. };
  1843. Matrix.TranslationToRef = function (x, y, z, result) {
  1844. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1845. };
  1846. Matrix.LookAtLH = function (eye, target, up) {
  1847. var result = Matrix.Zero();
  1848. Matrix.LookAtLHToRef(eye, target, up, result);
  1849. return result;
  1850. };
  1851. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1852. // Z axis
  1853. target.subtractToRef(eye, this._zAxis);
  1854. this._zAxis.normalize();
  1855. // X axis
  1856. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1857. this._xAxis.normalize();
  1858. // Y axis
  1859. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1860. this._yAxis.normalize();
  1861. // Eye angles
  1862. var ex = -Vector3.Dot(this._xAxis, eye);
  1863. var ey = -Vector3.Dot(this._yAxis, eye);
  1864. var ez = -Vector3.Dot(this._zAxis, eye);
  1865. 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);
  1866. };
  1867. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1868. var out = result.m;
  1869. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1870. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1871. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1872. // cc.kmVec3Subtract(f, pCenter, pEye);
  1873. var f = SIMD.float32x4.sub(center, eye);
  1874. // cc.kmVec3Normalize(f, f);
  1875. var tmp = SIMD.float32x4.mul(f, f);
  1876. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1877. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1878. // cc.kmVec3Assign(up, pUp);
  1879. // cc.kmVec3Normalize(up, up);
  1880. tmp = SIMD.float32x4.mul(up, up);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1883. // cc.kmVec3Cross(s, f, up);
  1884. 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)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1889. // cc.kmVec3Cross(u, s, f);
  1890. 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)));
  1891. // cc.kmVec3Normalize(s, s);
  1892. tmp = SIMD.float32x4.mul(s, s);
  1893. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1894. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1895. var zero = SIMD.float32x4.splat(0.0);
  1896. s = SIMD.float32x4.neg(s);
  1897. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1898. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1899. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1900. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1901. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1902. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1903. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1904. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1905. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1906. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1907. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1908. var b3 = SIMD.float32x4.neg(eye);
  1909. b3 = SIMD.float32x4.withW(b3, 1.0);
  1910. 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)))));
  1911. 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)))));
  1912. 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)))));
  1913. 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)))));
  1914. };
  1915. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1916. var matrix = Matrix.Zero();
  1917. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1918. return matrix;
  1919. };
  1920. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1921. var hw = 2.0 / width;
  1922. var hh = 2.0 / height;
  1923. var id = 1.0 / (zfar - znear);
  1924. var nid = znear / (znear - zfar);
  1925. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1926. };
  1927. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1928. var matrix = Matrix.Zero();
  1929. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1930. return matrix;
  1931. };
  1932. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1933. result.m[0] = 2.0 / (right - left);
  1934. result.m[1] = result.m[2] = result.m[3] = 0;
  1935. result.m[5] = 2.0 / (top - bottom);
  1936. result.m[4] = result.m[6] = result.m[7] = 0;
  1937. result.m[10] = -1.0 / (znear - zfar);
  1938. result.m[8] = result.m[9] = result.m[11] = 0;
  1939. result.m[12] = (left + right) / (left - right);
  1940. result.m[13] = (top + bottom) / (bottom - top);
  1941. result.m[14] = znear / (znear - zfar);
  1942. result.m[15] = 1.0;
  1943. };
  1944. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1945. var matrix = Matrix.Zero();
  1946. matrix.m[0] = (2.0 * znear) / width;
  1947. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1948. matrix.m[5] = (2.0 * znear) / height;
  1949. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1950. matrix.m[10] = -zfar / (znear - zfar);
  1951. matrix.m[8] = matrix.m[9] = 0.0;
  1952. matrix.m[11] = 1.0;
  1953. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1954. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1955. return matrix;
  1956. };
  1957. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1958. var matrix = Matrix.Zero();
  1959. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1960. return matrix;
  1961. };
  1962. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1963. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1964. var tan = 1.0 / (Math.tan(fov * 0.5));
  1965. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1966. if (v_fixed) {
  1967. result.m[0] = tan / aspect;
  1968. }
  1969. else {
  1970. result.m[0] = tan;
  1971. }
  1972. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1973. if (v_fixed) {
  1974. result.m[5] = tan;
  1975. }
  1976. else {
  1977. result.m[5] = tan * aspect;
  1978. }
  1979. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1980. result.m[8] = result.m[9] = 0.0;
  1981. result.m[10] = -zfar / (znear - zfar);
  1982. result.m[11] = 1.0;
  1983. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1984. result.m[14] = (znear * zfar) / (znear - zfar);
  1985. };
  1986. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1987. var cw = viewport.width;
  1988. var ch = viewport.height;
  1989. var cx = viewport.x;
  1990. var cy = viewport.y;
  1991. 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);
  1992. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1993. };
  1994. Matrix.Transpose = function (matrix) {
  1995. var result = new Matrix();
  1996. result.m[0] = matrix.m[0];
  1997. result.m[1] = matrix.m[4];
  1998. result.m[2] = matrix.m[8];
  1999. result.m[3] = matrix.m[12];
  2000. result.m[4] = matrix.m[1];
  2001. result.m[5] = matrix.m[5];
  2002. result.m[6] = matrix.m[9];
  2003. result.m[7] = matrix.m[13];
  2004. result.m[8] = matrix.m[2];
  2005. result.m[9] = matrix.m[6];
  2006. result.m[10] = matrix.m[10];
  2007. result.m[11] = matrix.m[14];
  2008. result.m[12] = matrix.m[3];
  2009. result.m[13] = matrix.m[7];
  2010. result.m[14] = matrix.m[11];
  2011. result.m[15] = matrix.m[15];
  2012. return result;
  2013. };
  2014. Matrix.Reflection = function (plane) {
  2015. var matrix = new Matrix();
  2016. Matrix.ReflectionToRef(plane, matrix);
  2017. return matrix;
  2018. };
  2019. Matrix.ReflectionToRef = function (plane, result) {
  2020. plane.normalize();
  2021. var x = plane.normal.x;
  2022. var y = plane.normal.y;
  2023. var z = plane.normal.z;
  2024. var temp = -2 * x;
  2025. var temp2 = -2 * y;
  2026. var temp3 = -2 * z;
  2027. result.m[0] = (temp * x) + 1;
  2028. result.m[1] = temp2 * x;
  2029. result.m[2] = temp3 * x;
  2030. result.m[3] = 0.0;
  2031. result.m[4] = temp * y;
  2032. result.m[5] = (temp2 * y) + 1;
  2033. result.m[6] = temp3 * y;
  2034. result.m[7] = 0.0;
  2035. result.m[8] = temp * z;
  2036. result.m[9] = temp2 * z;
  2037. result.m[10] = (temp3 * z) + 1;
  2038. result.m[11] = 0.0;
  2039. result.m[12] = temp * plane.d;
  2040. result.m[13] = temp2 * plane.d;
  2041. result.m[14] = temp3 * plane.d;
  2042. result.m[15] = 1.0;
  2043. };
  2044. Matrix._tempQuaternion = new Quaternion();
  2045. Matrix._xAxis = Vector3.Zero();
  2046. Matrix._yAxis = Vector3.Zero();
  2047. Matrix._zAxis = Vector3.Zero();
  2048. return Matrix;
  2049. })();
  2050. BABYLON.Matrix = Matrix;
  2051. var Plane = (function () {
  2052. function Plane(a, b, c, d) {
  2053. this.normal = new Vector3(a, b, c);
  2054. this.d = d;
  2055. }
  2056. Plane.prototype.asArray = function () {
  2057. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2058. };
  2059. // Methods
  2060. Plane.prototype.clone = function () {
  2061. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2062. };
  2063. Plane.prototype.normalize = function () {
  2064. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2065. var magnitude = 0;
  2066. if (norm !== 0) {
  2067. magnitude = 1.0 / norm;
  2068. }
  2069. this.normal.x *= magnitude;
  2070. this.normal.y *= magnitude;
  2071. this.normal.z *= magnitude;
  2072. this.d *= magnitude;
  2073. return this;
  2074. };
  2075. Plane.prototype.transform = function (transformation) {
  2076. var transposedMatrix = Matrix.Transpose(transformation);
  2077. var x = this.normal.x;
  2078. var y = this.normal.y;
  2079. var z = this.normal.z;
  2080. var d = this.d;
  2081. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2082. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2083. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2084. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2085. return new Plane(normalX, normalY, normalZ, finalD);
  2086. };
  2087. Plane.prototype.dotCoordinate = function (point) {
  2088. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2089. };
  2090. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2091. var x1 = point2.x - point1.x;
  2092. var y1 = point2.y - point1.y;
  2093. var z1 = point2.z - point1.z;
  2094. var x2 = point3.x - point1.x;
  2095. var y2 = point3.y - point1.y;
  2096. var z2 = point3.z - point1.z;
  2097. var yz = (y1 * z2) - (z1 * y2);
  2098. var xz = (z1 * x2) - (x1 * z2);
  2099. var xy = (x1 * y2) - (y1 * x2);
  2100. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2101. var invPyth;
  2102. if (pyth !== 0) {
  2103. invPyth = 1.0 / pyth;
  2104. }
  2105. else {
  2106. invPyth = 0;
  2107. }
  2108. this.normal.x = yz * invPyth;
  2109. this.normal.y = xz * invPyth;
  2110. this.normal.z = xy * invPyth;
  2111. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2112. return this;
  2113. };
  2114. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2115. var dot = Vector3.Dot(this.normal, direction);
  2116. return (dot <= epsilon);
  2117. };
  2118. Plane.prototype.signedDistanceTo = function (point) {
  2119. return Vector3.Dot(point, this.normal) + this.d;
  2120. };
  2121. // Statics
  2122. Plane.FromArray = function (array) {
  2123. return new Plane(array[0], array[1], array[2], array[3]);
  2124. };
  2125. Plane.FromPoints = function (point1, point2, point3) {
  2126. var result = new Plane(0, 0, 0, 0);
  2127. result.copyFromPoints(point1, point2, point3);
  2128. return result;
  2129. };
  2130. Plane.FromPositionAndNormal = function (origin, normal) {
  2131. var result = new Plane(0, 0, 0, 0);
  2132. normal.normalize();
  2133. result.normal = normal;
  2134. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2135. return result;
  2136. };
  2137. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2138. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2139. return Vector3.Dot(point, normal) + d;
  2140. };
  2141. return Plane;
  2142. })();
  2143. BABYLON.Plane = Plane;
  2144. var Viewport = (function () {
  2145. function Viewport(x, y, width, height) {
  2146. this.x = x;
  2147. this.y = y;
  2148. this.width = width;
  2149. this.height = height;
  2150. }
  2151. Viewport.prototype.toGlobal = function (engine) {
  2152. var width = engine.getRenderWidth();
  2153. var height = engine.getRenderHeight();
  2154. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2155. };
  2156. return Viewport;
  2157. })();
  2158. BABYLON.Viewport = Viewport;
  2159. var Frustum = (function () {
  2160. function Frustum() {
  2161. }
  2162. Frustum.GetPlanes = function (transform) {
  2163. var frustumPlanes = [];
  2164. for (var index = 0; index < 6; index++) {
  2165. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2166. }
  2167. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2168. return frustumPlanes;
  2169. };
  2170. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2171. // Near
  2172. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2173. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2174. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2175. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2176. frustumPlanes[0].normalize();
  2177. // Far
  2178. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2179. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2180. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2181. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2182. frustumPlanes[1].normalize();
  2183. // Left
  2184. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2185. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2186. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2187. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2188. frustumPlanes[2].normalize();
  2189. // Right
  2190. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2191. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2192. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2193. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2194. frustumPlanes[3].normalize();
  2195. // Top
  2196. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2197. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2198. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2199. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2200. frustumPlanes[4].normalize();
  2201. // Bottom
  2202. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2203. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2204. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2205. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2206. frustumPlanes[5].normalize();
  2207. };
  2208. return Frustum;
  2209. })();
  2210. BABYLON.Frustum = Frustum;
  2211. var Ray = (function () {
  2212. function Ray(origin, direction, length) {
  2213. if (length === void 0) { length = Number.MAX_VALUE; }
  2214. this.origin = origin;
  2215. this.direction = direction;
  2216. this.length = length;
  2217. }
  2218. // Methods
  2219. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2220. var d = 0.0;
  2221. var maxValue = Number.MAX_VALUE;
  2222. if (Math.abs(this.direction.x) < 0.0000001) {
  2223. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2224. return false;
  2225. }
  2226. }
  2227. else {
  2228. var inv = 1.0 / this.direction.x;
  2229. var min = (minimum.x - this.origin.x) * inv;
  2230. var max = (maximum.x - this.origin.x) * inv;
  2231. if (max === -Infinity) {
  2232. max = Infinity;
  2233. }
  2234. if (min > max) {
  2235. var temp = min;
  2236. min = max;
  2237. max = temp;
  2238. }
  2239. d = Math.max(min, d);
  2240. maxValue = Math.min(max, maxValue);
  2241. if (d > maxValue) {
  2242. return false;
  2243. }
  2244. }
  2245. if (Math.abs(this.direction.y) < 0.0000001) {
  2246. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2247. return false;
  2248. }
  2249. }
  2250. else {
  2251. inv = 1.0 / this.direction.y;
  2252. min = (minimum.y - this.origin.y) * inv;
  2253. max = (maximum.y - this.origin.y) * inv;
  2254. if (max === -Infinity) {
  2255. max = Infinity;
  2256. }
  2257. if (min > max) {
  2258. temp = min;
  2259. min = max;
  2260. max = temp;
  2261. }
  2262. d = Math.max(min, d);
  2263. maxValue = Math.min(max, maxValue);
  2264. if (d > maxValue) {
  2265. return false;
  2266. }
  2267. }
  2268. if (Math.abs(this.direction.z) < 0.0000001) {
  2269. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2270. return false;
  2271. }
  2272. }
  2273. else {
  2274. inv = 1.0 / this.direction.z;
  2275. min = (minimum.z - this.origin.z) * inv;
  2276. max = (maximum.z - this.origin.z) * inv;
  2277. if (max === -Infinity) {
  2278. max = Infinity;
  2279. }
  2280. if (min > max) {
  2281. temp = min;
  2282. min = max;
  2283. max = temp;
  2284. }
  2285. d = Math.max(min, d);
  2286. maxValue = Math.min(max, maxValue);
  2287. if (d > maxValue) {
  2288. return false;
  2289. }
  2290. }
  2291. return true;
  2292. };
  2293. Ray.prototype.intersectsBox = function (box) {
  2294. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2295. };
  2296. Ray.prototype.intersectsSphere = function (sphere) {
  2297. var x = sphere.center.x - this.origin.x;
  2298. var y = sphere.center.y - this.origin.y;
  2299. var z = sphere.center.z - this.origin.z;
  2300. var pyth = (x * x) + (y * y) + (z * z);
  2301. var rr = sphere.radius * sphere.radius;
  2302. if (pyth <= rr) {
  2303. return true;
  2304. }
  2305. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2306. if (dot < 0.0) {
  2307. return false;
  2308. }
  2309. var temp = pyth - (dot * dot);
  2310. return temp <= rr;
  2311. };
  2312. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2313. if (!this._edge1) {
  2314. this._edge1 = Vector3.Zero();
  2315. this._edge2 = Vector3.Zero();
  2316. this._pvec = Vector3.Zero();
  2317. this._tvec = Vector3.Zero();
  2318. this._qvec = Vector3.Zero();
  2319. }
  2320. vertex1.subtractToRef(vertex0, this._edge1);
  2321. vertex2.subtractToRef(vertex0, this._edge2);
  2322. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2323. var det = Vector3.Dot(this._edge1, this._pvec);
  2324. if (det === 0) {
  2325. return null;
  2326. }
  2327. var invdet = 1 / det;
  2328. this.origin.subtractToRef(vertex0, this._tvec);
  2329. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2330. if (bu < 0 || bu > 1.0) {
  2331. return null;
  2332. }
  2333. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2334. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2335. if (bv < 0 || bu + bv > 1.0) {
  2336. return null;
  2337. }
  2338. //check if the distance is longer than the predefined length.
  2339. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2340. if (distance > this.length) {
  2341. return null;
  2342. }
  2343. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2344. };
  2345. // Statics
  2346. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2347. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2348. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2349. var direction = end.subtract(start);
  2350. direction.normalize();
  2351. return new Ray(start, direction);
  2352. };
  2353. /**
  2354. * 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
  2355. * transformed to the given world matrix.
  2356. * @param origin The origin point
  2357. * @param end The end point
  2358. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2359. */
  2360. Ray.CreateNewFromTo = function (origin, end, world) {
  2361. if (world === void 0) { world = Matrix.Identity(); }
  2362. var direction = end.subtract(origin);
  2363. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2364. direction.normalize();
  2365. return Ray.Transform(new Ray(origin, direction, length), world);
  2366. };
  2367. Ray.Transform = function (ray, matrix) {
  2368. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2369. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2370. return new Ray(newOrigin, newDirection, ray.length);
  2371. };
  2372. return Ray;
  2373. })();
  2374. BABYLON.Ray = Ray;
  2375. (function (Space) {
  2376. Space[Space["LOCAL"] = 0] = "LOCAL";
  2377. Space[Space["WORLD"] = 1] = "WORLD";
  2378. })(BABYLON.Space || (BABYLON.Space = {}));
  2379. var Space = BABYLON.Space;
  2380. var Axis = (function () {
  2381. function Axis() {
  2382. }
  2383. Axis.X = new Vector3(1, 0, 0);
  2384. Axis.Y = new Vector3(0, 1, 0);
  2385. Axis.Z = new Vector3(0, 0, 1);
  2386. return Axis;
  2387. })();
  2388. BABYLON.Axis = Axis;
  2389. ;
  2390. var BezierCurve = (function () {
  2391. function BezierCurve() {
  2392. }
  2393. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2394. // Extract X (which is equal to time here)
  2395. var f0 = 1 - 3 * x2 + 3 * x1;
  2396. var f1 = 3 * x2 - 6 * x1;
  2397. var f2 = 3 * x1;
  2398. var refinedT = t;
  2399. for (var i = 0; i < 5; i++) {
  2400. var refinedT2 = refinedT * refinedT;
  2401. var refinedT3 = refinedT2 * refinedT;
  2402. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2403. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2404. refinedT -= (x - t) * slope;
  2405. refinedT = Math.min(1, Math.max(0, refinedT));
  2406. }
  2407. // Resolve cubic bezier for the given x
  2408. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2409. };
  2410. return BezierCurve;
  2411. })();
  2412. BABYLON.BezierCurve = BezierCurve;
  2413. (function (Orientation) {
  2414. Orientation[Orientation["CW"] = 0] = "CW";
  2415. Orientation[Orientation["CCW"] = 1] = "CCW";
  2416. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2417. var Orientation = BABYLON.Orientation;
  2418. var Angle = (function () {
  2419. function Angle(radians) {
  2420. var _this = this;
  2421. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2422. this.radians = function () { return _this._radians; };
  2423. this._radians = radians;
  2424. if (this._radians < 0)
  2425. this._radians += (2 * Math.PI);
  2426. }
  2427. Angle.BetweenTwoPoints = function (a, b) {
  2428. var delta = b.subtract(a);
  2429. var theta = Math.atan2(delta.y, delta.x);
  2430. return new Angle(theta);
  2431. };
  2432. Angle.FromRadians = function (radians) {
  2433. return new Angle(radians);
  2434. };
  2435. Angle.FromDegrees = function (degrees) {
  2436. return new Angle(degrees * Math.PI / 180);
  2437. };
  2438. return Angle;
  2439. })();
  2440. BABYLON.Angle = Angle;
  2441. var Arc2 = (function () {
  2442. function Arc2(startPoint, midPoint, endPoint) {
  2443. this.startPoint = startPoint;
  2444. this.midPoint = midPoint;
  2445. this.endPoint = endPoint;
  2446. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2447. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2448. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2449. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2450. 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);
  2451. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2452. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2453. var a1 = this.startAngle.degrees();
  2454. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2455. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2456. // angles correction
  2457. if (a2 - a1 > +180.0)
  2458. a2 -= 360.0;
  2459. if (a2 - a1 < -180.0)
  2460. a2 += 360.0;
  2461. if (a3 - a2 > +180.0)
  2462. a3 -= 360.0;
  2463. if (a3 - a2 < -180.0)
  2464. a3 += 360.0;
  2465. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2466. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2467. }
  2468. return Arc2;
  2469. })();
  2470. BABYLON.Arc2 = Arc2;
  2471. var PathCursor = (function () {
  2472. function PathCursor(path) {
  2473. this.path = path;
  2474. this._onchange = new Array();
  2475. this.value = 0;
  2476. this.animations = new Array();
  2477. }
  2478. PathCursor.prototype.getPoint = function () {
  2479. var point = this.path.getPointAtLengthPosition(this.value);
  2480. return new Vector3(point.x, 0, point.y);
  2481. };
  2482. PathCursor.prototype.moveAhead = function (step) {
  2483. if (step === void 0) { step = 0.002; }
  2484. this.move(step);
  2485. return this;
  2486. };
  2487. PathCursor.prototype.moveBack = function (step) {
  2488. if (step === void 0) { step = 0.002; }
  2489. this.move(-step);
  2490. return this;
  2491. };
  2492. PathCursor.prototype.move = function (step) {
  2493. if (Math.abs(step) > 1) {
  2494. throw "step size should be less than 1.";
  2495. }
  2496. this.value += step;
  2497. this.ensureLimits();
  2498. this.raiseOnChange();
  2499. return this;
  2500. };
  2501. PathCursor.prototype.ensureLimits = function () {
  2502. while (this.value > 1) {
  2503. this.value -= 1;
  2504. }
  2505. while (this.value < 0) {
  2506. this.value += 1;
  2507. }
  2508. return this;
  2509. };
  2510. // used by animation engine
  2511. PathCursor.prototype.markAsDirty = function (propertyName) {
  2512. this.ensureLimits();
  2513. this.raiseOnChange();
  2514. return this;
  2515. };
  2516. PathCursor.prototype.raiseOnChange = function () {
  2517. var _this = this;
  2518. this._onchange.forEach(function (f) { return f(_this); });
  2519. return this;
  2520. };
  2521. PathCursor.prototype.onchange = function (f) {
  2522. this._onchange.push(f);
  2523. return this;
  2524. };
  2525. return PathCursor;
  2526. })();
  2527. BABYLON.PathCursor = PathCursor;
  2528. var Path2 = (function () {
  2529. function Path2(x, y) {
  2530. this._points = new Array();
  2531. this._length = 0;
  2532. this.closed = false;
  2533. this._points.push(new Vector2(x, y));
  2534. }
  2535. Path2.prototype.addLineTo = function (x, y) {
  2536. if (closed) {
  2537. BABYLON.Tools.Error("cannot add lines to closed paths");
  2538. return this;
  2539. }
  2540. var newPoint = new Vector2(x, y);
  2541. var previousPoint = this._points[this._points.length - 1];
  2542. this._points.push(newPoint);
  2543. this._length += newPoint.subtract(previousPoint).length();
  2544. return this;
  2545. };
  2546. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2547. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2548. if (closed) {
  2549. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2550. return this;
  2551. }
  2552. var startPoint = this._points[this._points.length - 1];
  2553. var midPoint = new Vector2(midX, midY);
  2554. var endPoint = new Vector2(endX, endY);
  2555. var arc = new Arc2(startPoint, midPoint, endPoint);
  2556. var increment = arc.angle.radians() / numberOfSegments;
  2557. if (arc.orientation === 0 /* CW */)
  2558. increment *= -1;
  2559. var currentAngle = arc.startAngle.radians() + increment;
  2560. for (var i = 0; i < numberOfSegments; i++) {
  2561. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2562. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2563. this.addLineTo(x, y);
  2564. currentAngle += increment;
  2565. }
  2566. return this;
  2567. };
  2568. Path2.prototype.close = function () {
  2569. this.closed = true;
  2570. return this;
  2571. };
  2572. Path2.prototype.length = function () {
  2573. var result = this._length;
  2574. if (!this.closed) {
  2575. var lastPoint = this._points[this._points.length - 1];
  2576. var firstPoint = this._points[0];
  2577. result += (firstPoint.subtract(lastPoint).length());
  2578. }
  2579. return result;
  2580. };
  2581. Path2.prototype.getPoints = function () {
  2582. return this._points;
  2583. };
  2584. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2585. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2586. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2587. return Vector2.Zero();
  2588. }
  2589. var lengthPosition = normalizedLengthPosition * this.length();
  2590. var previousOffset = 0;
  2591. for (var i = 0; i < this._points.length; i++) {
  2592. var j = (i + 1) % this._points.length;
  2593. var a = this._points[i];
  2594. var b = this._points[j];
  2595. var bToA = b.subtract(a);
  2596. var nextOffset = (bToA.length() + previousOffset);
  2597. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2598. var dir = bToA.normalize();
  2599. var localOffset = lengthPosition - previousOffset;
  2600. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2601. }
  2602. previousOffset = nextOffset;
  2603. }
  2604. BABYLON.Tools.Error("internal error");
  2605. return Vector2.Zero();
  2606. };
  2607. Path2.StartingAt = function (x, y) {
  2608. return new Path2(x, y);
  2609. };
  2610. return Path2;
  2611. })();
  2612. BABYLON.Path2 = Path2;
  2613. var Path3D = (function () {
  2614. function Path3D(path) {
  2615. this.path = path;
  2616. this._curve = new Array();
  2617. this._distances = new Array();
  2618. this._tangents = new Array();
  2619. this._normals = new Array();
  2620. this._binormals = new Array();
  2621. this._curve = path.slice(); // copy array
  2622. this._compute();
  2623. }
  2624. Path3D.prototype.getCurve = function () {
  2625. return this._curve;
  2626. };
  2627. Path3D.prototype.getTangents = function () {
  2628. return this._tangents;
  2629. };
  2630. Path3D.prototype.getNormals = function () {
  2631. return this._normals;
  2632. };
  2633. Path3D.prototype.getBinormals = function () {
  2634. return this._binormals;
  2635. };
  2636. Path3D.prototype.getDistances = function () {
  2637. return this._distances;
  2638. };
  2639. Path3D.prototype.update = function (path) {
  2640. for (var i = 0; i < path.length; i++) {
  2641. this._curve[i] = path[i];
  2642. }
  2643. this._compute();
  2644. return this;
  2645. };
  2646. // private function compute() : computes tangents, normals and binormals
  2647. Path3D.prototype._compute = function () {
  2648. var l = this._curve.length;
  2649. // first and last tangents
  2650. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2651. this._tangents[0].normalize();
  2652. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2653. this._tangents[l - 1].normalize();
  2654. // normals and binormals at first point : arbitrary vector with _normalVector()
  2655. var tg0 = this._tangents[0];
  2656. var pp0 = this._normalVector(this._curve[0], tg0);
  2657. this._normals[0] = pp0;
  2658. this._normals[0].normalize();
  2659. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2660. this._normals[0].normalize();
  2661. this._distances[0] = 0;
  2662. // normals and binormals : next points
  2663. var prev; // previous vector (segment)
  2664. var cur; // current vector (segment)
  2665. var curTang; // current tangent
  2666. var prevNorm; // previous normal
  2667. var prevBinor; // previous binormal
  2668. for (var i = 1; i < l; i++) {
  2669. // tangents
  2670. prev = this._curve[i].subtract(this._curve[i - 1]);
  2671. if (i < l - 1) {
  2672. cur = this._curve[i + 1].subtract(this._curve[i]);
  2673. this._tangents[i] = prev.add(cur);
  2674. this._tangents[i].normalize();
  2675. }
  2676. this._distances[i] = this._distances[i - 1] + prev.length();
  2677. // normals and binormals
  2678. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2679. curTang = this._tangents[i];
  2680. prevNorm = this._normals[i - 1];
  2681. prevBinor = this._binormals[i - 1];
  2682. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2683. this._normals[i].normalize();
  2684. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2685. this._binormals[i].normalize();
  2686. }
  2687. };
  2688. // private function normalVector(v0, vt) :
  2689. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2690. Path3D.prototype._normalVector = function (v0, vt) {
  2691. var point;
  2692. if (vt.x !== 1) {
  2693. point = new Vector3(1, 0, 0);
  2694. }
  2695. else if (vt.y !== 1) {
  2696. point = new Vector3(0, 1, 0);
  2697. }
  2698. else if (vt.z !== 1) {
  2699. point = new Vector3(0, 0, 1);
  2700. }
  2701. var normal0 = Vector3.Cross(vt, point);
  2702. normal0.normalize();
  2703. return normal0;
  2704. };
  2705. return Path3D;
  2706. })();
  2707. BABYLON.Path3D = Path3D;
  2708. var Curve3 = (function () {
  2709. function Curve3(points) {
  2710. this._points = points;
  2711. }
  2712. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2713. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2714. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2715. var bez = new Array();
  2716. var equation = function (t, val0, val1, val2) {
  2717. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2718. return res;
  2719. };
  2720. for (var i = 0; i <= nbPoints; i++) {
  2721. 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)));
  2722. }
  2723. return new Curve3(bez);
  2724. };
  2725. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2726. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2727. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2728. var bez = new Array();
  2729. var equation = function (t, val0, val1, val2, val3) {
  2730. 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;
  2731. return res;
  2732. };
  2733. for (var i = 0; i <= nbPoints; i++) {
  2734. 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)));
  2735. }
  2736. return new Curve3(bez);
  2737. };
  2738. Curve3.prototype.getPoints = function () {
  2739. return this._points;
  2740. };
  2741. Curve3.prototype.continue = function (curve) {
  2742. var lastPoint = this._points[this._points.length - 1];
  2743. var continuedPoints = this._points.slice();
  2744. var curvePoints = curve.getPoints();
  2745. for (var i = 1; i < curvePoints.length; i++) {
  2746. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2747. }
  2748. return new Curve3(continuedPoints);
  2749. };
  2750. return Curve3;
  2751. })();
  2752. BABYLON.Curve3 = Curve3;
  2753. // Vertex formats
  2754. var PositionNormalVertex = (function () {
  2755. function PositionNormalVertex(position, normal) {
  2756. if (position === void 0) { position = Vector3.Zero(); }
  2757. if (normal === void 0) { normal = Vector3.Up(); }
  2758. this.position = position;
  2759. this.normal = normal;
  2760. }
  2761. PositionNormalVertex.prototype.clone = function () {
  2762. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2763. };
  2764. return PositionNormalVertex;
  2765. })();
  2766. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2767. var PositionNormalTextureVertex = (function () {
  2768. function PositionNormalTextureVertex(position, normal, uv) {
  2769. if (position === void 0) { position = Vector3.Zero(); }
  2770. if (normal === void 0) { normal = Vector3.Up(); }
  2771. if (uv === void 0) { uv = Vector2.Zero(); }
  2772. this.position = position;
  2773. this.normal = normal;
  2774. this.uv = uv;
  2775. }
  2776. PositionNormalTextureVertex.prototype.clone = function () {
  2777. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2778. };
  2779. return PositionNormalTextureVertex;
  2780. })();
  2781. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2782. // SIMD
  2783. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2784. var previousInvertToRef = Matrix.prototype.invertToRef;
  2785. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2786. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2787. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2788. var SIMDHelper = (function () {
  2789. function SIMDHelper() {
  2790. }
  2791. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2792. get: function () {
  2793. return SIMDHelper._isEnabled;
  2794. },
  2795. enumerable: true,
  2796. configurable: true
  2797. });
  2798. SIMDHelper.DisableSIMD = function () {
  2799. // Replace functions
  2800. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2801. Matrix.prototype.invertToRef = previousInvertToRef;
  2802. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2803. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2804. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2805. SIMDHelper._isEnabled = false;
  2806. };
  2807. SIMDHelper.EnableSIMD = function () {
  2808. if (window.SIMD === undefined) {
  2809. return;
  2810. }
  2811. // Replace functions
  2812. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2813. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2814. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2815. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2816. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2817. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2818. get: function () {
  2819. return this._data[0];
  2820. },
  2821. set: function (value) {
  2822. if (!this._data) {
  2823. this._data = new Float32Array(3);
  2824. }
  2825. this._data[0] = value;
  2826. }
  2827. });
  2828. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2829. get: function () {
  2830. return this._data[1];
  2831. },
  2832. set: function (value) {
  2833. this._data[1] = value;
  2834. }
  2835. });
  2836. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2837. get: function () {
  2838. return this._data[2];
  2839. },
  2840. set: function (value) {
  2841. this._data[2] = value;
  2842. }
  2843. });
  2844. SIMDHelper._isEnabled = true;
  2845. };
  2846. SIMDHelper._isEnabled = false;
  2847. return SIMDHelper;
  2848. })();
  2849. BABYLON.SIMDHelper = SIMDHelper;
  2850. if (window.SIMD !== undefined) {
  2851. SIMDHelper.EnableSIMD();
  2852. }
  2853. })(BABYLON || (BABYLON = {}));
  2854. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2855. (function (BABYLON) {
  2856. // Screenshots
  2857. var screenshotCanvas;
  2858. var cloneValue = function (source, destinationObject) {
  2859. if (!source)
  2860. return null;
  2861. if (source instanceof BABYLON.Mesh) {
  2862. return null;
  2863. }
  2864. if (source instanceof BABYLON.SubMesh) {
  2865. return source.clone(destinationObject);
  2866. }
  2867. else if (source.clone) {
  2868. return source.clone();
  2869. }
  2870. return null;
  2871. };
  2872. var Tools = (function () {
  2873. function Tools() {
  2874. }
  2875. Tools.GetFilename = function (path) {
  2876. var index = path.lastIndexOf("/");
  2877. if (index < 0)
  2878. return path;
  2879. return path.substring(index + 1);
  2880. };
  2881. Tools.GetDOMTextContent = function (element) {
  2882. var result = "";
  2883. var child = element.firstChild;
  2884. while (child) {
  2885. if (child.nodeType === 3) {
  2886. result += child.textContent;
  2887. }
  2888. child = child.nextSibling;
  2889. }
  2890. return result;
  2891. };
  2892. Tools.ToDegrees = function (angle) {
  2893. return angle * 180 / Math.PI;
  2894. };
  2895. Tools.ToRadians = function (angle) {
  2896. return angle * Math.PI / 180;
  2897. };
  2898. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2899. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2900. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2901. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2902. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2903. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2904. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2905. }
  2906. return {
  2907. minimum: minimum,
  2908. maximum: maximum
  2909. };
  2910. };
  2911. Tools.ExtractMinAndMax = function (positions, start, count) {
  2912. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2913. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2914. for (var index = start; index < start + count; index++) {
  2915. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2916. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2917. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2918. }
  2919. return {
  2920. minimum: minimum,
  2921. maximum: maximum
  2922. };
  2923. };
  2924. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2925. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2926. return undefined;
  2927. return Array.isArray(obj) ? obj : [obj];
  2928. };
  2929. // Misc.
  2930. Tools.GetPointerPrefix = function () {
  2931. var eventPrefix = "pointer";
  2932. // Check if hand.js is referenced or if the browser natively supports pointer events
  2933. if (!navigator.pointerEnabled) {
  2934. eventPrefix = "mouse";
  2935. }
  2936. return eventPrefix;
  2937. };
  2938. Tools.QueueNewFrame = function (func) {
  2939. if (window.requestAnimationFrame)
  2940. window.requestAnimationFrame(func);
  2941. else if (window.msRequestAnimationFrame)
  2942. window.msRequestAnimationFrame(func);
  2943. else if (window.webkitRequestAnimationFrame)
  2944. window.webkitRequestAnimationFrame(func);
  2945. else if (window.mozRequestAnimationFrame)
  2946. window.mozRequestAnimationFrame(func);
  2947. else if (window.oRequestAnimationFrame)
  2948. window.oRequestAnimationFrame(func);
  2949. else {
  2950. window.setTimeout(func, 16);
  2951. }
  2952. };
  2953. Tools.RequestFullscreen = function (element) {
  2954. if (element.requestFullscreen)
  2955. element.requestFullscreen();
  2956. else if (element.msRequestFullscreen)
  2957. element.msRequestFullscreen();
  2958. else if (element.webkitRequestFullscreen)
  2959. element.webkitRequestFullscreen();
  2960. else if (element.mozRequestFullScreen)
  2961. element.mozRequestFullScreen();
  2962. };
  2963. Tools.ExitFullscreen = function () {
  2964. if (document.exitFullscreen) {
  2965. document.exitFullscreen();
  2966. }
  2967. else if (document.mozCancelFullScreen) {
  2968. document.mozCancelFullScreen();
  2969. }
  2970. else if (document.webkitCancelFullScreen) {
  2971. document.webkitCancelFullScreen();
  2972. }
  2973. else if (document.msCancelFullScreen) {
  2974. document.msCancelFullScreen();
  2975. }
  2976. };
  2977. // External files
  2978. Tools.CleanUrl = function (url) {
  2979. url = url.replace(/#/mg, "%23");
  2980. return url;
  2981. };
  2982. Tools.LoadImage = function (url, onload, onerror, database) {
  2983. url = Tools.CleanUrl(url);
  2984. var img = new Image();
  2985. if (url.substr(0, 5) !== "data:")
  2986. img.crossOrigin = 'anonymous';
  2987. img.onload = function () {
  2988. onload(img);
  2989. };
  2990. img.onerror = function (err) {
  2991. onerror(img, err);
  2992. };
  2993. var noIndexedDB = function () {
  2994. img.src = url;
  2995. };
  2996. var loadFromIndexedDB = function () {
  2997. database.loadImageFromDB(url, img);
  2998. };
  2999. //ANY database to do!
  3000. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  3001. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3002. }
  3003. else {
  3004. if (url.indexOf("file:") === -1) {
  3005. noIndexedDB();
  3006. }
  3007. else {
  3008. try {
  3009. var textureName = url.substring(5);
  3010. var blobURL;
  3011. try {
  3012. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  3013. }
  3014. catch (ex) {
  3015. // Chrome doesn't support oneTimeOnly parameter
  3016. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  3017. }
  3018. img.src = blobURL;
  3019. }
  3020. catch (e) {
  3021. Tools.Log("Error while trying to load texture: " + textureName);
  3022. img.src = null;
  3023. }
  3024. }
  3025. }
  3026. return img;
  3027. };
  3028. //ANY
  3029. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3030. url = Tools.CleanUrl(url);
  3031. var noIndexedDB = function () {
  3032. var request = new XMLHttpRequest();
  3033. var loadUrl = Tools.BaseUrl + url;
  3034. request.open('GET', loadUrl, true);
  3035. if (useArrayBuffer) {
  3036. request.responseType = "arraybuffer";
  3037. }
  3038. request.onprogress = progressCallBack;
  3039. request.onreadystatechange = function () {
  3040. if (request.readyState === 4) {
  3041. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3042. callback(!useArrayBuffer ? request.responseText : request.response);
  3043. }
  3044. else {
  3045. if (onError) {
  3046. onError();
  3047. }
  3048. else {
  3049. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3050. }
  3051. }
  3052. }
  3053. };
  3054. request.send(null);
  3055. };
  3056. var loadFromIndexedDB = function () {
  3057. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3058. };
  3059. if (url.indexOf("file:") !== -1) {
  3060. var fileName = url.substring(5);
  3061. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3062. }
  3063. else {
  3064. // Caching all files
  3065. if (database && database.enableSceneOffline) {
  3066. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3067. }
  3068. else {
  3069. noIndexedDB();
  3070. }
  3071. }
  3072. };
  3073. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3074. var reader = new FileReader();
  3075. reader.onload = function (e) {
  3076. //target doesn't have result from ts 1.3
  3077. callback(e.target['result']);
  3078. };
  3079. reader.onprogress = progressCallback;
  3080. reader.readAsDataURL(fileToLoad);
  3081. };
  3082. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3083. var reader = new FileReader();
  3084. reader.onerror = function (e) {
  3085. Tools.Log("Error while reading file: " + fileToLoad.name);
  3086. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3087. };
  3088. reader.onload = function (e) {
  3089. //target doesn't have result from ts 1.3
  3090. callback(e.target['result']);
  3091. };
  3092. reader.onprogress = progressCallBack;
  3093. if (!useArrayBuffer) {
  3094. // Asynchronous read
  3095. reader.readAsText(fileToLoad);
  3096. }
  3097. else {
  3098. reader.readAsArrayBuffer(fileToLoad);
  3099. }
  3100. };
  3101. // Misc.
  3102. Tools.Clamp = function (value, min, max) {
  3103. if (min === void 0) { min = 0; }
  3104. if (max === void 0) { max = 1; }
  3105. return Math.min(max, Math.max(min, value));
  3106. };
  3107. // Returns -1 when value is a negative number and
  3108. // +1 when value is a positive number.
  3109. Tools.Sign = function (value) {
  3110. value = +value; // convert to a number
  3111. if (value === 0 || isNaN(value))
  3112. return value;
  3113. return value > 0 ? 1 : -1;
  3114. };
  3115. Tools.Format = function (value, decimals) {
  3116. if (decimals === void 0) { decimals = 2; }
  3117. return value.toFixed(decimals);
  3118. };
  3119. Tools.CheckExtends = function (v, min, max) {
  3120. if (v.x < min.x)
  3121. min.x = v.x;
  3122. if (v.y < min.y)
  3123. min.y = v.y;
  3124. if (v.z < min.z)
  3125. min.z = v.z;
  3126. if (v.x > max.x)
  3127. max.x = v.x;
  3128. if (v.y > max.y)
  3129. max.y = v.y;
  3130. if (v.z > max.z)
  3131. max.z = v.z;
  3132. };
  3133. Tools.WithinEpsilon = function (a, b, epsilon) {
  3134. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3135. var num = a - b;
  3136. return -epsilon <= num && num <= epsilon;
  3137. };
  3138. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3139. for (var prop in source) {
  3140. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3141. continue;
  3142. }
  3143. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3144. continue;
  3145. }
  3146. var sourceValue = source[prop];
  3147. var typeOfSourceValue = typeof sourceValue;
  3148. if (typeOfSourceValue === "function") {
  3149. continue;
  3150. }
  3151. if (typeOfSourceValue === "object") {
  3152. if (sourceValue instanceof Array) {
  3153. destination[prop] = [];
  3154. if (sourceValue.length > 0) {
  3155. if (typeof sourceValue[0] == "object") {
  3156. for (var index = 0; index < sourceValue.length; index++) {
  3157. var clonedValue = cloneValue(sourceValue[index], destination);
  3158. if (destination[prop].indexOf(clonedValue) === -1) {
  3159. destination[prop].push(clonedValue);
  3160. }
  3161. }
  3162. }
  3163. else {
  3164. destination[prop] = sourceValue.slice(0);
  3165. }
  3166. }
  3167. }
  3168. else {
  3169. destination[prop] = cloneValue(sourceValue, destination);
  3170. }
  3171. }
  3172. else {
  3173. destination[prop] = sourceValue;
  3174. }
  3175. }
  3176. };
  3177. Tools.IsEmpty = function (obj) {
  3178. for (var i in obj) {
  3179. return false;
  3180. }
  3181. return true;
  3182. };
  3183. Tools.RegisterTopRootEvents = function (events) {
  3184. for (var index = 0; index < events.length; index++) {
  3185. var event = events[index];
  3186. window.addEventListener(event.name, event.handler, false);
  3187. try {
  3188. if (window.parent) {
  3189. window.parent.addEventListener(event.name, event.handler, false);
  3190. }
  3191. }
  3192. catch (e) {
  3193. }
  3194. }
  3195. };
  3196. Tools.UnregisterTopRootEvents = function (events) {
  3197. for (var index = 0; index < events.length; index++) {
  3198. var event = events[index];
  3199. window.removeEventListener(event.name, event.handler);
  3200. try {
  3201. if (window.parent) {
  3202. window.parent.removeEventListener(event.name, event.handler);
  3203. }
  3204. }
  3205. catch (e) {
  3206. }
  3207. }
  3208. };
  3209. Tools.DumpFramebuffer = function (width, height, engine) {
  3210. // Read the contents of the framebuffer
  3211. var numberOfChannelsByLine = width * 4;
  3212. var halfHeight = height / 2;
  3213. //Reading datas from WebGL
  3214. var data = engine.readPixels(0, 0, width, height);
  3215. for (var i = 0; i < halfHeight; i++) {
  3216. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3217. var currentCell = j + i * numberOfChannelsByLine;
  3218. var targetLine = height - i - 1;
  3219. var targetCell = j + targetLine * numberOfChannelsByLine;
  3220. var temp = data[currentCell];
  3221. data[currentCell] = data[targetCell];
  3222. data[targetCell] = temp;
  3223. }
  3224. }
  3225. // Create a 2D canvas to store the result
  3226. if (!screenshotCanvas) {
  3227. screenshotCanvas = document.createElement('canvas');
  3228. }
  3229. screenshotCanvas.width = width;
  3230. screenshotCanvas.height = height;
  3231. var context = screenshotCanvas.getContext('2d');
  3232. // Copy the pixels to a 2D canvas
  3233. var imageData = context.createImageData(width, height);
  3234. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3235. var castData = imageData.data;
  3236. castData.set(data);
  3237. context.putImageData(imageData, 0, 0);
  3238. var base64Image = screenshotCanvas.toDataURL();
  3239. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3240. if (("download" in document.createElement("a"))) {
  3241. var a = window.document.createElement("a");
  3242. a.href = base64Image;
  3243. var date = new Date();
  3244. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3245. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3246. window.document.body.appendChild(a);
  3247. a.addEventListener("click", function () {
  3248. a.parentElement.removeChild(a);
  3249. });
  3250. a.click();
  3251. }
  3252. else {
  3253. var newWindow = window.open("");
  3254. var img = newWindow.document.createElement("img");
  3255. img.src = base64Image;
  3256. newWindow.document.body.appendChild(img);
  3257. }
  3258. };
  3259. Tools.CreateScreenshot = function (engine, camera, size) {
  3260. var width;
  3261. var height;
  3262. var scene = camera.getScene();
  3263. var previousCamera = null;
  3264. if (scene.activeCamera !== camera) {
  3265. previousCamera = scene.activeCamera;
  3266. scene.activeCamera = camera;
  3267. }
  3268. //If a precision value is specified
  3269. if (size.precision) {
  3270. width = Math.round(engine.getRenderWidth() * size.precision);
  3271. height = Math.round(width / engine.getAspectRatio(camera));
  3272. size = { width: width, height: height };
  3273. }
  3274. else if (size.width && size.height) {
  3275. width = size.width;
  3276. height = size.height;
  3277. }
  3278. else if (size.width && !size.height) {
  3279. width = size.width;
  3280. height = Math.round(width / engine.getAspectRatio(camera));
  3281. size = { width: width, height: height };
  3282. }
  3283. else if (size.height && !size.width) {
  3284. height = size.height;
  3285. width = Math.round(height * engine.getAspectRatio(camera));
  3286. size = { width: width, height: height };
  3287. }
  3288. else if (!isNaN(size)) {
  3289. height = size;
  3290. width = size;
  3291. }
  3292. else {
  3293. Tools.Error("Invalid 'size' parameter !");
  3294. return;
  3295. }
  3296. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3297. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3298. texture.renderList = scene.meshes;
  3299. texture.onAfterRender = function () {
  3300. Tools.DumpFramebuffer(width, height, engine);
  3301. };
  3302. scene.incrementRenderId();
  3303. texture.render(true);
  3304. texture.dispose();
  3305. if (previousCamera) {
  3306. scene.activeCamera = previousCamera;
  3307. }
  3308. };
  3309. // XHR response validator for local file scenario
  3310. Tools.ValidateXHRData = function (xhr, dataType) {
  3311. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3312. if (dataType === void 0) { dataType = 7; }
  3313. try {
  3314. if (dataType & 1) {
  3315. if (xhr.responseText && xhr.responseText.length > 0) {
  3316. return true;
  3317. }
  3318. else if (dataType === 1) {
  3319. return false;
  3320. }
  3321. }
  3322. if (dataType & 2) {
  3323. // Check header width and height since there is no "TGA" magic number
  3324. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3325. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3326. return true;
  3327. }
  3328. else if (dataType === 2) {
  3329. return false;
  3330. }
  3331. }
  3332. if (dataType & 4) {
  3333. // Check for the "DDS" magic number
  3334. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3335. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3336. return true;
  3337. }
  3338. else {
  3339. return false;
  3340. }
  3341. }
  3342. }
  3343. catch (e) {
  3344. }
  3345. return false;
  3346. };
  3347. Object.defineProperty(Tools, "NoneLogLevel", {
  3348. get: function () {
  3349. return Tools._NoneLogLevel;
  3350. },
  3351. enumerable: true,
  3352. configurable: true
  3353. });
  3354. Object.defineProperty(Tools, "MessageLogLevel", {
  3355. get: function () {
  3356. return Tools._MessageLogLevel;
  3357. },
  3358. enumerable: true,
  3359. configurable: true
  3360. });
  3361. Object.defineProperty(Tools, "WarningLogLevel", {
  3362. get: function () {
  3363. return Tools._WarningLogLevel;
  3364. },
  3365. enumerable: true,
  3366. configurable: true
  3367. });
  3368. Object.defineProperty(Tools, "ErrorLogLevel", {
  3369. get: function () {
  3370. return Tools._ErrorLogLevel;
  3371. },
  3372. enumerable: true,
  3373. configurable: true
  3374. });
  3375. Object.defineProperty(Tools, "AllLogLevel", {
  3376. get: function () {
  3377. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3378. },
  3379. enumerable: true,
  3380. configurable: true
  3381. });
  3382. Tools._AddLogEntry = function (entry) {
  3383. Tools._LogCache = entry + Tools._LogCache;
  3384. if (Tools.OnNewCacheEntry) {
  3385. Tools.OnNewCacheEntry(entry);
  3386. }
  3387. };
  3388. Tools._FormatMessage = function (message) {
  3389. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3390. var date = new Date();
  3391. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3392. };
  3393. Tools._LogDisabled = function (message) {
  3394. // nothing to do
  3395. };
  3396. Tools._LogEnabled = function (message) {
  3397. var formattedMessage = Tools._FormatMessage(message);
  3398. console.log("BJS - " + formattedMessage);
  3399. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3400. Tools._AddLogEntry(entry);
  3401. };
  3402. Tools._WarnDisabled = function (message) {
  3403. // nothing to do
  3404. };
  3405. Tools._WarnEnabled = function (message) {
  3406. var formattedMessage = Tools._FormatMessage(message);
  3407. console.warn("BJS - " + formattedMessage);
  3408. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3409. Tools._AddLogEntry(entry);
  3410. };
  3411. Tools._ErrorDisabled = function (message) {
  3412. // nothing to do
  3413. };
  3414. Tools._ErrorEnabled = function (message) {
  3415. var formattedMessage = Tools._FormatMessage(message);
  3416. console.error("BJS - " + formattedMessage);
  3417. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3418. Tools._AddLogEntry(entry);
  3419. };
  3420. Object.defineProperty(Tools, "LogCache", {
  3421. get: function () {
  3422. return Tools._LogCache;
  3423. },
  3424. enumerable: true,
  3425. configurable: true
  3426. });
  3427. Object.defineProperty(Tools, "LogLevels", {
  3428. set: function (level) {
  3429. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3430. Tools.Log = Tools._LogEnabled;
  3431. }
  3432. else {
  3433. Tools.Log = Tools._LogDisabled;
  3434. }
  3435. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3436. Tools.Warn = Tools._WarnEnabled;
  3437. }
  3438. else {
  3439. Tools.Warn = Tools._WarnDisabled;
  3440. }
  3441. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3442. Tools.Error = Tools._ErrorEnabled;
  3443. }
  3444. else {
  3445. Tools.Error = Tools._ErrorDisabled;
  3446. }
  3447. },
  3448. enumerable: true,
  3449. configurable: true
  3450. });
  3451. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3452. get: function () {
  3453. return Tools._PerformanceNoneLogLevel;
  3454. },
  3455. enumerable: true,
  3456. configurable: true
  3457. });
  3458. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3459. get: function () {
  3460. return Tools._PerformanceUserMarkLogLevel;
  3461. },
  3462. enumerable: true,
  3463. configurable: true
  3464. });
  3465. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3466. get: function () {
  3467. return Tools._PerformanceConsoleLogLevel;
  3468. },
  3469. enumerable: true,
  3470. configurable: true
  3471. });
  3472. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3473. set: function (level) {
  3474. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3475. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3476. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3477. return;
  3478. }
  3479. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3480. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3481. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3482. return;
  3483. }
  3484. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3485. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3486. },
  3487. enumerable: true,
  3488. configurable: true
  3489. });
  3490. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3491. };
  3492. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3493. };
  3494. Tools._StartUserMark = function (counterName, condition) {
  3495. if (condition === void 0) { condition = true; }
  3496. if (!condition || !Tools._performance.mark) {
  3497. return;
  3498. }
  3499. Tools._performance.mark(counterName + "-Begin");
  3500. };
  3501. Tools._EndUserMark = function (counterName, condition) {
  3502. if (condition === void 0) { condition = true; }
  3503. if (!condition || !Tools._performance.mark) {
  3504. return;
  3505. }
  3506. Tools._performance.mark(counterName + "-End");
  3507. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3508. };
  3509. Tools._StartPerformanceConsole = function (counterName, condition) {
  3510. if (condition === void 0) { condition = true; }
  3511. if (!condition) {
  3512. return;
  3513. }
  3514. Tools._StartUserMark(counterName, condition);
  3515. if (console.time) {
  3516. console.time(counterName);
  3517. }
  3518. };
  3519. Tools._EndPerformanceConsole = function (counterName, condition) {
  3520. if (condition === void 0) { condition = true; }
  3521. if (!condition) {
  3522. return;
  3523. }
  3524. Tools._EndUserMark(counterName, condition);
  3525. if (console.time) {
  3526. console.timeEnd(counterName);
  3527. }
  3528. };
  3529. Object.defineProperty(Tools, "Now", {
  3530. get: function () {
  3531. if (window.performance && window.performance.now) {
  3532. return window.performance.now();
  3533. }
  3534. return new Date().getTime();
  3535. },
  3536. enumerable: true,
  3537. configurable: true
  3538. });
  3539. // Deprecated
  3540. Tools.GetFps = function () {
  3541. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3542. return 0;
  3543. };
  3544. Tools.BaseUrl = "";
  3545. Tools.GetExponantOfTwo = function (value, max) {
  3546. var count = 1;
  3547. do {
  3548. count *= 2;
  3549. } while (count < value);
  3550. if (count > max)
  3551. count = max;
  3552. return count;
  3553. };
  3554. // Logs
  3555. Tools._NoneLogLevel = 0;
  3556. Tools._MessageLogLevel = 1;
  3557. Tools._WarningLogLevel = 2;
  3558. Tools._ErrorLogLevel = 4;
  3559. Tools._LogCache = "";
  3560. Tools.Log = Tools._LogEnabled;
  3561. Tools.Warn = Tools._WarnEnabled;
  3562. Tools.Error = Tools._ErrorEnabled;
  3563. // Performances
  3564. Tools._PerformanceNoneLogLevel = 0;
  3565. Tools._PerformanceUserMarkLogLevel = 1;
  3566. Tools._PerformanceConsoleLogLevel = 2;
  3567. Tools._performance = window.performance;
  3568. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3569. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3570. return Tools;
  3571. })();
  3572. BABYLON.Tools = Tools;
  3573. /**
  3574. * An implementation of a loop for asynchronous functions.
  3575. */
  3576. var AsyncLoop = (function () {
  3577. /**
  3578. * Constroctor.
  3579. * @param iterations the number of iterations.
  3580. * @param _fn the function to run each iteration
  3581. * @param _successCallback the callback that will be called upon succesful execution
  3582. * @param offset starting offset.
  3583. */
  3584. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3585. if (offset === void 0) { offset = 0; }
  3586. this.iterations = iterations;
  3587. this._fn = _fn;
  3588. this._successCallback = _successCallback;
  3589. this.index = offset - 1;
  3590. this._done = false;
  3591. }
  3592. /**
  3593. * Execute the next iteration. Must be called after the last iteration was finished.
  3594. */
  3595. AsyncLoop.prototype.executeNext = function () {
  3596. if (!this._done) {
  3597. if (this.index + 1 < this.iterations) {
  3598. ++this.index;
  3599. this._fn(this);
  3600. }
  3601. else {
  3602. this.breakLoop();
  3603. }
  3604. }
  3605. };
  3606. /**
  3607. * Break the loop and run the success callback.
  3608. */
  3609. AsyncLoop.prototype.breakLoop = function () {
  3610. this._done = true;
  3611. this._successCallback();
  3612. };
  3613. /**
  3614. * Helper function
  3615. */
  3616. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3617. if (offset === void 0) { offset = 0; }
  3618. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3619. loop.executeNext();
  3620. return loop;
  3621. };
  3622. /**
  3623. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3624. * @param iterations total number of iterations
  3625. * @param syncedIterations number of synchronous iterations in each async iteration.
  3626. * @param fn the function to call each iteration.
  3627. * @param callback a success call back that will be called when iterating stops.
  3628. * @param breakFunction a break condition (optional)
  3629. * @param timeout timeout settings for the setTimeout function. default - 0.
  3630. * @constructor
  3631. */
  3632. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3633. if (timeout === void 0) { timeout = 0; }
  3634. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3635. if (breakFunction && breakFunction())
  3636. loop.breakLoop();
  3637. else {
  3638. setTimeout(function () {
  3639. for (var i = 0; i < syncedIterations; ++i) {
  3640. var iteration = (loop.index * syncedIterations) + i;
  3641. if (iteration >= iterations)
  3642. break;
  3643. fn(iteration);
  3644. if (breakFunction && breakFunction()) {
  3645. loop.breakLoop();
  3646. break;
  3647. }
  3648. }
  3649. loop.executeNext();
  3650. }, timeout);
  3651. }
  3652. }, callback);
  3653. };
  3654. return AsyncLoop;
  3655. })();
  3656. BABYLON.AsyncLoop = AsyncLoop;
  3657. })(BABYLON || (BABYLON = {}));
  3658. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3659. (function (BABYLON) {
  3660. var _DepthCullingState = (function () {
  3661. function _DepthCullingState() {
  3662. this._isDepthTestDirty = false;
  3663. this._isDepthMaskDirty = false;
  3664. this._isDepthFuncDirty = false;
  3665. this._isCullFaceDirty = false;
  3666. this._isCullDirty = false;
  3667. this._isZOffsetDirty = false;
  3668. }
  3669. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3670. get: function () {
  3671. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3672. },
  3673. enumerable: true,
  3674. configurable: true
  3675. });
  3676. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3677. get: function () {
  3678. return this._zOffset;
  3679. },
  3680. set: function (value) {
  3681. if (this._zOffset === value) {
  3682. return;
  3683. }
  3684. this._zOffset = value;
  3685. this._isZOffsetDirty = true;
  3686. },
  3687. enumerable: true,
  3688. configurable: true
  3689. });
  3690. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3691. get: function () {
  3692. return this._cullFace;
  3693. },
  3694. set: function (value) {
  3695. if (this._cullFace === value) {
  3696. return;
  3697. }
  3698. this._cullFace = value;
  3699. this._isCullFaceDirty = true;
  3700. },
  3701. enumerable: true,
  3702. configurable: true
  3703. });
  3704. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3705. get: function () {
  3706. return this._cull;
  3707. },
  3708. set: function (value) {
  3709. if (this._cull === value) {
  3710. return;
  3711. }
  3712. this._cull = value;
  3713. this._isCullDirty = true;
  3714. },
  3715. enumerable: true,
  3716. configurable: true
  3717. });
  3718. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3719. get: function () {
  3720. return this._depthFunc;
  3721. },
  3722. set: function (value) {
  3723. if (this._depthFunc === value) {
  3724. return;
  3725. }
  3726. this._depthFunc = value;
  3727. this._isDepthFuncDirty = true;
  3728. },
  3729. enumerable: true,
  3730. configurable: true
  3731. });
  3732. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3733. get: function () {
  3734. return this._depthMask;
  3735. },
  3736. set: function (value) {
  3737. if (this._depthMask === value) {
  3738. return;
  3739. }
  3740. this._depthMask = value;
  3741. this._isDepthMaskDirty = true;
  3742. },
  3743. enumerable: true,
  3744. configurable: true
  3745. });
  3746. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3747. get: function () {
  3748. return this._depthTest;
  3749. },
  3750. set: function (value) {
  3751. if (this._depthTest === value) {
  3752. return;
  3753. }
  3754. this._depthTest = value;
  3755. this._isDepthTestDirty = true;
  3756. },
  3757. enumerable: true,
  3758. configurable: true
  3759. });
  3760. _DepthCullingState.prototype.reset = function () {
  3761. this._depthMask = true;
  3762. this._depthTest = true;
  3763. this._depthFunc = null;
  3764. this._cull = null;
  3765. this._cullFace = null;
  3766. this._zOffset = 0;
  3767. this._isDepthTestDirty = true;
  3768. this._isDepthMaskDirty = true;
  3769. this._isDepthFuncDirty = false;
  3770. this._isCullFaceDirty = false;
  3771. this._isCullDirty = false;
  3772. this._isZOffsetDirty = false;
  3773. };
  3774. _DepthCullingState.prototype.apply = function (gl) {
  3775. if (!this.isDirty) {
  3776. return;
  3777. }
  3778. // Cull
  3779. if (this._isCullDirty) {
  3780. if (this.cull) {
  3781. gl.enable(gl.CULL_FACE);
  3782. }
  3783. else {
  3784. gl.disable(gl.CULL_FACE);
  3785. }
  3786. this._isCullDirty = false;
  3787. }
  3788. // Cull face
  3789. if (this._isCullFaceDirty) {
  3790. gl.cullFace(this.cullFace);
  3791. this._isCullFaceDirty = false;
  3792. }
  3793. // Depth mask
  3794. if (this._isDepthMaskDirty) {
  3795. gl.depthMask(this.depthMask);
  3796. this._isDepthMaskDirty = false;
  3797. }
  3798. // Depth test
  3799. if (this._isDepthTestDirty) {
  3800. if (this.depthTest) {
  3801. gl.enable(gl.DEPTH_TEST);
  3802. }
  3803. else {
  3804. gl.disable(gl.DEPTH_TEST);
  3805. }
  3806. this._isDepthTestDirty = false;
  3807. }
  3808. // Depth func
  3809. if (this._isDepthFuncDirty) {
  3810. gl.depthFunc(this.depthFunc);
  3811. this._isDepthFuncDirty = false;
  3812. }
  3813. // zOffset
  3814. if (this._isZOffsetDirty) {
  3815. if (this.zOffset) {
  3816. gl.enable(gl.POLYGON_OFFSET_FILL);
  3817. gl.polygonOffset(this.zOffset, 0);
  3818. }
  3819. else {
  3820. gl.disable(gl.POLYGON_OFFSET_FILL);
  3821. }
  3822. this._isZOffsetDirty = false;
  3823. }
  3824. };
  3825. return _DepthCullingState;
  3826. })();
  3827. BABYLON._DepthCullingState = _DepthCullingState;
  3828. var _AlphaState = (function () {
  3829. function _AlphaState() {
  3830. this._isAlphaBlendDirty = false;
  3831. this._isBlendFunctionParametersDirty = false;
  3832. this._alphaBlend = false;
  3833. this._blendFunctionParameters = new Array(4);
  3834. }
  3835. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3836. get: function () {
  3837. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3838. },
  3839. enumerable: true,
  3840. configurable: true
  3841. });
  3842. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3843. get: function () {
  3844. return this._alphaBlend;
  3845. },
  3846. set: function (value) {
  3847. if (this._alphaBlend === value) {
  3848. return;
  3849. }
  3850. this._alphaBlend = value;
  3851. this._isAlphaBlendDirty = true;
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3857. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3858. return;
  3859. }
  3860. this._blendFunctionParameters[0] = value0;
  3861. this._blendFunctionParameters[1] = value1;
  3862. this._blendFunctionParameters[2] = value2;
  3863. this._blendFunctionParameters[3] = value3;
  3864. this._isBlendFunctionParametersDirty = true;
  3865. };
  3866. _AlphaState.prototype.reset = function () {
  3867. this._alphaBlend = false;
  3868. this._blendFunctionParameters[0] = null;
  3869. this._blendFunctionParameters[1] = null;
  3870. this._blendFunctionParameters[2] = null;
  3871. this._blendFunctionParameters[3] = null;
  3872. this._isAlphaBlendDirty = true;
  3873. this._isBlendFunctionParametersDirty = false;
  3874. };
  3875. _AlphaState.prototype.apply = function (gl) {
  3876. if (!this.isDirty) {
  3877. return;
  3878. }
  3879. // Alpha blend
  3880. if (this._isAlphaBlendDirty) {
  3881. if (this._alphaBlend) {
  3882. gl.enable(gl.BLEND);
  3883. }
  3884. else {
  3885. gl.disable(gl.BLEND);
  3886. }
  3887. this._isAlphaBlendDirty = false;
  3888. }
  3889. // Alpha function
  3890. if (this._isBlendFunctionParametersDirty) {
  3891. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3892. this._isBlendFunctionParametersDirty = false;
  3893. }
  3894. };
  3895. return _AlphaState;
  3896. })();
  3897. BABYLON._AlphaState = _AlphaState;
  3898. var compileShader = function (gl, source, type, defines) {
  3899. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3900. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3901. gl.compileShader(shader);
  3902. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3903. throw new Error(gl.getShaderInfoLog(shader));
  3904. }
  3905. return shader;
  3906. };
  3907. var getWebGLTextureType = function (gl, type) {
  3908. var textureType = gl.UNSIGNED_BYTE;
  3909. if (type === Engine.TEXTURETYPE_FLOAT)
  3910. textureType = gl.FLOAT;
  3911. return textureType;
  3912. };
  3913. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3914. var magFilter = gl.NEAREST;
  3915. var minFilter = gl.NEAREST;
  3916. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3917. magFilter = gl.LINEAR;
  3918. if (generateMipMaps) {
  3919. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3920. }
  3921. else {
  3922. minFilter = gl.LINEAR;
  3923. }
  3924. }
  3925. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3926. magFilter = gl.LINEAR;
  3927. if (generateMipMaps) {
  3928. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3929. }
  3930. else {
  3931. minFilter = gl.LINEAR;
  3932. }
  3933. }
  3934. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3935. magFilter = gl.NEAREST;
  3936. if (generateMipMaps) {
  3937. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3938. }
  3939. else {
  3940. minFilter = gl.NEAREST;
  3941. }
  3942. }
  3943. return {
  3944. min: minFilter,
  3945. mag: magFilter
  3946. };
  3947. };
  3948. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3949. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3950. var engine = scene.getEngine();
  3951. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3952. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3953. gl.bindTexture(gl.TEXTURE_2D, texture);
  3954. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3955. texture._baseWidth = width;
  3956. texture._baseHeight = height;
  3957. texture._width = potWidth;
  3958. texture._height = potHeight;
  3959. texture.isReady = true;
  3960. processFunction(potWidth, potHeight);
  3961. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3962. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3964. if (!noMipmap && !isCompressed) {
  3965. gl.generateMipmap(gl.TEXTURE_2D);
  3966. }
  3967. gl.bindTexture(gl.TEXTURE_2D, null);
  3968. engine._activeTexturesCache = [];
  3969. scene._removePendingData(texture);
  3970. };
  3971. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3972. var onload = function () {
  3973. loadedImages[index] = img;
  3974. loadedImages._internalCount++;
  3975. scene._removePendingData(img);
  3976. if (loadedImages._internalCount === 6) {
  3977. onfinish(loadedImages);
  3978. }
  3979. };
  3980. var onerror = function () {
  3981. scene._removePendingData(img);
  3982. };
  3983. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3984. scene._addPendingData(img);
  3985. };
  3986. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3987. var loadedImages = [];
  3988. loadedImages._internalCount = 0;
  3989. for (var index = 0; index < 6; index++) {
  3990. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3991. }
  3992. };
  3993. var EngineCapabilities = (function () {
  3994. function EngineCapabilities() {
  3995. }
  3996. return EngineCapabilities;
  3997. })();
  3998. BABYLON.EngineCapabilities = EngineCapabilities;
  3999. /**
  4000. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  4001. */
  4002. var Engine = (function () {
  4003. /**
  4004. * @constructor
  4005. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  4006. * @param {boolean} [antialias] - enable antialias
  4007. * @param options - further options to be sent to the getContext function
  4008. */
  4009. function Engine(canvas, antialias, options) {
  4010. var _this = this;
  4011. // Public members
  4012. this.isFullscreen = false;
  4013. this.isPointerLock = false;
  4014. this.cullBackFaces = true;
  4015. this.renderEvenInBackground = true;
  4016. this.scenes = new Array();
  4017. this._windowIsBackground = false;
  4018. this._loadingDivBackgroundColor = "black";
  4019. this._drawCalls = 0;
  4020. this._renderingQueueLaunched = false;
  4021. this._activeRenderLoops = [];
  4022. // FPS
  4023. this.fpsRange = 60;
  4024. this.previousFramesDuration = [];
  4025. this.fps = 60;
  4026. this.deltaTime = 0;
  4027. // States
  4028. this._depthCullingState = new _DepthCullingState();
  4029. this._alphaState = new _AlphaState();
  4030. this._alphaMode = Engine.ALPHA_DISABLE;
  4031. // Cache
  4032. this._loadedTexturesCache = new Array();
  4033. this._activeTexturesCache = new Array();
  4034. this._compiledEffects = {};
  4035. this._uintIndicesCurrentlySet = false;
  4036. this._renderingCanvas = canvas;
  4037. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4038. options = options || {};
  4039. options.antialias = antialias;
  4040. try {
  4041. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4042. }
  4043. catch (e) {
  4044. throw new Error("WebGL not supported");
  4045. }
  4046. if (!this._gl) {
  4047. throw new Error("WebGL not supported");
  4048. }
  4049. this._onBlur = function () {
  4050. _this._windowIsBackground = true;
  4051. };
  4052. this._onFocus = function () {
  4053. _this._windowIsBackground = false;
  4054. };
  4055. window.addEventListener("blur", this._onBlur);
  4056. window.addEventListener("focus", this._onFocus);
  4057. // Viewport
  4058. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4059. this.resize();
  4060. // Caps
  4061. this._caps = new EngineCapabilities();
  4062. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4063. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4064. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4065. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4066. // Infos
  4067. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4068. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4069. if (rendererInfo != null) {
  4070. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4071. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4072. }
  4073. if (!this._glVendor) {
  4074. this._glVendor = "Unknown vendor";
  4075. }
  4076. if (!this._glRenderer) {
  4077. this._glRenderer = "Unknown renderer";
  4078. }
  4079. // Extensions
  4080. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4081. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4082. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4083. 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');
  4084. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4085. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4086. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4087. this._caps.highPrecisionShaderSupported = true;
  4088. if (this._gl.getShaderPrecisionFormat) {
  4089. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  4090. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  4091. }
  4092. // Depth buffer
  4093. this.setDepthBuffer(true);
  4094. this.setDepthFunctionToLessOrEqual();
  4095. this.setDepthWrite(true);
  4096. // Fullscreen
  4097. this._onFullscreenChange = function () {
  4098. if (document.fullscreen !== undefined) {
  4099. _this.isFullscreen = document.fullscreen;
  4100. }
  4101. else if (document.mozFullScreen !== undefined) {
  4102. _this.isFullscreen = document.mozFullScreen;
  4103. }
  4104. else if (document.webkitIsFullScreen !== undefined) {
  4105. _this.isFullscreen = document.webkitIsFullScreen;
  4106. }
  4107. else if (document.msIsFullScreen !== undefined) {
  4108. _this.isFullscreen = document.msIsFullScreen;
  4109. }
  4110. // Pointer lock
  4111. if (_this.isFullscreen && _this._pointerLockRequested) {
  4112. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4113. if (canvas.requestPointerLock) {
  4114. canvas.requestPointerLock();
  4115. }
  4116. }
  4117. };
  4118. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4119. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4120. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4121. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4122. // Pointer lock
  4123. this._onPointerLockChange = function () {
  4124. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4125. };
  4126. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4127. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4128. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4129. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4130. if (!Engine.audioEngine) {
  4131. Engine.audioEngine = new BABYLON.AudioEngine();
  4132. }
  4133. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4134. }
  4135. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4136. get: function () {
  4137. return Engine._ALPHA_DISABLE;
  4138. },
  4139. enumerable: true,
  4140. configurable: true
  4141. });
  4142. Object.defineProperty(Engine, "ALPHA_ADD", {
  4143. get: function () {
  4144. return Engine._ALPHA_ADD;
  4145. },
  4146. enumerable: true,
  4147. configurable: true
  4148. });
  4149. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4150. get: function () {
  4151. return Engine._ALPHA_COMBINE;
  4152. },
  4153. enumerable: true,
  4154. configurable: true
  4155. });
  4156. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4157. get: function () {
  4158. return Engine._DELAYLOADSTATE_NONE;
  4159. },
  4160. enumerable: true,
  4161. configurable: true
  4162. });
  4163. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4164. get: function () {
  4165. return Engine._DELAYLOADSTATE_LOADED;
  4166. },
  4167. enumerable: true,
  4168. configurable: true
  4169. });
  4170. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4171. get: function () {
  4172. return Engine._DELAYLOADSTATE_LOADING;
  4173. },
  4174. enumerable: true,
  4175. configurable: true
  4176. });
  4177. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4178. get: function () {
  4179. return Engine._DELAYLOADSTATE_NOTLOADED;
  4180. },
  4181. enumerable: true,
  4182. configurable: true
  4183. });
  4184. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4185. get: function () {
  4186. return Engine._TEXTUREFORMAT_ALPHA;
  4187. },
  4188. enumerable: true,
  4189. configurable: true
  4190. });
  4191. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4192. get: function () {
  4193. return Engine._TEXTUREFORMAT_LUMINANCE;
  4194. },
  4195. enumerable: true,
  4196. configurable: true
  4197. });
  4198. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4199. get: function () {
  4200. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4201. },
  4202. enumerable: true,
  4203. configurable: true
  4204. });
  4205. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4206. get: function () {
  4207. return Engine._TEXTUREFORMAT_RGB;
  4208. },
  4209. enumerable: true,
  4210. configurable: true
  4211. });
  4212. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4213. get: function () {
  4214. return Engine._TEXTUREFORMAT_RGBA;
  4215. },
  4216. enumerable: true,
  4217. configurable: true
  4218. });
  4219. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4220. get: function () {
  4221. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4222. },
  4223. enumerable: true,
  4224. configurable: true
  4225. });
  4226. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4227. get: function () {
  4228. return Engine._TEXTURETYPE_FLOAT;
  4229. },
  4230. enumerable: true,
  4231. configurable: true
  4232. });
  4233. Object.defineProperty(Engine, "Version", {
  4234. get: function () {
  4235. return "2.1.0 beta";
  4236. },
  4237. enumerable: true,
  4238. configurable: true
  4239. });
  4240. Engine.prototype._prepareWorkingCanvas = function () {
  4241. if (this._workingCanvas) {
  4242. return;
  4243. }
  4244. this._workingCanvas = document.createElement("canvas");
  4245. this._workingContext = this._workingCanvas.getContext("2d");
  4246. };
  4247. Engine.prototype.getGlInfo = function () {
  4248. return {
  4249. vendor: this._glVendor,
  4250. renderer: this._glRenderer,
  4251. version: this._glVersion
  4252. };
  4253. };
  4254. Engine.prototype.getAspectRatio = function (camera) {
  4255. var viewport = camera.viewport;
  4256. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4257. };
  4258. Engine.prototype.getRenderWidth = function () {
  4259. if (this._currentRenderTarget) {
  4260. return this._currentRenderTarget._width;
  4261. }
  4262. return this._renderingCanvas.width;
  4263. };
  4264. Engine.prototype.getRenderHeight = function () {
  4265. if (this._currentRenderTarget) {
  4266. return this._currentRenderTarget._height;
  4267. }
  4268. return this._renderingCanvas.height;
  4269. };
  4270. Engine.prototype.getRenderingCanvas = function () {
  4271. return this._renderingCanvas;
  4272. };
  4273. Engine.prototype.getRenderingCanvasClientRect = function () {
  4274. return this._renderingCanvas.getBoundingClientRect();
  4275. };
  4276. Engine.prototype.setHardwareScalingLevel = function (level) {
  4277. this._hardwareScalingLevel = level;
  4278. this.resize();
  4279. };
  4280. Engine.prototype.getHardwareScalingLevel = function () {
  4281. return this._hardwareScalingLevel;
  4282. };
  4283. Engine.prototype.getLoadedTexturesCache = function () {
  4284. return this._loadedTexturesCache;
  4285. };
  4286. Engine.prototype.getCaps = function () {
  4287. return this._caps;
  4288. };
  4289. Object.defineProperty(Engine.prototype, "drawCalls", {
  4290. get: function () {
  4291. return this._drawCalls;
  4292. },
  4293. enumerable: true,
  4294. configurable: true
  4295. });
  4296. // Methods
  4297. Engine.prototype.resetDrawCalls = function () {
  4298. this._drawCalls = 0;
  4299. };
  4300. Engine.prototype.setDepthFunctionToGreater = function () {
  4301. this._depthCullingState.depthFunc = this._gl.GREATER;
  4302. };
  4303. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4304. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4305. };
  4306. Engine.prototype.setDepthFunctionToLess = function () {
  4307. this._depthCullingState.depthFunc = this._gl.LESS;
  4308. };
  4309. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4310. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4311. };
  4312. /**
  4313. * stop executing a render loop function and remove it from the execution array
  4314. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4315. */
  4316. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4317. if (!renderFunction) {
  4318. this._activeRenderLoops = [];
  4319. return;
  4320. }
  4321. var index = this._activeRenderLoops.indexOf(renderFunction);
  4322. if (index >= 0) {
  4323. this._activeRenderLoops.splice(index, 1);
  4324. }
  4325. };
  4326. Engine.prototype._renderLoop = function () {
  4327. var _this = this;
  4328. var shouldRender = true;
  4329. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4330. shouldRender = false;
  4331. }
  4332. if (shouldRender) {
  4333. // Start new frame
  4334. this.beginFrame();
  4335. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4336. var renderFunction = this._activeRenderLoops[index];
  4337. renderFunction();
  4338. }
  4339. // Present
  4340. this.endFrame();
  4341. }
  4342. if (this._activeRenderLoops.length > 0) {
  4343. // Register new frame
  4344. BABYLON.Tools.QueueNewFrame(function () {
  4345. _this._renderLoop();
  4346. });
  4347. }
  4348. else {
  4349. this._renderingQueueLaunched = false;
  4350. }
  4351. };
  4352. /**
  4353. * Register and execute a render loop. The engine can have more than one render function.
  4354. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4355. * @example
  4356. * engine.runRenderLoop(function () {
  4357. * scene.render()
  4358. * })
  4359. */
  4360. Engine.prototype.runRenderLoop = function (renderFunction) {
  4361. var _this = this;
  4362. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4363. return;
  4364. }
  4365. this._activeRenderLoops.push(renderFunction);
  4366. if (!this._renderingQueueLaunched) {
  4367. this._renderingQueueLaunched = true;
  4368. BABYLON.Tools.QueueNewFrame(function () {
  4369. _this._renderLoop();
  4370. });
  4371. }
  4372. };
  4373. /**
  4374. * Toggle full screen mode.
  4375. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4376. */
  4377. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4378. if (this.isFullscreen) {
  4379. BABYLON.Tools.ExitFullscreen();
  4380. }
  4381. else {
  4382. this._pointerLockRequested = requestPointerLock;
  4383. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4384. }
  4385. };
  4386. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4387. this.applyStates();
  4388. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4389. if (this._depthCullingState.depthMask) {
  4390. this._gl.clearDepth(1.0);
  4391. }
  4392. var mode = 0;
  4393. if (backBuffer)
  4394. mode |= this._gl.COLOR_BUFFER_BIT;
  4395. if (depthStencil && this._depthCullingState.depthMask)
  4396. mode |= this._gl.DEPTH_BUFFER_BIT;
  4397. this._gl.clear(mode);
  4398. };
  4399. /**
  4400. * Set the WebGL's viewport
  4401. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4402. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4403. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4404. */
  4405. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4406. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  4407. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  4408. var x = viewport.x || 0;
  4409. var y = viewport.y || 0;
  4410. this._cachedViewport = viewport;
  4411. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4412. };
  4413. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4414. this._cachedViewport = null;
  4415. this._gl.viewport(x, y, width, height);
  4416. };
  4417. Engine.prototype.beginFrame = function () {
  4418. this._measureFps();
  4419. };
  4420. Engine.prototype.endFrame = function () {
  4421. //this.flushFramebuffer();
  4422. };
  4423. /**
  4424. * resize the view according to the canvas' size.
  4425. * @example
  4426. * window.addEventListener("resize", function () {
  4427. * engine.resize();
  4428. * });
  4429. */
  4430. Engine.prototype.resize = function () {
  4431. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  4432. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  4433. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  4434. };
  4435. /**
  4436. * force a specific size of the canvas
  4437. * @param {number} width - the new canvas' width
  4438. * @param {number} height - the new canvas' height
  4439. */
  4440. Engine.prototype.setSize = function (width, height) {
  4441. this._renderingCanvas.width = width;
  4442. this._renderingCanvas.height = height;
  4443. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4444. for (var index = 0; index < this.scenes.length; index++) {
  4445. var scene = this.scenes[index];
  4446. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  4447. var cam = scene.cameras[camIndex];
  4448. cam._currentRenderId = 0;
  4449. }
  4450. }
  4451. };
  4452. Engine.prototype.bindFramebuffer = function (texture) {
  4453. this._currentRenderTarget = texture;
  4454. var gl = this._gl;
  4455. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4456. this._gl.viewport(0, 0, texture._width, texture._height);
  4457. this.wipeCaches();
  4458. };
  4459. Engine.prototype.unBindFramebuffer = function (texture) {
  4460. this._currentRenderTarget = null;
  4461. if (texture.generateMipMaps) {
  4462. var gl = this._gl;
  4463. gl.bindTexture(gl.TEXTURE_2D, texture);
  4464. gl.generateMipmap(gl.TEXTURE_2D);
  4465. gl.bindTexture(gl.TEXTURE_2D, null);
  4466. }
  4467. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4468. };
  4469. Engine.prototype.flushFramebuffer = function () {
  4470. this._gl.flush();
  4471. };
  4472. Engine.prototype.restoreDefaultFramebuffer = function () {
  4473. this._currentRenderTarget = null;
  4474. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4475. this.setViewport(this._cachedViewport);
  4476. this.wipeCaches();
  4477. };
  4478. // VBOs
  4479. Engine.prototype._resetVertexBufferBinding = function () {
  4480. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4481. this._cachedVertexBuffers = null;
  4482. };
  4483. Engine.prototype.createVertexBuffer = function (vertices) {
  4484. var vbo = this._gl.createBuffer();
  4485. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4486. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4487. this._resetVertexBufferBinding();
  4488. vbo.references = 1;
  4489. return vbo;
  4490. };
  4491. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4492. var vbo = this._gl.createBuffer();
  4493. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4494. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4495. this._resetVertexBufferBinding();
  4496. vbo.references = 1;
  4497. return vbo;
  4498. };
  4499. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4500. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4501. if (offset === undefined) {
  4502. offset = 0;
  4503. }
  4504. if (vertices instanceof Float32Array) {
  4505. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4506. }
  4507. else {
  4508. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4509. }
  4510. this._resetVertexBufferBinding();
  4511. };
  4512. Engine.prototype._resetIndexBufferBinding = function () {
  4513. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4514. this._cachedIndexBuffer = null;
  4515. };
  4516. Engine.prototype.createIndexBuffer = function (indices) {
  4517. var vbo = this._gl.createBuffer();
  4518. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4519. // Check for 32 bits indices
  4520. var arrayBuffer;
  4521. var need32Bits = false;
  4522. if (this._caps.uintIndices) {
  4523. for (var index = 0; index < indices.length; index++) {
  4524. if (indices[index] > 65535) {
  4525. need32Bits = true;
  4526. break;
  4527. }
  4528. }
  4529. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4530. }
  4531. else {
  4532. arrayBuffer = new Uint16Array(indices);
  4533. }
  4534. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4535. this._resetIndexBufferBinding();
  4536. vbo.references = 1;
  4537. vbo.is32Bits = need32Bits;
  4538. return vbo;
  4539. };
  4540. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4541. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4542. this._cachedVertexBuffers = vertexBuffer;
  4543. this._cachedEffectForVertexBuffers = effect;
  4544. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4545. var offset = 0;
  4546. for (var index = 0; index < vertexDeclaration.length; index++) {
  4547. var order = effect.getAttributeLocation(index);
  4548. if (order >= 0) {
  4549. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4550. }
  4551. offset += vertexDeclaration[index] * 4;
  4552. }
  4553. }
  4554. if (this._cachedIndexBuffer !== indexBuffer) {
  4555. this._cachedIndexBuffer = indexBuffer;
  4556. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4557. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4558. }
  4559. };
  4560. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4561. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4562. this._cachedVertexBuffers = vertexBuffers;
  4563. this._cachedEffectForVertexBuffers = effect;
  4564. var attributes = effect.getAttributesNames();
  4565. for (var index = 0; index < attributes.length; index++) {
  4566. var order = effect.getAttributeLocation(index);
  4567. if (order >= 0) {
  4568. var vertexBuffer = vertexBuffers[attributes[index]];
  4569. if (!vertexBuffer) {
  4570. continue;
  4571. }
  4572. var stride = vertexBuffer.getStrideSize();
  4573. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4574. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4575. }
  4576. }
  4577. }
  4578. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4579. this._cachedIndexBuffer = indexBuffer;
  4580. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4581. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4582. }
  4583. };
  4584. Engine.prototype._releaseBuffer = function (buffer) {
  4585. buffer.references--;
  4586. if (buffer.references === 0) {
  4587. this._gl.deleteBuffer(buffer);
  4588. return true;
  4589. }
  4590. return false;
  4591. };
  4592. Engine.prototype.createInstancesBuffer = function (capacity) {
  4593. var buffer = this._gl.createBuffer();
  4594. buffer.capacity = capacity;
  4595. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4596. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4597. return buffer;
  4598. };
  4599. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4600. this._gl.deleteBuffer(buffer);
  4601. };
  4602. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4603. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4604. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4605. for (var index = 0; index < 4; index++) {
  4606. var offsetLocation = offsetLocations[index];
  4607. this._gl.enableVertexAttribArray(offsetLocation);
  4608. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4609. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4610. }
  4611. };
  4612. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4613. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4614. for (var index = 0; index < 4; index++) {
  4615. var offsetLocation = offsetLocations[index];
  4616. this._gl.disableVertexAttribArray(offsetLocation);
  4617. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4618. }
  4619. };
  4620. Engine.prototype.applyStates = function () {
  4621. this._depthCullingState.apply(this._gl);
  4622. this._alphaState.apply(this._gl);
  4623. };
  4624. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4625. // Apply states
  4626. this.applyStates();
  4627. this._drawCalls++;
  4628. // Render
  4629. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4630. if (instancesCount) {
  4631. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4632. return;
  4633. }
  4634. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4635. };
  4636. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4637. // Apply states
  4638. this.applyStates();
  4639. this._drawCalls++;
  4640. if (instancesCount) {
  4641. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4642. return;
  4643. }
  4644. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4645. };
  4646. // Shaders
  4647. Engine.prototype._releaseEffect = function (effect) {
  4648. if (this._compiledEffects[effect._key]) {
  4649. delete this._compiledEffects[effect._key];
  4650. if (effect.getProgram()) {
  4651. this._gl.deleteProgram(effect.getProgram());
  4652. }
  4653. }
  4654. };
  4655. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4656. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4657. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4658. var name = vertex + "+" + fragment + "@" + defines;
  4659. if (this._compiledEffects[name]) {
  4660. return this._compiledEffects[name];
  4661. }
  4662. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4663. effect._key = name;
  4664. this._compiledEffects[name] = effect;
  4665. return effect;
  4666. };
  4667. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4668. if (uniformsNames === void 0) { uniformsNames = []; }
  4669. if (samplers === void 0) { samplers = []; }
  4670. if (defines === void 0) { defines = ""; }
  4671. return this.createEffect({
  4672. vertex: "particles",
  4673. fragmentElement: fragmentName
  4674. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4675. };
  4676. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4677. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4678. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4679. var shaderProgram = this._gl.createProgram();
  4680. this._gl.attachShader(shaderProgram, vertexShader);
  4681. this._gl.attachShader(shaderProgram, fragmentShader);
  4682. this._gl.linkProgram(shaderProgram);
  4683. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4684. if (!linked) {
  4685. var error = this._gl.getProgramInfoLog(shaderProgram);
  4686. if (error) {
  4687. throw new Error(error);
  4688. }
  4689. }
  4690. this._gl.deleteShader(vertexShader);
  4691. this._gl.deleteShader(fragmentShader);
  4692. return shaderProgram;
  4693. };
  4694. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4695. var results = [];
  4696. for (var index = 0; index < uniformsNames.length; index++) {
  4697. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4698. }
  4699. return results;
  4700. };
  4701. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4702. var results = [];
  4703. for (var index = 0; index < attributesNames.length; index++) {
  4704. try {
  4705. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4706. }
  4707. catch (e) {
  4708. results.push(-1);
  4709. }
  4710. }
  4711. return results;
  4712. };
  4713. Engine.prototype.enableEffect = function (effect) {
  4714. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4715. if (effect && effect.onBind) {
  4716. effect.onBind(effect);
  4717. }
  4718. return;
  4719. }
  4720. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4721. // Use program
  4722. this._gl.useProgram(effect.getProgram());
  4723. for (var i in this._vertexAttribArrays) {
  4724. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4725. continue;
  4726. }
  4727. this._vertexAttribArrays[i] = false;
  4728. this._gl.disableVertexAttribArray(i);
  4729. }
  4730. var attributesCount = effect.getAttributesCount();
  4731. for (var index = 0; index < attributesCount; index++) {
  4732. // Attributes
  4733. var order = effect.getAttributeLocation(index);
  4734. if (order >= 0) {
  4735. this._vertexAttribArrays[order] = true;
  4736. this._gl.enableVertexAttribArray(order);
  4737. }
  4738. }
  4739. this._currentEffect = effect;
  4740. if (effect.onBind) {
  4741. effect.onBind(effect);
  4742. }
  4743. };
  4744. Engine.prototype.setArray = function (uniform, array) {
  4745. if (!uniform)
  4746. return;
  4747. this._gl.uniform1fv(uniform, array);
  4748. };
  4749. Engine.prototype.setArray2 = function (uniform, array) {
  4750. if (!uniform || array.length % 2 !== 0)
  4751. return;
  4752. this._gl.uniform2fv(uniform, array);
  4753. };
  4754. Engine.prototype.setArray3 = function (uniform, array) {
  4755. if (!uniform || array.length % 3 !== 0)
  4756. return;
  4757. this._gl.uniform3fv(uniform, array);
  4758. };
  4759. Engine.prototype.setArray4 = function (uniform, array) {
  4760. if (!uniform || array.length % 4 !== 0)
  4761. return;
  4762. this._gl.uniform4fv(uniform, array);
  4763. };
  4764. Engine.prototype.setMatrices = function (uniform, matrices) {
  4765. if (!uniform)
  4766. return;
  4767. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4768. };
  4769. Engine.prototype.setMatrix = function (uniform, matrix) {
  4770. if (!uniform)
  4771. return;
  4772. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4773. };
  4774. Engine.prototype.setFloat = function (uniform, value) {
  4775. if (!uniform)
  4776. return;
  4777. this._gl.uniform1f(uniform, value);
  4778. };
  4779. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4780. if (!uniform)
  4781. return;
  4782. this._gl.uniform2f(uniform, x, y);
  4783. };
  4784. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4785. if (!uniform)
  4786. return;
  4787. this._gl.uniform3f(uniform, x, y, z);
  4788. };
  4789. Engine.prototype.setBool = function (uniform, bool) {
  4790. if (!uniform)
  4791. return;
  4792. this._gl.uniform1i(uniform, bool);
  4793. };
  4794. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4795. if (!uniform)
  4796. return;
  4797. this._gl.uniform4f(uniform, x, y, z, w);
  4798. };
  4799. Engine.prototype.setColor3 = function (uniform, color3) {
  4800. if (!uniform)
  4801. return;
  4802. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4803. };
  4804. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4805. if (!uniform)
  4806. return;
  4807. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4808. };
  4809. // States
  4810. Engine.prototype.setState = function (culling, zOffset, force) {
  4811. if (zOffset === void 0) { zOffset = 0; }
  4812. // Culling
  4813. if (this._depthCullingState.cull !== culling || force) {
  4814. if (culling) {
  4815. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4816. this._depthCullingState.cull = true;
  4817. }
  4818. else {
  4819. this._depthCullingState.cull = false;
  4820. }
  4821. }
  4822. // Z offset
  4823. this._depthCullingState.zOffset = zOffset;
  4824. };
  4825. Engine.prototype.setDepthBuffer = function (enable) {
  4826. this._depthCullingState.depthTest = enable;
  4827. };
  4828. Engine.prototype.getDepthWrite = function () {
  4829. return this._depthCullingState.depthMask;
  4830. };
  4831. Engine.prototype.setDepthWrite = function (enable) {
  4832. this._depthCullingState.depthMask = enable;
  4833. };
  4834. Engine.prototype.setColorWrite = function (enable) {
  4835. this._gl.colorMask(enable, enable, enable, enable);
  4836. };
  4837. Engine.prototype.setAlphaMode = function (mode) {
  4838. switch (mode) {
  4839. case Engine.ALPHA_DISABLE:
  4840. this.setDepthWrite(true);
  4841. this._alphaState.alphaBlend = false;
  4842. break;
  4843. case Engine.ALPHA_COMBINE:
  4844. this.setDepthWrite(false);
  4845. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4846. this._alphaState.alphaBlend = true;
  4847. break;
  4848. case Engine.ALPHA_ADD:
  4849. this.setDepthWrite(false);
  4850. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4851. this._alphaState.alphaBlend = true;
  4852. break;
  4853. }
  4854. this._alphaMode = mode;
  4855. };
  4856. Engine.prototype.getAlphaMode = function () {
  4857. return this._alphaMode;
  4858. };
  4859. Engine.prototype.setAlphaTesting = function (enable) {
  4860. this._alphaTest = enable;
  4861. };
  4862. Engine.prototype.getAlphaTesting = function () {
  4863. return this._alphaTest;
  4864. };
  4865. // Textures
  4866. Engine.prototype.wipeCaches = function () {
  4867. this._activeTexturesCache = [];
  4868. this._currentEffect = null;
  4869. this._depthCullingState.reset();
  4870. this._alphaState.reset();
  4871. this._cachedVertexBuffers = null;
  4872. this._cachedIndexBuffer = null;
  4873. this._cachedEffectForVertexBuffers = null;
  4874. };
  4875. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4876. var gl = this._gl;
  4877. gl.bindTexture(gl.TEXTURE_2D, texture);
  4878. var magFilter = gl.NEAREST;
  4879. var minFilter = gl.NEAREST;
  4880. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4881. magFilter = gl.LINEAR;
  4882. minFilter = gl.LINEAR;
  4883. }
  4884. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4885. magFilter = gl.LINEAR;
  4886. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4887. }
  4888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4889. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4890. gl.bindTexture(gl.TEXTURE_2D, null);
  4891. texture.samplingMode = samplingMode;
  4892. };
  4893. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4894. var _this = this;
  4895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4896. if (onLoad === void 0) { onLoad = null; }
  4897. if (onError === void 0) { onError = null; }
  4898. if (buffer === void 0) { buffer = null; }
  4899. var texture = this._gl.createTexture();
  4900. var extension;
  4901. var fromData = false;
  4902. if (url.substr(0, 5) === "data:") {
  4903. fromData = true;
  4904. }
  4905. if (!fromData)
  4906. extension = url.substr(url.length - 4, 4).toLowerCase();
  4907. else {
  4908. var oldUrl = url;
  4909. fromData = oldUrl.split(':');
  4910. url = oldUrl;
  4911. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4912. }
  4913. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4914. var isTGA = (extension === ".tga");
  4915. scene._addPendingData(texture);
  4916. texture.url = url;
  4917. texture.noMipmap = noMipmap;
  4918. texture.references = 1;
  4919. texture.samplingMode = samplingMode;
  4920. this._loadedTexturesCache.push(texture);
  4921. var onerror = function () {
  4922. scene._removePendingData(texture);
  4923. if (onError) {
  4924. onError();
  4925. }
  4926. };
  4927. if (isTGA) {
  4928. var callback = function (arrayBuffer) {
  4929. var data = new Uint8Array(arrayBuffer);
  4930. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4931. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4932. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4933. if (onLoad) {
  4934. onLoad();
  4935. }
  4936. }, samplingMode);
  4937. };
  4938. if (!(fromData instanceof Array))
  4939. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4940. callback(arrayBuffer);
  4941. }, onerror, scene.database, true);
  4942. else
  4943. callback(buffer);
  4944. }
  4945. else if (isDDS) {
  4946. callback = function (data) {
  4947. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4948. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4949. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4950. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4951. if (onLoad) {
  4952. onLoad();
  4953. }
  4954. }, samplingMode);
  4955. };
  4956. if (!(fromData instanceof Array))
  4957. BABYLON.Tools.LoadFile(url, function (data) {
  4958. callback(data);
  4959. }, onerror, scene.database, true);
  4960. else
  4961. callback(buffer);
  4962. }
  4963. else {
  4964. var onload = function (img) {
  4965. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4966. var isPot = (img.width === potWidth && img.height === potHeight);
  4967. if (!isPot) {
  4968. _this._prepareWorkingCanvas();
  4969. _this._workingCanvas.width = potWidth;
  4970. _this._workingCanvas.height = potHeight;
  4971. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4972. _this._workingContext.imageSmoothingEnabled = false;
  4973. _this._workingContext.mozImageSmoothingEnabled = false;
  4974. _this._workingContext.oImageSmoothingEnabled = false;
  4975. _this._workingContext.webkitImageSmoothingEnabled = false;
  4976. _this._workingContext.msImageSmoothingEnabled = false;
  4977. }
  4978. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4979. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4980. _this._workingContext.imageSmoothingEnabled = true;
  4981. _this._workingContext.mozImageSmoothingEnabled = true;
  4982. _this._workingContext.oImageSmoothingEnabled = true;
  4983. _this._workingContext.webkitImageSmoothingEnabled = true;
  4984. _this._workingContext.msImageSmoothingEnabled = true;
  4985. }
  4986. }
  4987. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4988. if (onLoad) {
  4989. onLoad();
  4990. }
  4991. }, samplingMode);
  4992. };
  4993. if (!(fromData instanceof Array))
  4994. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4995. else
  4996. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4997. }
  4998. return texture;
  4999. };
  5000. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  5001. var texture = this._gl.createTexture();
  5002. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5003. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5004. // Format
  5005. var internalFormat = this._gl.RGBA;
  5006. switch (format) {
  5007. case Engine.TEXTUREFORMAT_ALPHA:
  5008. internalFormat = this._gl.ALPHA;
  5009. break;
  5010. case Engine.TEXTUREFORMAT_LUMINANCE:
  5011. internalFormat = this._gl.LUMINANCE;
  5012. break;
  5013. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5014. internalFormat = this._gl.LUMINANCE_ALPHA;
  5015. break;
  5016. case Engine.TEXTUREFORMAT_RGB:
  5017. internalFormat = this._gl.RGB;
  5018. break;
  5019. case Engine.TEXTUREFORMAT_RGBA:
  5020. internalFormat = this._gl.RGBA;
  5021. break;
  5022. }
  5023. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  5024. if (generateMipMaps) {
  5025. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5026. }
  5027. // Filters
  5028. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  5029. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5030. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5031. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5032. this._activeTexturesCache = [];
  5033. texture._baseWidth = width;
  5034. texture._baseHeight = height;
  5035. texture._width = width;
  5036. texture._height = height;
  5037. texture.isReady = true;
  5038. texture.references = 1;
  5039. texture.samplingMode = samplingMode;
  5040. this._loadedTexturesCache.push(texture);
  5041. return texture;
  5042. };
  5043. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5044. var texture = this._gl.createTexture();
  5045. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5046. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5047. this._activeTexturesCache = [];
  5048. texture._baseWidth = width;
  5049. texture._baseHeight = height;
  5050. texture._width = width;
  5051. texture._height = height;
  5052. texture.isReady = false;
  5053. texture.generateMipMaps = generateMipMaps;
  5054. texture.references = 1;
  5055. texture.samplingMode = samplingMode;
  5056. this.updateTextureSamplingMode(samplingMode, texture);
  5057. this._loadedTexturesCache.push(texture);
  5058. return texture;
  5059. };
  5060. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5061. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5062. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5063. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5064. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5065. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5066. };
  5067. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5068. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5069. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5070. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5071. if (texture.generateMipMaps) {
  5072. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5073. }
  5074. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5075. this._activeTexturesCache = [];
  5076. texture.isReady = true;
  5077. };
  5078. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5079. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5080. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5081. // Scale the video if it is a NPOT using the current working canvas
  5082. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5083. if (!texture._workingCanvas) {
  5084. texture._workingCanvas = document.createElement("canvas");
  5085. texture._workingContext = texture._workingCanvas.getContext("2d");
  5086. texture._workingCanvas.width = texture._width;
  5087. texture._workingCanvas.height = texture._height;
  5088. }
  5089. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5090. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5091. }
  5092. else {
  5093. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5094. }
  5095. if (texture.generateMipMaps) {
  5096. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5097. }
  5098. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5099. this._activeTexturesCache = [];
  5100. texture.isReady = true;
  5101. };
  5102. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5103. // old version had a "generateMipMaps" arg instead of options.
  5104. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5105. // in the same way, generateDepthBuffer is defaulted to true
  5106. var generateMipMaps = false;
  5107. var generateDepthBuffer = true;
  5108. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5109. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5110. if (options !== undefined) {
  5111. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5112. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5113. type = options.type === undefined ? type : options.type;
  5114. if (options.samplingMode !== undefined) {
  5115. samplingMode = options.samplingMode;
  5116. }
  5117. if (type === Engine.TEXTURETYPE_FLOAT) {
  5118. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5119. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5120. }
  5121. }
  5122. var gl = this._gl;
  5123. var texture = gl.createTexture();
  5124. gl.bindTexture(gl.TEXTURE_2D, texture);
  5125. var width = size.width || size;
  5126. var height = size.height || size;
  5127. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5128. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5129. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5130. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5131. }
  5132. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5136. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5137. var depthBuffer;
  5138. // Create the depth buffer
  5139. if (generateDepthBuffer) {
  5140. depthBuffer = gl.createRenderbuffer();
  5141. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5142. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5143. }
  5144. // Create the framebuffer
  5145. var framebuffer = gl.createFramebuffer();
  5146. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5147. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5148. if (generateDepthBuffer) {
  5149. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5150. }
  5151. // Unbind
  5152. gl.bindTexture(gl.TEXTURE_2D, null);
  5153. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5154. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5155. texture._framebuffer = framebuffer;
  5156. if (generateDepthBuffer) {
  5157. texture._depthBuffer = depthBuffer;
  5158. }
  5159. texture._width = width;
  5160. texture._height = height;
  5161. texture.isReady = true;
  5162. texture.generateMipMaps = generateMipMaps;
  5163. texture.references = 1;
  5164. texture.samplingMode = samplingMode;
  5165. this._activeTexturesCache = [];
  5166. this._loadedTexturesCache.push(texture);
  5167. return texture;
  5168. };
  5169. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5170. var _this = this;
  5171. var gl = this._gl;
  5172. var texture = gl.createTexture();
  5173. texture.isCube = true;
  5174. texture.url = rootUrl;
  5175. texture.references = 1;
  5176. this._loadedTexturesCache.push(texture);
  5177. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5178. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5179. if (isDDS) {
  5180. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5181. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5182. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5183. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5184. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5185. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5186. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5187. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5188. }
  5189. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5190. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5193. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5194. _this._activeTexturesCache = [];
  5195. texture._width = info.width;
  5196. texture._height = info.height;
  5197. texture.isReady = true;
  5198. }, null, null, true);
  5199. }
  5200. else {
  5201. cascadeLoad(rootUrl, scene, function (imgs) {
  5202. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5203. var height = width;
  5204. _this._prepareWorkingCanvas();
  5205. _this._workingCanvas.width = width;
  5206. _this._workingCanvas.height = height;
  5207. var faces = [
  5208. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5209. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5210. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5211. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5212. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5213. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5214. ];
  5215. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5216. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5217. for (var index = 0; index < faces.length; index++) {
  5218. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5219. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5220. }
  5221. if (!noMipmap) {
  5222. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5223. }
  5224. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5228. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5229. _this._activeTexturesCache = [];
  5230. texture._width = width;
  5231. texture._height = height;
  5232. texture.isReady = true;
  5233. }, extensions);
  5234. }
  5235. return texture;
  5236. };
  5237. Engine.prototype._releaseTexture = function (texture) {
  5238. var gl = this._gl;
  5239. if (texture._framebuffer) {
  5240. gl.deleteFramebuffer(texture._framebuffer);
  5241. }
  5242. if (texture._depthBuffer) {
  5243. gl.deleteRenderbuffer(texture._depthBuffer);
  5244. }
  5245. gl.deleteTexture(texture);
  5246. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5247. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5248. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5249. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5250. this._activeTexturesCache[channel] = null;
  5251. }
  5252. var index = this._loadedTexturesCache.indexOf(texture);
  5253. if (index !== -1) {
  5254. this._loadedTexturesCache.splice(index, 1);
  5255. }
  5256. };
  5257. Engine.prototype.bindSamplers = function (effect) {
  5258. this._gl.useProgram(effect.getProgram());
  5259. var samplers = effect.getSamplers();
  5260. for (var index = 0; index < samplers.length; index++) {
  5261. var uniform = effect.getUniform(samplers[index]);
  5262. this._gl.uniform1i(uniform, index);
  5263. }
  5264. this._currentEffect = null;
  5265. };
  5266. Engine.prototype._bindTexture = function (channel, texture) {
  5267. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5268. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5269. this._activeTexturesCache[channel] = null;
  5270. };
  5271. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5272. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5273. };
  5274. Engine.prototype.setTexture = function (channel, texture) {
  5275. if (channel < 0) {
  5276. return;
  5277. }
  5278. // Not ready?
  5279. if (!texture || !texture.isReady()) {
  5280. if (this._activeTexturesCache[channel] != null) {
  5281. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5282. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5283. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5284. this._activeTexturesCache[channel] = null;
  5285. }
  5286. return;
  5287. }
  5288. // Video
  5289. if (texture instanceof BABYLON.VideoTexture) {
  5290. if (texture.update()) {
  5291. this._activeTexturesCache[channel] = null;
  5292. }
  5293. }
  5294. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5295. texture.delayLoad();
  5296. return;
  5297. }
  5298. if (this._activeTexturesCache[channel] === texture) {
  5299. return;
  5300. }
  5301. this._activeTexturesCache[channel] = texture;
  5302. var internalTexture = texture.getInternalTexture();
  5303. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5304. if (internalTexture.isCube) {
  5305. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5306. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5307. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5308. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5309. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5310. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5311. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5312. }
  5313. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5314. }
  5315. else {
  5316. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5317. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5318. internalTexture._cachedWrapU = texture.wrapU;
  5319. switch (texture.wrapU) {
  5320. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5321. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5322. break;
  5323. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5324. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5325. break;
  5326. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5327. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5328. break;
  5329. }
  5330. }
  5331. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5332. internalTexture._cachedWrapV = texture.wrapV;
  5333. switch (texture.wrapV) {
  5334. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5335. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5336. break;
  5337. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5338. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5339. break;
  5340. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5341. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5342. break;
  5343. }
  5344. }
  5345. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5346. }
  5347. };
  5348. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5349. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5350. var value = texture.anisotropicFilteringLevel;
  5351. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5352. value = 1;
  5353. }
  5354. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5355. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5356. texture._cachedAnisotropicFilteringLevel = value;
  5357. }
  5358. };
  5359. Engine.prototype.readPixels = function (x, y, width, height) {
  5360. var data = new Uint8Array(height * width * 4);
  5361. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5362. return data;
  5363. };
  5364. // Dispose
  5365. Engine.prototype.dispose = function () {
  5366. this.hideLoadingUI();
  5367. this.stopRenderLoop();
  5368. while (this.scenes.length) {
  5369. this.scenes[0].dispose();
  5370. }
  5371. // Release audio engine
  5372. Engine.audioEngine.dispose();
  5373. for (var name in this._compiledEffects) {
  5374. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5375. }
  5376. for (var i in this._vertexAttribArrays) {
  5377. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5378. continue;
  5379. }
  5380. this._gl.disableVertexAttribArray(i);
  5381. }
  5382. // Events
  5383. window.removeEventListener("blur", this._onBlur);
  5384. window.removeEventListener("focus", this._onFocus);
  5385. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5386. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5387. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5388. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5389. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5390. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5391. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5392. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5393. };
  5394. // Loading screen
  5395. Engine.prototype.displayLoadingUI = function () {
  5396. var _this = this;
  5397. this._loadingDiv = document.createElement("div");
  5398. this._loadingDiv.style.opacity = "0";
  5399. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5400. // Loading text
  5401. this._loadingTextDiv = document.createElement("div");
  5402. this._loadingTextDiv.style.position = "absolute";
  5403. this._loadingTextDiv.style.left = "0";
  5404. this._loadingTextDiv.style.top = "50%";
  5405. this._loadingTextDiv.style.marginTop = "80px";
  5406. this._loadingTextDiv.style.width = "100%";
  5407. this._loadingTextDiv.style.height = "20px";
  5408. this._loadingTextDiv.style.fontFamily = "Arial";
  5409. this._loadingTextDiv.style.fontSize = "14px";
  5410. this._loadingTextDiv.style.color = "white";
  5411. this._loadingTextDiv.style.textAlign = "center";
  5412. this._loadingTextDiv.innerHTML = "Loading";
  5413. this._loadingDiv.appendChild(this._loadingTextDiv);
  5414. // Loading img
  5415. var imgBack = new Image();
  5416. 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==";
  5417. imgBack.style.position = "absolute";
  5418. imgBack.style.left = "50%";
  5419. imgBack.style.top = "50%";
  5420. imgBack.style.marginLeft = "-50px";
  5421. imgBack.style.marginTop = "-50px";
  5422. imgBack.style.transition = "transform 1.0s ease";
  5423. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5424. var deg = 360;
  5425. var onTransitionEnd = function () {
  5426. deg += 360;
  5427. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5428. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5429. };
  5430. imgBack.addEventListener("transitionend", onTransitionEnd);
  5431. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5432. this._loadingDiv.appendChild(imgBack);
  5433. // front image
  5434. var imgFront = new Image();
  5435. 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=";
  5436. imgFront.style.position = "absolute";
  5437. imgFront.style.left = "50%";
  5438. imgFront.style.top = "50%";
  5439. imgFront.style.marginLeft = "-50px";
  5440. imgFront.style.marginTop = "-50px";
  5441. this._loadingDiv.appendChild(imgFront);
  5442. // Resize
  5443. this._resizeLoadingUI = function () {
  5444. var canvasRect = _this.getRenderingCanvasClientRect();
  5445. _this._loadingDiv.style.position = "absolute";
  5446. _this._loadingDiv.style.left = canvasRect.left + "px";
  5447. _this._loadingDiv.style.top = canvasRect.top + "px";
  5448. _this._loadingDiv.style.width = canvasRect.width + "px";
  5449. _this._loadingDiv.style.height = canvasRect.height + "px";
  5450. };
  5451. this._resizeLoadingUI();
  5452. window.addEventListener("resize", this._resizeLoadingUI);
  5453. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5454. document.body.appendChild(this._loadingDiv);
  5455. setTimeout(function () {
  5456. _this._loadingDiv.style.opacity = "1";
  5457. imgBack.style.transform = "rotateZ(360deg)";
  5458. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5459. }, 0);
  5460. };
  5461. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5462. set: function (text) {
  5463. if (!this._loadingDiv) {
  5464. return;
  5465. }
  5466. this._loadingTextDiv.innerHTML = text;
  5467. },
  5468. enumerable: true,
  5469. configurable: true
  5470. });
  5471. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5472. get: function () {
  5473. return this._loadingDivBackgroundColor;
  5474. },
  5475. set: function (color) {
  5476. this._loadingDivBackgroundColor = color;
  5477. if (!this._loadingDiv) {
  5478. return;
  5479. }
  5480. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5481. },
  5482. enumerable: true,
  5483. configurable: true
  5484. });
  5485. Engine.prototype.hideLoadingUI = function () {
  5486. var _this = this;
  5487. if (!this._loadingDiv) {
  5488. return;
  5489. }
  5490. var onTransitionEnd = function () {
  5491. if (!_this._loadingDiv) {
  5492. return;
  5493. }
  5494. document.body.removeChild(_this._loadingDiv);
  5495. window.removeEventListener("resize", _this._resizeLoadingUI);
  5496. _this._loadingDiv = null;
  5497. };
  5498. this._loadingDiv.style.opacity = "0";
  5499. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5500. };
  5501. // FPS
  5502. Engine.prototype.getFps = function () {
  5503. return this.fps;
  5504. };
  5505. Engine.prototype.getDeltaTime = function () {
  5506. return this.deltaTime;
  5507. };
  5508. Engine.prototype._measureFps = function () {
  5509. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5510. var length = this.previousFramesDuration.length;
  5511. if (length >= 2) {
  5512. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5513. }
  5514. if (length >= this.fpsRange) {
  5515. if (length > this.fpsRange) {
  5516. this.previousFramesDuration.splice(0, 1);
  5517. length = this.previousFramesDuration.length;
  5518. }
  5519. var sum = 0;
  5520. for (var id = 0; id < length - 1; id++) {
  5521. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5522. }
  5523. this.fps = 1000.0 / (sum / (length - 1));
  5524. }
  5525. };
  5526. // Statics
  5527. Engine.isSupported = function () {
  5528. try {
  5529. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5530. if (navigator.isCocoonJS) {
  5531. return true;
  5532. }
  5533. var tempcanvas = document.createElement("canvas");
  5534. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5535. return gl != null && !!window.WebGLRenderingContext;
  5536. }
  5537. catch (e) {
  5538. return false;
  5539. }
  5540. };
  5541. // Const statics
  5542. Engine._ALPHA_DISABLE = 0;
  5543. Engine._ALPHA_ADD = 1;
  5544. Engine._ALPHA_COMBINE = 2;
  5545. Engine._DELAYLOADSTATE_NONE = 0;
  5546. Engine._DELAYLOADSTATE_LOADED = 1;
  5547. Engine._DELAYLOADSTATE_LOADING = 2;
  5548. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5549. Engine._TEXTUREFORMAT_ALPHA = 0;
  5550. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5551. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5552. Engine._TEXTUREFORMAT_RGB = 4;
  5553. Engine._TEXTUREFORMAT_RGBA = 4;
  5554. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5555. Engine._TEXTURETYPE_FLOAT = 1;
  5556. // Updatable statics so stick with vars here
  5557. Engine.Epsilon = 0.001;
  5558. Engine.CollisionsEpsilon = 0.001;
  5559. Engine.ShadersRepository = "Babylon/Shaders/";
  5560. return Engine;
  5561. })();
  5562. BABYLON.Engine = Engine;
  5563. })(BABYLON || (BABYLON = {}));
  5564. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5565. (function (BABYLON) {
  5566. /**
  5567. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5568. */
  5569. var Node = (function () {
  5570. /**
  5571. * @constructor
  5572. * @param {string} name - the name and id to be given to this node
  5573. * @param {BABYLON.Scene} the scene this node will be added to
  5574. */
  5575. function Node(name, scene) {
  5576. this.state = "";
  5577. this.animations = new Array();
  5578. this._childrenFlag = -1;
  5579. this._isEnabled = true;
  5580. this._isReady = true;
  5581. this._currentRenderId = -1;
  5582. this._parentRenderId = -1;
  5583. this.name = name;
  5584. this.id = name;
  5585. this._scene = scene;
  5586. this._initCache();
  5587. }
  5588. Node.prototype.getScene = function () {
  5589. return this._scene;
  5590. };
  5591. Node.prototype.getEngine = function () {
  5592. return this._scene.getEngine();
  5593. };
  5594. // override it in derived class
  5595. Node.prototype.getWorldMatrix = function () {
  5596. return BABYLON.Matrix.Identity();
  5597. };
  5598. // override it in derived class if you add new variables to the cache
  5599. // and call the parent class method
  5600. Node.prototype._initCache = function () {
  5601. this._cache = {};
  5602. this._cache.parent = undefined;
  5603. };
  5604. Node.prototype.updateCache = function (force) {
  5605. if (!force && this.isSynchronized())
  5606. return;
  5607. this._cache.parent = this.parent;
  5608. this._updateCache();
  5609. };
  5610. // override it in derived class if you add new variables to the cache
  5611. // and call the parent class method if !ignoreParentClass
  5612. Node.prototype._updateCache = function (ignoreParentClass) {
  5613. };
  5614. // override it in derived class if you add new variables to the cache
  5615. Node.prototype._isSynchronized = function () {
  5616. return true;
  5617. };
  5618. Node.prototype._markSyncedWithParent = function () {
  5619. this._parentRenderId = this.parent._currentRenderId;
  5620. };
  5621. Node.prototype.isSynchronizedWithParent = function () {
  5622. if (!this.parent) {
  5623. return true;
  5624. }
  5625. if (this._parentRenderId !== this.parent._currentRenderId) {
  5626. return false;
  5627. }
  5628. return this.parent.isSynchronized();
  5629. };
  5630. Node.prototype.isSynchronized = function (updateCache) {
  5631. var check = this.hasNewParent();
  5632. check = check || !this.isSynchronizedWithParent();
  5633. check = check || !this._isSynchronized();
  5634. if (updateCache)
  5635. this.updateCache(true);
  5636. return !check;
  5637. };
  5638. Node.prototype.hasNewParent = function (update) {
  5639. if (this._cache.parent === this.parent)
  5640. return false;
  5641. if (update)
  5642. this._cache.parent = this.parent;
  5643. return true;
  5644. };
  5645. /**
  5646. * Is this node ready to be used/rendered
  5647. * @return {boolean} is it ready
  5648. */
  5649. Node.prototype.isReady = function () {
  5650. return this._isReady;
  5651. };
  5652. /**
  5653. * Is this node enabled.
  5654. * If the node has a parent and is enabled, the parent will be inspected as well.
  5655. * @return {boolean} whether this node (and its parent) is enabled.
  5656. * @see setEnabled
  5657. */
  5658. Node.prototype.isEnabled = function () {
  5659. if (!this._isEnabled) {
  5660. return false;
  5661. }
  5662. if (this.parent) {
  5663. return this.parent.isEnabled();
  5664. }
  5665. return true;
  5666. };
  5667. /**
  5668. * Set the enabled state of this node.
  5669. * @param {boolean} value - the new enabled state
  5670. * @see isEnabled
  5671. */
  5672. Node.prototype.setEnabled = function (value) {
  5673. this._isEnabled = value;
  5674. };
  5675. /**
  5676. * Is this node a descendant of the given node.
  5677. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5678. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5679. * @see parent
  5680. */
  5681. Node.prototype.isDescendantOf = function (ancestor) {
  5682. if (this.parent) {
  5683. if (this.parent === ancestor) {
  5684. return true;
  5685. }
  5686. return this.parent.isDescendantOf(ancestor);
  5687. }
  5688. return false;
  5689. };
  5690. Node.prototype._getDescendants = function (list, results) {
  5691. for (var index = 0; index < list.length; index++) {
  5692. var item = list[index];
  5693. if (item.isDescendantOf(this)) {
  5694. results.push(item);
  5695. }
  5696. }
  5697. };
  5698. /**
  5699. * Will return all nodes that have this node as parent.
  5700. * @return {BABYLON.Node[]} all children nodes of all types.
  5701. */
  5702. Node.prototype.getDescendants = function () {
  5703. var results = [];
  5704. this._getDescendants(this._scene.meshes, results);
  5705. this._getDescendants(this._scene.lights, results);
  5706. this._getDescendants(this._scene.cameras, results);
  5707. return results;
  5708. };
  5709. Node.prototype._setReady = function (state) {
  5710. if (state == this._isReady) {
  5711. return;
  5712. }
  5713. if (!state) {
  5714. this._isReady = false;
  5715. return;
  5716. }
  5717. this._isReady = true;
  5718. if (this.onReady) {
  5719. this.onReady(this);
  5720. }
  5721. };
  5722. return Node;
  5723. })();
  5724. BABYLON.Node = Node;
  5725. })(BABYLON || (BABYLON = {}));
  5726. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5727. (function (BABYLON) {
  5728. var BoundingSphere = (function () {
  5729. function BoundingSphere(minimum, maximum) {
  5730. this.minimum = minimum;
  5731. this.maximum = maximum;
  5732. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5733. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5734. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5735. this.radius = distance * 0.5;
  5736. this.centerWorld = BABYLON.Vector3.Zero();
  5737. this._update(BABYLON.Matrix.Identity());
  5738. }
  5739. // Methods
  5740. BoundingSphere.prototype._update = function (world) {
  5741. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5742. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5743. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5744. };
  5745. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5746. for (var i = 0; i < 6; i++) {
  5747. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5748. return false;
  5749. }
  5750. return true;
  5751. };
  5752. BoundingSphere.prototype.intersectsPoint = function (point) {
  5753. var x = this.centerWorld.x - point.x;
  5754. var y = this.centerWorld.y - point.y;
  5755. var z = this.centerWorld.z - point.z;
  5756. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5757. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5758. return false;
  5759. return true;
  5760. };
  5761. // Statics
  5762. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5763. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5764. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5765. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5766. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5767. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5768. return false;
  5769. return true;
  5770. };
  5771. return BoundingSphere;
  5772. })();
  5773. BABYLON.BoundingSphere = BoundingSphere;
  5774. })(BABYLON || (BABYLON = {}));
  5775. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5776. (function (BABYLON) {
  5777. var BoundingBox = (function () {
  5778. function BoundingBox(minimum, maximum) {
  5779. this.minimum = minimum;
  5780. this.maximum = maximum;
  5781. this.vectors = new Array();
  5782. this.vectorsWorld = new Array();
  5783. // Bounding vectors
  5784. this.vectors.push(this.minimum.clone());
  5785. this.vectors.push(this.maximum.clone());
  5786. this.vectors.push(this.minimum.clone());
  5787. this.vectors[2].x = this.maximum.x;
  5788. this.vectors.push(this.minimum.clone());
  5789. this.vectors[3].y = this.maximum.y;
  5790. this.vectors.push(this.minimum.clone());
  5791. this.vectors[4].z = this.maximum.z;
  5792. this.vectors.push(this.maximum.clone());
  5793. this.vectors[5].z = this.minimum.z;
  5794. this.vectors.push(this.maximum.clone());
  5795. this.vectors[6].x = this.minimum.x;
  5796. this.vectors.push(this.maximum.clone());
  5797. this.vectors[7].y = this.minimum.y;
  5798. // OBB
  5799. this.center = this.maximum.add(this.minimum).scale(0.5);
  5800. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5801. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5802. for (var index = 0; index < this.vectors.length; index++) {
  5803. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5804. }
  5805. this.minimumWorld = BABYLON.Vector3.Zero();
  5806. this.maximumWorld = BABYLON.Vector3.Zero();
  5807. this._update(BABYLON.Matrix.Identity());
  5808. }
  5809. // Methods
  5810. BoundingBox.prototype.getWorldMatrix = function () {
  5811. return this._worldMatrix;
  5812. };
  5813. BoundingBox.prototype._update = function (world) {
  5814. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5815. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5816. for (var index = 0; index < this.vectors.length; index++) {
  5817. var v = this.vectorsWorld[index];
  5818. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5819. if (v.x < this.minimumWorld.x)
  5820. this.minimumWorld.x = v.x;
  5821. if (v.y < this.minimumWorld.y)
  5822. this.minimumWorld.y = v.y;
  5823. if (v.z < this.minimumWorld.z)
  5824. this.minimumWorld.z = v.z;
  5825. if (v.x > this.maximumWorld.x)
  5826. this.maximumWorld.x = v.x;
  5827. if (v.y > this.maximumWorld.y)
  5828. this.maximumWorld.y = v.y;
  5829. if (v.z > this.maximumWorld.z)
  5830. this.maximumWorld.z = v.z;
  5831. }
  5832. // OBB
  5833. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5834. this.center.scaleInPlace(0.5);
  5835. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5836. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5837. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5838. this._worldMatrix = world;
  5839. };
  5840. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5841. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5842. };
  5843. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5844. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5845. };
  5846. BoundingBox.prototype.intersectsPoint = function (point) {
  5847. var delta = BABYLON.Engine.Epsilon;
  5848. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5849. return false;
  5850. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5851. return false;
  5852. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5853. return false;
  5854. return true;
  5855. };
  5856. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5857. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5858. };
  5859. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5860. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5861. return false;
  5862. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5863. return false;
  5864. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5865. return false;
  5866. return true;
  5867. };
  5868. // Statics
  5869. BoundingBox.Intersects = function (box0, box1) {
  5870. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5871. return false;
  5872. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5873. return false;
  5874. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5875. return false;
  5876. return true;
  5877. };
  5878. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5879. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5880. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5881. return (num <= (sphereRadius * sphereRadius));
  5882. };
  5883. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5884. for (var p = 0; p < 6; p++) {
  5885. for (var i = 0; i < 8; i++) {
  5886. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5887. return false;
  5888. }
  5889. }
  5890. }
  5891. return true;
  5892. };
  5893. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5894. for (var p = 0; p < 6; p++) {
  5895. var inCount = 8;
  5896. for (var i = 0; i < 8; i++) {
  5897. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5898. --inCount;
  5899. }
  5900. else {
  5901. break;
  5902. }
  5903. }
  5904. if (inCount === 0)
  5905. return false;
  5906. }
  5907. return true;
  5908. };
  5909. return BoundingBox;
  5910. })();
  5911. BABYLON.BoundingBox = BoundingBox;
  5912. })(BABYLON || (BABYLON = {}));
  5913. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5914. (function (BABYLON) {
  5915. var computeBoxExtents = function (axis, box) {
  5916. var p = BABYLON.Vector3.Dot(box.center, axis);
  5917. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5918. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5919. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5920. var r = r0 + r1 + r2;
  5921. return {
  5922. min: p - r,
  5923. max: p + r
  5924. };
  5925. };
  5926. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5927. var axisOverlap = function (axis, box0, box1) {
  5928. var result0 = computeBoxExtents(axis, box0);
  5929. var result1 = computeBoxExtents(axis, box1);
  5930. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5931. };
  5932. var BoundingInfo = (function () {
  5933. function BoundingInfo(minimum, maximum) {
  5934. this.minimum = minimum;
  5935. this.maximum = maximum;
  5936. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5937. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5938. }
  5939. // Methods
  5940. BoundingInfo.prototype._update = function (world) {
  5941. this.boundingBox._update(world);
  5942. this.boundingSphere._update(world);
  5943. };
  5944. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5945. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5946. return false;
  5947. return this.boundingBox.isInFrustum(frustumPlanes);
  5948. };
  5949. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5950. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5951. };
  5952. BoundingInfo.prototype._checkCollision = function (collider) {
  5953. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5954. };
  5955. BoundingInfo.prototype.intersectsPoint = function (point) {
  5956. if (!this.boundingSphere.centerWorld) {
  5957. return false;
  5958. }
  5959. if (!this.boundingSphere.intersectsPoint(point)) {
  5960. return false;
  5961. }
  5962. if (!this.boundingBox.intersectsPoint(point)) {
  5963. return false;
  5964. }
  5965. return true;
  5966. };
  5967. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5968. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5969. return false;
  5970. }
  5971. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5972. return false;
  5973. }
  5974. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5975. return false;
  5976. }
  5977. if (!precise) {
  5978. return true;
  5979. }
  5980. var box0 = this.boundingBox;
  5981. var box1 = boundingInfo.boundingBox;
  5982. if (!axisOverlap(box0.directions[0], box0, box1))
  5983. return false;
  5984. if (!axisOverlap(box0.directions[1], box0, box1))
  5985. return false;
  5986. if (!axisOverlap(box0.directions[2], box0, box1))
  5987. return false;
  5988. if (!axisOverlap(box1.directions[0], box0, box1))
  5989. return false;
  5990. if (!axisOverlap(box1.directions[1], box0, box1))
  5991. return false;
  5992. if (!axisOverlap(box1.directions[2], box0, box1))
  5993. return false;
  5994. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5995. return false;
  5996. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5997. return false;
  5998. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5999. return false;
  6000. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  6001. return false;
  6002. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  6003. return false;
  6004. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  6005. return false;
  6006. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  6007. return false;
  6008. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  6009. return false;
  6010. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  6011. return false;
  6012. return true;
  6013. };
  6014. return BoundingInfo;
  6015. })();
  6016. BABYLON.BoundingInfo = BoundingInfo;
  6017. })(BABYLON || (BABYLON = {}));
  6018. //# sourceMappingURL=babylon.boundingInfo.js.map
  6019. var BABYLON;
  6020. (function (BABYLON) {
  6021. var Light = (function (_super) {
  6022. __extends(Light, _super);
  6023. function Light(name, scene) {
  6024. _super.call(this, name, scene);
  6025. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  6026. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  6027. this.intensity = 1.0;
  6028. this.range = Number.MAX_VALUE;
  6029. this.includeOnlyWithLayerMask = 0;
  6030. this.includedOnlyMeshes = new Array();
  6031. this.excludedMeshes = new Array();
  6032. this.excludeWithLayerMask = 0;
  6033. this._excludedMeshesIds = new Array();
  6034. this._includedOnlyMeshesIds = new Array();
  6035. scene.addLight(this);
  6036. }
  6037. Light.prototype.getShadowGenerator = function () {
  6038. return this._shadowGenerator;
  6039. };
  6040. Light.prototype.getAbsolutePosition = function () {
  6041. return BABYLON.Vector3.Zero();
  6042. };
  6043. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6044. };
  6045. Light.prototype._getWorldMatrix = function () {
  6046. return BABYLON.Matrix.Identity();
  6047. };
  6048. Light.prototype.canAffectMesh = function (mesh) {
  6049. if (!mesh) {
  6050. return true;
  6051. }
  6052. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6053. return false;
  6054. }
  6055. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6056. return false;
  6057. }
  6058. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  6059. return false;
  6060. }
  6061. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  6062. return false;
  6063. }
  6064. return true;
  6065. };
  6066. Light.prototype.getWorldMatrix = function () {
  6067. this._currentRenderId = this.getScene().getRenderId();
  6068. var worldMatrix = this._getWorldMatrix();
  6069. if (this.parent && this.parent.getWorldMatrix) {
  6070. if (!this._parentedWorldMatrix) {
  6071. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6072. }
  6073. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6074. this._markSyncedWithParent();
  6075. return this._parentedWorldMatrix;
  6076. }
  6077. return worldMatrix;
  6078. };
  6079. Light.prototype.dispose = function () {
  6080. if (this._shadowGenerator) {
  6081. this._shadowGenerator.dispose();
  6082. this._shadowGenerator = null;
  6083. }
  6084. // Remove from scene
  6085. this.getScene().removeLight(this);
  6086. };
  6087. return Light;
  6088. })(BABYLON.Node);
  6089. BABYLON.Light = Light;
  6090. })(BABYLON || (BABYLON = {}));
  6091. //# sourceMappingURL=babylon.light.js.map
  6092. var BABYLON;
  6093. (function (BABYLON) {
  6094. var PointLight = (function (_super) {
  6095. __extends(PointLight, _super);
  6096. function PointLight(name, position, scene) {
  6097. _super.call(this, name, scene);
  6098. this.position = position;
  6099. }
  6100. PointLight.prototype.getAbsolutePosition = function () {
  6101. return this._transformedPosition ? this._transformedPosition : this.position;
  6102. };
  6103. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6104. if (this.parent && this.parent.getWorldMatrix) {
  6105. if (!this._transformedPosition) {
  6106. this._transformedPosition = BABYLON.Vector3.Zero();
  6107. }
  6108. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6109. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6110. return;
  6111. }
  6112. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6113. };
  6114. PointLight.prototype.getShadowGenerator = function () {
  6115. return null;
  6116. };
  6117. PointLight.prototype._getWorldMatrix = function () {
  6118. if (!this._worldMatrix) {
  6119. this._worldMatrix = BABYLON.Matrix.Identity();
  6120. }
  6121. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6122. return this._worldMatrix;
  6123. };
  6124. return PointLight;
  6125. })(BABYLON.Light);
  6126. BABYLON.PointLight = PointLight;
  6127. })(BABYLON || (BABYLON = {}));
  6128. //# sourceMappingURL=babylon.pointLight.js.map
  6129. var BABYLON;
  6130. (function (BABYLON) {
  6131. var SpotLight = (function (_super) {
  6132. __extends(SpotLight, _super);
  6133. function SpotLight(name, position, direction, angle, exponent, scene) {
  6134. _super.call(this, name, scene);
  6135. this.position = position;
  6136. this.direction = direction;
  6137. this.angle = angle;
  6138. this.exponent = exponent;
  6139. }
  6140. SpotLight.prototype.getAbsolutePosition = function () {
  6141. return this.transformedPosition ? this.transformedPosition : this.position;
  6142. };
  6143. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6144. var activeCamera = this.getScene().activeCamera;
  6145. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6146. };
  6147. SpotLight.prototype.supportsVSM = function () {
  6148. return true;
  6149. };
  6150. SpotLight.prototype.needRefreshPerFrame = function () {
  6151. return false;
  6152. };
  6153. SpotLight.prototype.setDirectionToTarget = function (target) {
  6154. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6155. return this.direction;
  6156. };
  6157. SpotLight.prototype.computeTransformedPosition = function () {
  6158. if (this.parent && this.parent.getWorldMatrix) {
  6159. if (!this.transformedPosition) {
  6160. this.transformedPosition = BABYLON.Vector3.Zero();
  6161. }
  6162. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6163. return true;
  6164. }
  6165. return false;
  6166. };
  6167. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6168. var normalizeDirection;
  6169. if (this.parent && this.parent.getWorldMatrix) {
  6170. if (!this._transformedDirection) {
  6171. this._transformedDirection = BABYLON.Vector3.Zero();
  6172. }
  6173. this.computeTransformedPosition();
  6174. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6175. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6176. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6177. }
  6178. else {
  6179. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6180. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6181. }
  6182. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6183. };
  6184. SpotLight.prototype._getWorldMatrix = function () {
  6185. if (!this._worldMatrix) {
  6186. this._worldMatrix = BABYLON.Matrix.Identity();
  6187. }
  6188. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6189. return this._worldMatrix;
  6190. };
  6191. return SpotLight;
  6192. })(BABYLON.Light);
  6193. BABYLON.SpotLight = SpotLight;
  6194. })(BABYLON || (BABYLON = {}));
  6195. //# sourceMappingURL=babylon.spotLight.js.map
  6196. var BABYLON;
  6197. (function (BABYLON) {
  6198. var DirectionalLight = (function (_super) {
  6199. __extends(DirectionalLight, _super);
  6200. function DirectionalLight(name, direction, scene) {
  6201. _super.call(this, name, scene);
  6202. this.direction = direction;
  6203. this.shadowOrthoScale = 0.5;
  6204. this.position = direction.scale(-1);
  6205. }
  6206. DirectionalLight.prototype.getAbsolutePosition = function () {
  6207. return this.transformedPosition ? this.transformedPosition : this.position;
  6208. };
  6209. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6210. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6211. return this.direction;
  6212. };
  6213. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6214. var orthoLeft = Number.MAX_VALUE;
  6215. var orthoRight = Number.MIN_VALUE;
  6216. var orthoTop = Number.MIN_VALUE;
  6217. var orthoBottom = Number.MAX_VALUE;
  6218. var tempVector3 = BABYLON.Vector3.Zero();
  6219. var activeCamera = this.getScene().activeCamera;
  6220. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6221. var mesh = renderList[meshIndex];
  6222. if (!mesh) {
  6223. continue;
  6224. }
  6225. var boundingInfo = mesh.getBoundingInfo();
  6226. if (!boundingInfo) {
  6227. continue;
  6228. }
  6229. var boundingBox = boundingInfo.boundingBox;
  6230. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6231. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6232. if (tempVector3.x < orthoLeft)
  6233. orthoLeft = tempVector3.x;
  6234. if (tempVector3.y < orthoBottom)
  6235. orthoBottom = tempVector3.y;
  6236. if (tempVector3.x > orthoRight)
  6237. orthoRight = tempVector3.x;
  6238. if (tempVector3.y > orthoTop)
  6239. orthoTop = tempVector3.y;
  6240. }
  6241. }
  6242. var xOffset = orthoRight - orthoLeft;
  6243. var yOffset = orthoTop - orthoBottom;
  6244. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6245. };
  6246. DirectionalLight.prototype.supportsVSM = function () {
  6247. return true;
  6248. };
  6249. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6250. return true;
  6251. };
  6252. DirectionalLight.prototype.computeTransformedPosition = function () {
  6253. if (this.parent && this.parent.getWorldMatrix) {
  6254. if (!this.transformedPosition) {
  6255. this.transformedPosition = BABYLON.Vector3.Zero();
  6256. }
  6257. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6258. return true;
  6259. }
  6260. return false;
  6261. };
  6262. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6263. if (this.parent && this.parent.getWorldMatrix) {
  6264. if (!this._transformedDirection) {
  6265. this._transformedDirection = BABYLON.Vector3.Zero();
  6266. }
  6267. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6268. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6269. return;
  6270. }
  6271. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6272. };
  6273. DirectionalLight.prototype._getWorldMatrix = function () {
  6274. if (!this._worldMatrix) {
  6275. this._worldMatrix = BABYLON.Matrix.Identity();
  6276. }
  6277. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6278. return this._worldMatrix;
  6279. };
  6280. return DirectionalLight;
  6281. })(BABYLON.Light);
  6282. BABYLON.DirectionalLight = DirectionalLight;
  6283. })(BABYLON || (BABYLON = {}));
  6284. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6285. (function (BABYLON) {
  6286. var ShadowGenerator = (function () {
  6287. function ShadowGenerator(mapSize, light) {
  6288. var _this = this;
  6289. // Members
  6290. this._filter = ShadowGenerator.FILTER_NONE;
  6291. this.blurScale = 2;
  6292. this._blurBoxOffset = 0;
  6293. this._bias = 0.00005;
  6294. this._darkness = 0;
  6295. this._transparencyShadow = false;
  6296. this._viewMatrix = BABYLON.Matrix.Zero();
  6297. this._projectionMatrix = BABYLON.Matrix.Zero();
  6298. this._transformMatrix = BABYLON.Matrix.Zero();
  6299. this._worldViewProjection = BABYLON.Matrix.Zero();
  6300. this._light = light;
  6301. this._scene = light.getScene();
  6302. this._mapSize = mapSize;
  6303. light._shadowGenerator = this;
  6304. // Render target
  6305. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6306. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6307. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6308. this._shadowMap.anisotropicFilteringLevel = 1;
  6309. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6310. this._shadowMap.renderParticles = false;
  6311. this._shadowMap.onAfterUnbind = function () {
  6312. if (!_this.useBlurVarianceShadowMap) {
  6313. return;
  6314. }
  6315. if (!_this._shadowMap2) {
  6316. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6317. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6318. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6319. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6320. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6321. _this._downSamplePostprocess.onApply = function (effect) {
  6322. effect.setTexture("textureSampler", _this._shadowMap);
  6323. };
  6324. _this.blurBoxOffset = 1;
  6325. }
  6326. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6327. };
  6328. // Custom render function
  6329. var renderSubMesh = function (subMesh) {
  6330. var mesh = subMesh.getRenderingMesh();
  6331. var scene = _this._scene;
  6332. var engine = scene.getEngine();
  6333. // Culling
  6334. engine.setState(subMesh.getMaterial().backFaceCulling);
  6335. // Managing instances
  6336. var batch = mesh._getInstancesRenderList(subMesh._id);
  6337. if (batch.mustReturn) {
  6338. return;
  6339. }
  6340. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6341. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6342. engine.enableEffect(_this._effect);
  6343. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6344. var material = subMesh.getMaterial();
  6345. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6346. // Alpha test
  6347. if (material && material.needAlphaTesting()) {
  6348. var alphaTexture = material.getAlphaTestTexture();
  6349. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6350. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6351. }
  6352. // Bones
  6353. if (mesh.useBones) {
  6354. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6355. }
  6356. // Draw
  6357. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6358. }
  6359. else {
  6360. // Need to reset refresh rate of the shadowMap
  6361. _this._shadowMap.resetRefreshCounter();
  6362. }
  6363. };
  6364. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6365. var index;
  6366. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6367. renderSubMesh(opaqueSubMeshes.data[index]);
  6368. }
  6369. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6370. renderSubMesh(alphaTestSubMeshes.data[index]);
  6371. }
  6372. if (_this._transparencyShadow) {
  6373. for (index = 0; index < transparentSubMeshes.length; index++) {
  6374. renderSubMesh(transparentSubMeshes.data[index]);
  6375. }
  6376. }
  6377. };
  6378. this._shadowMap.onClear = function (engine) {
  6379. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6380. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6381. }
  6382. else {
  6383. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6384. }
  6385. };
  6386. }
  6387. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6388. // Static
  6389. get: function () {
  6390. return ShadowGenerator._FILTER_NONE;
  6391. },
  6392. enumerable: true,
  6393. configurable: true
  6394. });
  6395. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6396. get: function () {
  6397. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6398. },
  6399. enumerable: true,
  6400. configurable: true
  6401. });
  6402. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6403. get: function () {
  6404. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6405. },
  6406. enumerable: true,
  6407. configurable: true
  6408. });
  6409. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6410. get: function () {
  6411. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6412. },
  6413. enumerable: true,
  6414. configurable: true
  6415. });
  6416. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6417. get: function () {
  6418. return this._bias;
  6419. },
  6420. set: function (bias) {
  6421. this._bias = bias;
  6422. },
  6423. enumerable: true,
  6424. configurable: true
  6425. });
  6426. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6427. get: function () {
  6428. return this._blurBoxOffset;
  6429. },
  6430. set: function (value) {
  6431. var _this = this;
  6432. if (this._blurBoxOffset === value) {
  6433. return;
  6434. }
  6435. this._blurBoxOffset = value;
  6436. if (this._boxBlurPostprocess) {
  6437. this._boxBlurPostprocess.dispose();
  6438. }
  6439. 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);
  6440. this._boxBlurPostprocess.onApply = function (effect) {
  6441. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6442. };
  6443. },
  6444. enumerable: true,
  6445. configurable: true
  6446. });
  6447. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6448. get: function () {
  6449. return this._filter;
  6450. },
  6451. set: function (value) {
  6452. if (this._filter === value) {
  6453. return;
  6454. }
  6455. this._filter = value;
  6456. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6457. this._shadowMap.anisotropicFilteringLevel = 16;
  6458. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6459. }
  6460. else {
  6461. this._shadowMap.anisotropicFilteringLevel = 1;
  6462. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6463. }
  6464. },
  6465. enumerable: true,
  6466. configurable: true
  6467. });
  6468. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6469. get: function () {
  6470. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6471. },
  6472. set: function (value) {
  6473. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6474. },
  6475. enumerable: true,
  6476. configurable: true
  6477. });
  6478. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6479. get: function () {
  6480. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6481. },
  6482. set: function (value) {
  6483. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6484. },
  6485. enumerable: true,
  6486. configurable: true
  6487. });
  6488. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6489. get: function () {
  6490. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6491. },
  6492. set: function (value) {
  6493. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6494. },
  6495. enumerable: true,
  6496. configurable: true
  6497. });
  6498. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6499. var defines = [];
  6500. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6501. defines.push("#define VSM");
  6502. }
  6503. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6504. var mesh = subMesh.getMesh();
  6505. var material = subMesh.getMaterial();
  6506. // Alpha test
  6507. if (material && material.needAlphaTesting()) {
  6508. defines.push("#define ALPHATEST");
  6509. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6510. attribs.push(BABYLON.VertexBuffer.UVKind);
  6511. defines.push("#define UV1");
  6512. }
  6513. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6514. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6515. defines.push("#define UV2");
  6516. }
  6517. }
  6518. // Bones
  6519. if (mesh.useBones) {
  6520. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6521. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6522. defines.push("#define BONES");
  6523. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6524. }
  6525. // Instances
  6526. if (useInstances) {
  6527. defines.push("#define INSTANCES");
  6528. attribs.push("world0");
  6529. attribs.push("world1");
  6530. attribs.push("world2");
  6531. attribs.push("world3");
  6532. }
  6533. // Get correct effect
  6534. var join = defines.join("\n");
  6535. if (this._cachedDefines !== join) {
  6536. this._cachedDefines = join;
  6537. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6538. }
  6539. return this._effect.isReady();
  6540. };
  6541. ShadowGenerator.prototype.getShadowMap = function () {
  6542. return this._shadowMap;
  6543. };
  6544. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6545. if (this._shadowMap2) {
  6546. return this._shadowMap2;
  6547. }
  6548. return this._shadowMap;
  6549. };
  6550. ShadowGenerator.prototype.getLight = function () {
  6551. return this._light;
  6552. };
  6553. // Methods
  6554. ShadowGenerator.prototype.getTransformMatrix = function () {
  6555. var scene = this._scene;
  6556. if (this._currentRenderID === scene.getRenderId()) {
  6557. return this._transformMatrix;
  6558. }
  6559. this._currentRenderID = scene.getRenderId();
  6560. var lightPosition = this._light.position;
  6561. var lightDirection = this._light.direction;
  6562. if (this._light.computeTransformedPosition()) {
  6563. lightPosition = this._light.transformedPosition;
  6564. }
  6565. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6566. this._cachedPosition = lightPosition.clone();
  6567. this._cachedDirection = lightDirection.clone();
  6568. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6569. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6570. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6571. }
  6572. return this._transformMatrix;
  6573. };
  6574. ShadowGenerator.prototype.getDarkness = function () {
  6575. return this._darkness;
  6576. };
  6577. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6578. if (darkness >= 1.0)
  6579. this._darkness = 1.0;
  6580. else if (darkness <= 0.0)
  6581. this._darkness = 0.0;
  6582. else
  6583. this._darkness = darkness;
  6584. };
  6585. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6586. this._transparencyShadow = hasShadow;
  6587. };
  6588. ShadowGenerator.prototype._packHalf = function (depth) {
  6589. var scale = depth * 255.0;
  6590. var fract = scale - Math.floor(scale);
  6591. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6592. };
  6593. ShadowGenerator.prototype.dispose = function () {
  6594. this._shadowMap.dispose();
  6595. if (this._shadowMap2) {
  6596. this._shadowMap2.dispose();
  6597. }
  6598. if (this._downSamplePostprocess) {
  6599. this._downSamplePostprocess.dispose();
  6600. }
  6601. if (this._boxBlurPostprocess) {
  6602. this._boxBlurPostprocess.dispose();
  6603. }
  6604. };
  6605. ShadowGenerator._FILTER_NONE = 0;
  6606. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6607. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6608. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6609. return ShadowGenerator;
  6610. })();
  6611. BABYLON.ShadowGenerator = ShadowGenerator;
  6612. })(BABYLON || (BABYLON = {}));
  6613. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6614. var BABYLON;
  6615. (function (BABYLON) {
  6616. var HemisphericLight = (function (_super) {
  6617. __extends(HemisphericLight, _super);
  6618. function HemisphericLight(name, direction, scene) {
  6619. _super.call(this, name, scene);
  6620. this.direction = direction;
  6621. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6622. }
  6623. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6624. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6625. return this.direction;
  6626. };
  6627. HemisphericLight.prototype.getShadowGenerator = function () {
  6628. return null;
  6629. };
  6630. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6631. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6632. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6633. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6634. };
  6635. HemisphericLight.prototype._getWorldMatrix = function () {
  6636. if (!this._worldMatrix) {
  6637. this._worldMatrix = BABYLON.Matrix.Identity();
  6638. }
  6639. return this._worldMatrix;
  6640. };
  6641. return HemisphericLight;
  6642. })(BABYLON.Light);
  6643. BABYLON.HemisphericLight = HemisphericLight;
  6644. })(BABYLON || (BABYLON = {}));
  6645. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6646. (function (BABYLON) {
  6647. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6648. if (boxMin.x > sphereCenter.x + sphereRadius)
  6649. return false;
  6650. if (sphereCenter.x - sphereRadius > boxMax.x)
  6651. return false;
  6652. if (boxMin.y > sphereCenter.y + sphereRadius)
  6653. return false;
  6654. if (sphereCenter.y - sphereRadius > boxMax.y)
  6655. return false;
  6656. if (boxMin.z > sphereCenter.z + sphereRadius)
  6657. return false;
  6658. if (sphereCenter.z - sphereRadius > boxMax.z)
  6659. return false;
  6660. return true;
  6661. };
  6662. var getLowestRoot = function (a, b, c, maxR) {
  6663. var determinant = b * b - 4.0 * a * c;
  6664. var result = { root: 0, found: false };
  6665. if (determinant < 0)
  6666. return result;
  6667. var sqrtD = Math.sqrt(determinant);
  6668. var r1 = (-b - sqrtD) / (2.0 * a);
  6669. var r2 = (-b + sqrtD) / (2.0 * a);
  6670. if (r1 > r2) {
  6671. var temp = r2;
  6672. r2 = r1;
  6673. r1 = temp;
  6674. }
  6675. if (r1 > 0 && r1 < maxR) {
  6676. result.root = r1;
  6677. result.found = true;
  6678. return result;
  6679. }
  6680. if (r2 > 0 && r2 < maxR) {
  6681. result.root = r2;
  6682. result.found = true;
  6683. return result;
  6684. }
  6685. return result;
  6686. };
  6687. var Collider = (function () {
  6688. function Collider() {
  6689. this.radius = new BABYLON.Vector3(1, 1, 1);
  6690. this.retry = 0;
  6691. this.basePointWorld = BABYLON.Vector3.Zero();
  6692. this.velocityWorld = BABYLON.Vector3.Zero();
  6693. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6694. this._collisionPoint = BABYLON.Vector3.Zero();
  6695. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6696. this._tempVector = BABYLON.Vector3.Zero();
  6697. this._tempVector2 = BABYLON.Vector3.Zero();
  6698. this._tempVector3 = BABYLON.Vector3.Zero();
  6699. this._tempVector4 = BABYLON.Vector3.Zero();
  6700. this._edge = BABYLON.Vector3.Zero();
  6701. this._baseToVertex = BABYLON.Vector3.Zero();
  6702. this._destinationPoint = BABYLON.Vector3.Zero();
  6703. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6704. this._displacementVector = BABYLON.Vector3.Zero();
  6705. }
  6706. // Methods
  6707. Collider.prototype._initialize = function (source, dir, e) {
  6708. this.velocity = dir;
  6709. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6710. this.basePoint = source;
  6711. source.multiplyToRef(this.radius, this.basePointWorld);
  6712. dir.multiplyToRef(this.radius, this.velocityWorld);
  6713. this.velocityWorldLength = this.velocityWorld.length();
  6714. this.epsilon = e;
  6715. this.collisionFound = false;
  6716. };
  6717. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6718. pa.subtractToRef(point, this._tempVector);
  6719. pb.subtractToRef(point, this._tempVector2);
  6720. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6721. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6722. if (d < 0)
  6723. return false;
  6724. pc.subtractToRef(point, this._tempVector3);
  6725. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6726. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6727. if (d < 0)
  6728. return false;
  6729. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6730. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6731. return d >= 0;
  6732. };
  6733. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6734. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6735. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6736. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6737. return false;
  6738. }
  6739. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6740. return false;
  6741. return true;
  6742. };
  6743. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6744. var t0;
  6745. var embeddedInPlane = false;
  6746. if (!subMesh._trianglePlanes) {
  6747. subMesh._trianglePlanes = [];
  6748. }
  6749. if (!subMesh._trianglePlanes[faceIndex]) {
  6750. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6751. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6752. }
  6753. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6754. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6755. return;
  6756. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6757. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6758. if (normalDotVelocity == 0) {
  6759. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6760. return;
  6761. embeddedInPlane = true;
  6762. t0 = 0;
  6763. }
  6764. else {
  6765. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6766. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6767. if (t0 > t1) {
  6768. var temp = t1;
  6769. t1 = t0;
  6770. t0 = temp;
  6771. }
  6772. if (t0 > 1.0 || t1 < 0.0)
  6773. return;
  6774. if (t0 < 0)
  6775. t0 = 0;
  6776. if (t0 > 1.0)
  6777. t0 = 1.0;
  6778. }
  6779. this._collisionPoint.copyFromFloats(0, 0, 0);
  6780. var found = false;
  6781. var t = 1.0;
  6782. if (!embeddedInPlane) {
  6783. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6784. this.velocity.scaleToRef(t0, this._tempVector);
  6785. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6786. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6787. found = true;
  6788. t = t0;
  6789. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6790. }
  6791. }
  6792. if (!found) {
  6793. var velocitySquaredLength = this.velocity.lengthSquared();
  6794. var a = velocitySquaredLength;
  6795. this.basePoint.subtractToRef(p1, this._tempVector);
  6796. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6797. var c = this._tempVector.lengthSquared() - 1.0;
  6798. var lowestRoot = getLowestRoot(a, b, c, t);
  6799. if (lowestRoot.found) {
  6800. t = lowestRoot.root;
  6801. found = true;
  6802. this._collisionPoint.copyFrom(p1);
  6803. }
  6804. this.basePoint.subtractToRef(p2, this._tempVector);
  6805. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6806. c = this._tempVector.lengthSquared() - 1.0;
  6807. lowestRoot = getLowestRoot(a, b, c, t);
  6808. if (lowestRoot.found) {
  6809. t = lowestRoot.root;
  6810. found = true;
  6811. this._collisionPoint.copyFrom(p2);
  6812. }
  6813. this.basePoint.subtractToRef(p3, this._tempVector);
  6814. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6815. c = this._tempVector.lengthSquared() - 1.0;
  6816. lowestRoot = getLowestRoot(a, b, c, t);
  6817. if (lowestRoot.found) {
  6818. t = lowestRoot.root;
  6819. found = true;
  6820. this._collisionPoint.copyFrom(p3);
  6821. }
  6822. p2.subtractToRef(p1, this._edge);
  6823. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6824. var edgeSquaredLength = this._edge.lengthSquared();
  6825. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6826. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6827. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6828. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6829. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6830. lowestRoot = getLowestRoot(a, b, c, t);
  6831. if (lowestRoot.found) {
  6832. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6833. if (f >= 0.0 && f <= 1.0) {
  6834. t = lowestRoot.root;
  6835. found = true;
  6836. this._edge.scaleInPlace(f);
  6837. p1.addToRef(this._edge, this._collisionPoint);
  6838. }
  6839. }
  6840. p3.subtractToRef(p2, this._edge);
  6841. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6842. edgeSquaredLength = this._edge.lengthSquared();
  6843. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6844. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6845. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6846. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6847. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6848. lowestRoot = getLowestRoot(a, b, c, t);
  6849. if (lowestRoot.found) {
  6850. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6851. if (f >= 0.0 && f <= 1.0) {
  6852. t = lowestRoot.root;
  6853. found = true;
  6854. this._edge.scaleInPlace(f);
  6855. p2.addToRef(this._edge, this._collisionPoint);
  6856. }
  6857. }
  6858. p1.subtractToRef(p3, this._edge);
  6859. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6860. edgeSquaredLength = this._edge.lengthSquared();
  6861. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6862. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6863. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6864. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6865. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6866. lowestRoot = getLowestRoot(a, b, c, t);
  6867. if (lowestRoot.found) {
  6868. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6869. if (f >= 0.0 && f <= 1.0) {
  6870. t = lowestRoot.root;
  6871. found = true;
  6872. this._edge.scaleInPlace(f);
  6873. p3.addToRef(this._edge, this._collisionPoint);
  6874. }
  6875. }
  6876. }
  6877. if (found) {
  6878. var distToCollision = t * this.velocity.length();
  6879. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6880. if (!this.intersectionPoint) {
  6881. this.intersectionPoint = this._collisionPoint.clone();
  6882. }
  6883. else {
  6884. this.intersectionPoint.copyFrom(this._collisionPoint);
  6885. }
  6886. this.nearestDistance = distToCollision;
  6887. this.collisionFound = true;
  6888. this.collidedMesh = subMesh.getMesh();
  6889. }
  6890. }
  6891. };
  6892. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6893. for (var i = indexStart; i < indexEnd; i += 3) {
  6894. var p1 = pts[indices[i] - decal];
  6895. var p2 = pts[indices[i + 1] - decal];
  6896. var p3 = pts[indices[i + 2] - decal];
  6897. this._testTriangle(i, subMesh, p3, p2, p1);
  6898. }
  6899. };
  6900. Collider.prototype._getResponse = function (pos, vel) {
  6901. pos.addToRef(vel, this._destinationPoint);
  6902. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6903. this.basePoint.addToRef(vel, pos);
  6904. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6905. this._slidePlaneNormal.normalize();
  6906. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6907. pos.addInPlace(this._displacementVector);
  6908. this.intersectionPoint.addInPlace(this._displacementVector);
  6909. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6910. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6911. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6912. };
  6913. return Collider;
  6914. })();
  6915. BABYLON.Collider = Collider;
  6916. })(BABYLON || (BABYLON = {}));
  6917. //# sourceMappingURL=babylon.collider.js.map
  6918. var BABYLON;
  6919. (function (BABYLON) {
  6920. var Camera = (function (_super) {
  6921. __extends(Camera, _super);
  6922. function Camera(name, position, scene) {
  6923. _super.call(this, name, scene);
  6924. this.position = position;
  6925. // Members
  6926. this.upVector = BABYLON.Vector3.Up();
  6927. this.orthoLeft = null;
  6928. this.orthoRight = null;
  6929. this.orthoBottom = null;
  6930. this.orthoTop = null;
  6931. this.fov = 0.8;
  6932. this.minZ = 1.0;
  6933. this.maxZ = 10000.0;
  6934. this.inertia = 0.9;
  6935. this.mode = Camera.PERSPECTIVE_CAMERA;
  6936. this.isIntermediate = false;
  6937. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6938. this.subCameras = [];
  6939. this.layerMask = 0xFFFFFFFF;
  6940. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6941. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6942. this._projectionMatrix = new BABYLON.Matrix();
  6943. this._postProcesses = new Array();
  6944. this._postProcessesTakenIndices = [];
  6945. this._activeMeshes = new BABYLON.SmartArray(256);
  6946. this._globalPosition = BABYLON.Vector3.Zero();
  6947. scene.addCamera(this);
  6948. if (!scene.activeCamera) {
  6949. scene.activeCamera = this;
  6950. }
  6951. }
  6952. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6953. get: function () {
  6954. return Camera._PERSPECTIVE_CAMERA;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6960. get: function () {
  6961. return Camera._ORTHOGRAPHIC_CAMERA;
  6962. },
  6963. enumerable: true,
  6964. configurable: true
  6965. });
  6966. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6967. get: function () {
  6968. return Camera._FOVMODE_VERTICAL_FIXED;
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6974. get: function () {
  6975. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6976. },
  6977. enumerable: true,
  6978. configurable: true
  6979. });
  6980. Object.defineProperty(Camera.prototype, "globalPosition", {
  6981. get: function () {
  6982. return this._globalPosition;
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. Camera.prototype.getActiveMeshes = function () {
  6988. return this._activeMeshes;
  6989. };
  6990. Camera.prototype.isActiveMesh = function (mesh) {
  6991. return (this._activeMeshes.indexOf(mesh) !== -1);
  6992. };
  6993. //Cache
  6994. Camera.prototype._initCache = function () {
  6995. _super.prototype._initCache.call(this);
  6996. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6997. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6998. this._cache.mode = undefined;
  6999. this._cache.minZ = undefined;
  7000. this._cache.maxZ = undefined;
  7001. this._cache.fov = undefined;
  7002. this._cache.aspectRatio = undefined;
  7003. this._cache.orthoLeft = undefined;
  7004. this._cache.orthoRight = undefined;
  7005. this._cache.orthoBottom = undefined;
  7006. this._cache.orthoTop = undefined;
  7007. this._cache.renderWidth = undefined;
  7008. this._cache.renderHeight = undefined;
  7009. };
  7010. Camera.prototype._updateCache = function (ignoreParentClass) {
  7011. if (!ignoreParentClass) {
  7012. _super.prototype._updateCache.call(this);
  7013. }
  7014. var engine = this.getEngine();
  7015. this._cache.position.copyFrom(this.position);
  7016. this._cache.upVector.copyFrom(this.upVector);
  7017. this._cache.mode = this.mode;
  7018. this._cache.minZ = this.minZ;
  7019. this._cache.maxZ = this.maxZ;
  7020. this._cache.fov = this.fov;
  7021. this._cache.aspectRatio = engine.getAspectRatio(this);
  7022. this._cache.orthoLeft = this.orthoLeft;
  7023. this._cache.orthoRight = this.orthoRight;
  7024. this._cache.orthoBottom = this.orthoBottom;
  7025. this._cache.orthoTop = this.orthoTop;
  7026. this._cache.renderWidth = engine.getRenderWidth();
  7027. this._cache.renderHeight = engine.getRenderHeight();
  7028. };
  7029. Camera.prototype._updateFromScene = function () {
  7030. this.updateCache();
  7031. this._update();
  7032. };
  7033. // Synchronized
  7034. Camera.prototype._isSynchronized = function () {
  7035. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  7036. };
  7037. Camera.prototype._isSynchronizedViewMatrix = function () {
  7038. if (!_super.prototype._isSynchronized.call(this))
  7039. return false;
  7040. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  7041. };
  7042. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7043. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7044. if (!check) {
  7045. return false;
  7046. }
  7047. var engine = this.getEngine();
  7048. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7049. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7050. }
  7051. else {
  7052. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  7053. }
  7054. return check;
  7055. };
  7056. // Controls
  7057. Camera.prototype.attachControl = function (element) {
  7058. };
  7059. Camera.prototype.detachControl = function (element) {
  7060. };
  7061. Camera.prototype._update = function () {
  7062. };
  7063. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7064. if (insertAt === void 0) { insertAt = null; }
  7065. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7066. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7067. return 0;
  7068. }
  7069. if (insertAt == null || insertAt < 0) {
  7070. this._postProcesses.push(postProcess);
  7071. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7072. return this._postProcesses.length - 1;
  7073. }
  7074. var add = 0;
  7075. if (this._postProcesses[insertAt]) {
  7076. var start = this._postProcesses.length - 1;
  7077. for (var i = start; i >= insertAt + 1; --i) {
  7078. this._postProcesses[i + 1] = this._postProcesses[i];
  7079. }
  7080. add = 1;
  7081. }
  7082. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7083. if (this._postProcessesTakenIndices[i] < insertAt) {
  7084. continue;
  7085. }
  7086. start = this._postProcessesTakenIndices.length - 1;
  7087. for (var j = start; j >= i; --j) {
  7088. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7089. }
  7090. this._postProcessesTakenIndices[i] = insertAt;
  7091. break;
  7092. }
  7093. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7094. this._postProcessesTakenIndices.push(insertAt);
  7095. }
  7096. var result = insertAt + add;
  7097. this._postProcesses[result] = postProcess;
  7098. return result;
  7099. };
  7100. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7101. if (atIndices === void 0) { atIndices = null; }
  7102. var result = [];
  7103. if (!atIndices) {
  7104. var length = this._postProcesses.length;
  7105. for (var i = 0; i < length; i++) {
  7106. if (this._postProcesses[i] !== postProcess) {
  7107. continue;
  7108. }
  7109. delete this._postProcesses[i];
  7110. var index = this._postProcessesTakenIndices.indexOf(i);
  7111. this._postProcessesTakenIndices.splice(index, 1);
  7112. }
  7113. }
  7114. else {
  7115. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7116. for (i = 0; i < atIndices.length; i++) {
  7117. var foundPostProcess = this._postProcesses[atIndices[i]];
  7118. if (foundPostProcess !== postProcess) {
  7119. result.push(i);
  7120. continue;
  7121. }
  7122. delete this._postProcesses[atIndices[i]];
  7123. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7124. this._postProcessesTakenIndices.splice(index, 1);
  7125. }
  7126. }
  7127. return result;
  7128. };
  7129. Camera.prototype.getWorldMatrix = function () {
  7130. if (!this._worldMatrix) {
  7131. this._worldMatrix = BABYLON.Matrix.Identity();
  7132. }
  7133. var viewMatrix = this.getViewMatrix();
  7134. viewMatrix.invertToRef(this._worldMatrix);
  7135. return this._worldMatrix;
  7136. };
  7137. Camera.prototype._getViewMatrix = function () {
  7138. return BABYLON.Matrix.Identity();
  7139. };
  7140. Camera.prototype.getViewMatrix = function (force) {
  7141. this._computedViewMatrix = this._computeViewMatrix(force);
  7142. if (!force && this._isSynchronizedViewMatrix()) {
  7143. return this._computedViewMatrix;
  7144. }
  7145. if (!this.parent || !this.parent.getWorldMatrix) {
  7146. this._globalPosition.copyFrom(this.position);
  7147. }
  7148. else {
  7149. if (!this._worldMatrix) {
  7150. this._worldMatrix = BABYLON.Matrix.Identity();
  7151. }
  7152. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7153. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7154. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7155. this._computedViewMatrix.invert();
  7156. this._markSyncedWithParent();
  7157. }
  7158. this._currentRenderId = this.getScene().getRenderId();
  7159. return this._computedViewMatrix;
  7160. };
  7161. Camera.prototype._computeViewMatrix = function (force) {
  7162. if (!force && this._isSynchronizedViewMatrix()) {
  7163. return this._computedViewMatrix;
  7164. }
  7165. this._computedViewMatrix = this._getViewMatrix();
  7166. this._currentRenderId = this.getScene().getRenderId();
  7167. return this._computedViewMatrix;
  7168. };
  7169. Camera.prototype.getProjectionMatrix = function (force) {
  7170. if (!force && this._isSynchronizedProjectionMatrix()) {
  7171. return this._projectionMatrix;
  7172. }
  7173. var engine = this.getEngine();
  7174. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7175. if (this.minZ <= 0) {
  7176. this.minZ = 0.1;
  7177. }
  7178. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7179. return this._projectionMatrix;
  7180. }
  7181. var halfWidth = engine.getRenderWidth() / 2.0;
  7182. var halfHeight = engine.getRenderHeight() / 2.0;
  7183. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7184. return this._projectionMatrix;
  7185. };
  7186. Camera.prototype.dispose = function () {
  7187. // Remove from scene
  7188. this.getScene().removeCamera(this);
  7189. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7190. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7191. }
  7192. };
  7193. // Statics
  7194. Camera._PERSPECTIVE_CAMERA = 0;
  7195. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7196. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7197. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7198. return Camera;
  7199. })(BABYLON.Node);
  7200. BABYLON.Camera = Camera;
  7201. })(BABYLON || (BABYLON = {}));
  7202. //# sourceMappingURL=babylon.camera.js.map
  7203. var BABYLON;
  7204. (function (BABYLON) {
  7205. var TargetCamera = (function (_super) {
  7206. __extends(TargetCamera, _super);
  7207. function TargetCamera(name, position, scene) {
  7208. _super.call(this, name, position, scene);
  7209. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7210. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7211. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7212. this.speed = 2.0;
  7213. this.noRotationConstraint = false;
  7214. this.lockedTarget = null;
  7215. this._currentTarget = BABYLON.Vector3.Zero();
  7216. this._viewMatrix = BABYLON.Matrix.Zero();
  7217. this._camMatrix = BABYLON.Matrix.Zero();
  7218. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7219. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7220. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7221. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7222. this._lookAtTemp = BABYLON.Matrix.Zero();
  7223. this._tempMatrix = BABYLON.Matrix.Zero();
  7224. }
  7225. TargetCamera.prototype._getLockedTargetPosition = function () {
  7226. if (!this.lockedTarget) {
  7227. return null;
  7228. }
  7229. return this.lockedTarget.position || this.lockedTarget;
  7230. };
  7231. // Cache
  7232. TargetCamera.prototype._initCache = function () {
  7233. _super.prototype._initCache.call(this);
  7234. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7235. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7236. };
  7237. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7238. if (!ignoreParentClass) {
  7239. _super.prototype._updateCache.call(this);
  7240. }
  7241. var lockedTargetPosition = this._getLockedTargetPosition();
  7242. if (!lockedTargetPosition) {
  7243. this._cache.lockedTarget = null;
  7244. }
  7245. else {
  7246. if (!this._cache.lockedTarget) {
  7247. this._cache.lockedTarget = lockedTargetPosition.clone();
  7248. }
  7249. else {
  7250. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7251. }
  7252. }
  7253. this._cache.rotation.copyFrom(this.rotation);
  7254. };
  7255. // Synchronized
  7256. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7257. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7258. return false;
  7259. }
  7260. var lockedTargetPosition = this._getLockedTargetPosition();
  7261. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7262. };
  7263. // Methods
  7264. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7265. var engine = this.getEngine();
  7266. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7267. };
  7268. // Target
  7269. TargetCamera.prototype.setTarget = function (target) {
  7270. this.upVector.normalize();
  7271. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7272. this._camMatrix.invert();
  7273. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7274. var vDir = target.subtract(this.position);
  7275. if (vDir.x >= 0.0) {
  7276. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7277. }
  7278. else {
  7279. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7280. }
  7281. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7282. if (isNaN(this.rotation.x)) {
  7283. this.rotation.x = 0;
  7284. }
  7285. if (isNaN(this.rotation.y)) {
  7286. this.rotation.y = 0;
  7287. }
  7288. if (isNaN(this.rotation.z)) {
  7289. this.rotation.z = 0;
  7290. }
  7291. };
  7292. TargetCamera.prototype.getTarget = function () {
  7293. return this._currentTarget;
  7294. };
  7295. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7296. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7297. };
  7298. TargetCamera.prototype._updatePosition = function () {
  7299. this.position.addInPlace(this.cameraDirection);
  7300. };
  7301. TargetCamera.prototype._update = function () {
  7302. var needToMove = this._decideIfNeedsToMove();
  7303. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7304. // Move
  7305. if (needToMove) {
  7306. this._updatePosition();
  7307. }
  7308. // Rotate
  7309. if (needToRotate) {
  7310. this.rotation.x += this.cameraRotation.x;
  7311. this.rotation.y += this.cameraRotation.y;
  7312. if (!this.noRotationConstraint) {
  7313. var limit = (Math.PI / 2) * 0.95;
  7314. if (this.rotation.x > limit)
  7315. this.rotation.x = limit;
  7316. if (this.rotation.x < -limit)
  7317. this.rotation.x = -limit;
  7318. }
  7319. }
  7320. // Inertia
  7321. if (needToMove) {
  7322. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7323. this.cameraDirection.x = 0;
  7324. }
  7325. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7326. this.cameraDirection.y = 0;
  7327. }
  7328. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7329. this.cameraDirection.z = 0;
  7330. }
  7331. this.cameraDirection.scaleInPlace(this.inertia);
  7332. }
  7333. if (needToRotate) {
  7334. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7335. this.cameraRotation.x = 0;
  7336. }
  7337. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7338. this.cameraRotation.y = 0;
  7339. }
  7340. this.cameraRotation.scaleInPlace(this.inertia);
  7341. }
  7342. };
  7343. TargetCamera.prototype._getViewMatrix = function () {
  7344. if (!this.lockedTarget) {
  7345. // Compute
  7346. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7347. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7348. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7349. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7350. this._lookAtTemp.invert();
  7351. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7352. }
  7353. else {
  7354. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7355. }
  7356. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7357. // Computing target and final matrix
  7358. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7359. }
  7360. else {
  7361. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7362. }
  7363. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7364. return this._viewMatrix;
  7365. };
  7366. return TargetCamera;
  7367. })(BABYLON.Camera);
  7368. BABYLON.TargetCamera = TargetCamera;
  7369. })(BABYLON || (BABYLON = {}));
  7370. //# sourceMappingURL=babylon.targetCamera.js.map
  7371. var BABYLON;
  7372. (function (BABYLON) {
  7373. var FollowCamera = (function (_super) {
  7374. __extends(FollowCamera, _super);
  7375. function FollowCamera(name, position, scene) {
  7376. _super.call(this, name, position, scene);
  7377. this.radius = 12;
  7378. this.rotationOffset = 0;
  7379. this.heightOffset = 4;
  7380. this.cameraAcceleration = 0.05;
  7381. this.maxCameraSpeed = 20;
  7382. }
  7383. FollowCamera.prototype.getRadians = function (degrees) {
  7384. return degrees * Math.PI / 180;
  7385. };
  7386. FollowCamera.prototype.follow = function (cameraTarget) {
  7387. if (!cameraTarget)
  7388. return;
  7389. var yRotation;
  7390. if (cameraTarget.rotationQuaternion) {
  7391. var rotMatrix = new BABYLON.Matrix();
  7392. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  7393. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  7394. }
  7395. else {
  7396. yRotation = cameraTarget.rotation.y;
  7397. }
  7398. var radians = this.getRadians(this.rotationOffset) + yRotation;
  7399. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7400. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7401. var dx = targetX - this.position.x;
  7402. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7403. var dz = (targetZ) - this.position.z;
  7404. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7405. var vy = dy * this.cameraAcceleration;
  7406. var vz = dz * this.cameraAcceleration * 2;
  7407. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7408. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7409. }
  7410. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7411. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7412. }
  7413. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7414. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7415. }
  7416. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7417. this.setTarget(cameraTarget.position);
  7418. };
  7419. FollowCamera.prototype._update = function () {
  7420. _super.prototype._update.call(this);
  7421. this.follow(this.target);
  7422. };
  7423. return FollowCamera;
  7424. })(BABYLON.TargetCamera);
  7425. BABYLON.FollowCamera = FollowCamera;
  7426. })(BABYLON || (BABYLON = {}));
  7427. //# sourceMappingURL=babylon.followCamera.js.map
  7428. var BABYLON;
  7429. (function (BABYLON) {
  7430. var FreeCamera = (function (_super) {
  7431. __extends(FreeCamera, _super);
  7432. function FreeCamera(name, position, scene) {
  7433. _super.call(this, name, position, scene);
  7434. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7435. this.keysUp = [38];
  7436. this.keysDown = [40];
  7437. this.keysLeft = [37];
  7438. this.keysRight = [39];
  7439. this.checkCollisions = false;
  7440. this.applyGravity = false;
  7441. this.angularSensibility = 2000.0;
  7442. this._keys = [];
  7443. this._collider = new BABYLON.Collider();
  7444. this._needMoveForGravity = true;
  7445. this._oldPosition = BABYLON.Vector3.Zero();
  7446. this._diffPosition = BABYLON.Vector3.Zero();
  7447. this._newPosition = BABYLON.Vector3.Zero();
  7448. }
  7449. // Controls
  7450. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7451. var _this = this;
  7452. var previousPosition;
  7453. var engine = this.getEngine();
  7454. if (this._attachedElement) {
  7455. return;
  7456. }
  7457. this._attachedElement = element;
  7458. if (this._onMouseDown === undefined) {
  7459. this._onMouseDown = function (evt) {
  7460. previousPosition = {
  7461. x: evt.clientX,
  7462. y: evt.clientY
  7463. };
  7464. if (!noPreventDefault) {
  7465. evt.preventDefault();
  7466. }
  7467. };
  7468. this._onMouseUp = function (evt) {
  7469. previousPosition = null;
  7470. if (!noPreventDefault) {
  7471. evt.preventDefault();
  7472. }
  7473. };
  7474. this._onMouseOut = function (evt) {
  7475. previousPosition = null;
  7476. _this._keys = [];
  7477. if (!noPreventDefault) {
  7478. evt.preventDefault();
  7479. }
  7480. };
  7481. this._onMouseMove = function (evt) {
  7482. if (!previousPosition && !engine.isPointerLock) {
  7483. return;
  7484. }
  7485. var offsetX;
  7486. var offsetY;
  7487. if (!engine.isPointerLock) {
  7488. offsetX = evt.clientX - previousPosition.x;
  7489. offsetY = evt.clientY - previousPosition.y;
  7490. }
  7491. else {
  7492. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7493. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7494. }
  7495. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7496. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7497. previousPosition = {
  7498. x: evt.clientX,
  7499. y: evt.clientY
  7500. };
  7501. if (!noPreventDefault) {
  7502. evt.preventDefault();
  7503. }
  7504. };
  7505. this._onKeyDown = function (evt) {
  7506. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7507. var index = _this._keys.indexOf(evt.keyCode);
  7508. if (index === -1) {
  7509. _this._keys.push(evt.keyCode);
  7510. }
  7511. if (!noPreventDefault) {
  7512. evt.preventDefault();
  7513. }
  7514. }
  7515. };
  7516. this._onKeyUp = function (evt) {
  7517. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7518. var index = _this._keys.indexOf(evt.keyCode);
  7519. if (index >= 0) {
  7520. _this._keys.splice(index, 1);
  7521. }
  7522. if (!noPreventDefault) {
  7523. evt.preventDefault();
  7524. }
  7525. }
  7526. };
  7527. this._onLostFocus = function () {
  7528. _this._keys = [];
  7529. };
  7530. this._reset = function () {
  7531. _this._keys = [];
  7532. previousPosition = null;
  7533. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7534. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7535. };
  7536. }
  7537. element.addEventListener("mousedown", this._onMouseDown, false);
  7538. element.addEventListener("mouseup", this._onMouseUp, false);
  7539. element.addEventListener("mouseout", this._onMouseOut, false);
  7540. element.addEventListener("mousemove", this._onMouseMove, false);
  7541. BABYLON.Tools.RegisterTopRootEvents([
  7542. { name: "keydown", handler: this._onKeyDown },
  7543. { name: "keyup", handler: this._onKeyUp },
  7544. { name: "blur", handler: this._onLostFocus }
  7545. ]);
  7546. };
  7547. FreeCamera.prototype.detachControl = function (element) {
  7548. if (this._attachedElement != element) {
  7549. return;
  7550. }
  7551. element.removeEventListener("mousedown", this._onMouseDown);
  7552. element.removeEventListener("mouseup", this._onMouseUp);
  7553. element.removeEventListener("mouseout", this._onMouseOut);
  7554. element.removeEventListener("mousemove", this._onMouseMove);
  7555. BABYLON.Tools.UnregisterTopRootEvents([
  7556. { name: "keydown", handler: this._onKeyDown },
  7557. { name: "keyup", handler: this._onKeyUp },
  7558. { name: "blur", handler: this._onLostFocus }
  7559. ]);
  7560. this._attachedElement = null;
  7561. if (this._reset) {
  7562. this._reset();
  7563. }
  7564. };
  7565. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7566. var globalPosition;
  7567. if (this.parent) {
  7568. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7569. }
  7570. else {
  7571. globalPosition = this.position;
  7572. }
  7573. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7574. this._collider.radius = this.ellipsoid;
  7575. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7576. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7577. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7578. this.position.addInPlace(this._diffPosition);
  7579. if (this.onCollide) {
  7580. this.onCollide(this._collider.collidedMesh);
  7581. }
  7582. }
  7583. };
  7584. FreeCamera.prototype._checkInputs = function () {
  7585. if (!this._localDirection) {
  7586. this._localDirection = BABYLON.Vector3.Zero();
  7587. this._transformedDirection = BABYLON.Vector3.Zero();
  7588. }
  7589. for (var index = 0; index < this._keys.length; index++) {
  7590. var keyCode = this._keys[index];
  7591. var speed = this._computeLocalCameraSpeed();
  7592. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7593. this._localDirection.copyFromFloats(-speed, 0, 0);
  7594. }
  7595. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7596. this._localDirection.copyFromFloats(0, 0, speed);
  7597. }
  7598. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7599. this._localDirection.copyFromFloats(speed, 0, 0);
  7600. }
  7601. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7602. this._localDirection.copyFromFloats(0, 0, -speed);
  7603. }
  7604. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7605. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7606. this.cameraDirection.addInPlace(this._transformedDirection);
  7607. }
  7608. };
  7609. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7610. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7611. };
  7612. FreeCamera.prototype._updatePosition = function () {
  7613. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7614. this._collideWithWorld(this.cameraDirection);
  7615. if (this.applyGravity) {
  7616. var oldPosition = this.position;
  7617. this._collideWithWorld(this.getScene().gravity);
  7618. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7619. }
  7620. }
  7621. else {
  7622. this.position.addInPlace(this.cameraDirection);
  7623. }
  7624. };
  7625. FreeCamera.prototype._update = function () {
  7626. this._checkInputs();
  7627. _super.prototype._update.call(this);
  7628. };
  7629. return FreeCamera;
  7630. })(BABYLON.TargetCamera);
  7631. BABYLON.FreeCamera = FreeCamera;
  7632. })(BABYLON || (BABYLON = {}));
  7633. //# sourceMappingURL=babylon.freeCamera.js.map
  7634. var BABYLON;
  7635. (function (BABYLON) {
  7636. // We're mainly based on the logic defined into the FreeCamera code
  7637. var TouchCamera = (function (_super) {
  7638. __extends(TouchCamera, _super);
  7639. function TouchCamera(name, position, scene) {
  7640. _super.call(this, name, position, scene);
  7641. this._offsetX = null;
  7642. this._offsetY = null;
  7643. this._pointerCount = 0;
  7644. this._pointerPressed = [];
  7645. this.angularSensibility = 200000.0;
  7646. this.moveSensibility = 500.0;
  7647. }
  7648. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7649. var _this = this;
  7650. var previousPosition;
  7651. if (this._attachedCanvas) {
  7652. return;
  7653. }
  7654. this._attachedCanvas = canvas;
  7655. if (this._onPointerDown === undefined) {
  7656. this._onPointerDown = function (evt) {
  7657. if (!noPreventDefault) {
  7658. evt.preventDefault();
  7659. }
  7660. _this._pointerPressed.push(evt.pointerId);
  7661. if (_this._pointerPressed.length !== 1) {
  7662. return;
  7663. }
  7664. previousPosition = {
  7665. x: evt.clientX,
  7666. y: evt.clientY
  7667. };
  7668. };
  7669. this._onPointerUp = function (evt) {
  7670. if (!noPreventDefault) {
  7671. evt.preventDefault();
  7672. }
  7673. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7674. if (index === -1) {
  7675. return;
  7676. }
  7677. _this._pointerPressed.splice(index, 1);
  7678. if (index != 0) {
  7679. return;
  7680. }
  7681. previousPosition = null;
  7682. _this._offsetX = null;
  7683. _this._offsetY = null;
  7684. };
  7685. this._onPointerMove = function (evt) {
  7686. if (!noPreventDefault) {
  7687. evt.preventDefault();
  7688. }
  7689. if (!previousPosition) {
  7690. return;
  7691. }
  7692. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7693. if (index != 0) {
  7694. return;
  7695. }
  7696. _this._offsetX = evt.clientX - previousPosition.x;
  7697. _this._offsetY = -(evt.clientY - previousPosition.y);
  7698. };
  7699. this._onLostFocus = function () {
  7700. _this._offsetX = null;
  7701. _this._offsetY = null;
  7702. };
  7703. }
  7704. canvas.addEventListener("pointerdown", this._onPointerDown);
  7705. canvas.addEventListener("pointerup", this._onPointerUp);
  7706. canvas.addEventListener("pointerout", this._onPointerUp);
  7707. canvas.addEventListener("pointermove", this._onPointerMove);
  7708. BABYLON.Tools.RegisterTopRootEvents([
  7709. { name: "blur", handler: this._onLostFocus }
  7710. ]);
  7711. };
  7712. TouchCamera.prototype.detachControl = function (canvas) {
  7713. if (this._attachedCanvas != canvas) {
  7714. return;
  7715. }
  7716. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7717. canvas.removeEventListener("pointerup", this._onPointerUp);
  7718. canvas.removeEventListener("pointerout", this._onPointerUp);
  7719. canvas.removeEventListener("pointermove", this._onPointerMove);
  7720. BABYLON.Tools.UnregisterTopRootEvents([
  7721. { name: "blur", handler: this._onLostFocus }
  7722. ]);
  7723. this._attachedCanvas = null;
  7724. };
  7725. TouchCamera.prototype._checkInputs = function () {
  7726. if (!this._offsetX) {
  7727. return;
  7728. }
  7729. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7730. if (this._pointerPressed.length > 1) {
  7731. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7732. }
  7733. else {
  7734. var speed = this._computeLocalCameraSpeed();
  7735. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7736. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7737. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7738. }
  7739. };
  7740. return TouchCamera;
  7741. })(BABYLON.FreeCamera);
  7742. BABYLON.TouchCamera = TouchCamera;
  7743. })(BABYLON || (BABYLON = {}));
  7744. //# sourceMappingURL=babylon.touchCamera.js.map
  7745. var BABYLON;
  7746. (function (BABYLON) {
  7747. // We're mainly based on the logic defined into the FreeCamera code
  7748. var DeviceOrientationCamera = (function (_super) {
  7749. __extends(DeviceOrientationCamera, _super);
  7750. function DeviceOrientationCamera(name, position, scene) {
  7751. var _this = this;
  7752. _super.call(this, name, position, scene);
  7753. this._offsetX = null;
  7754. this._offsetY = null;
  7755. this._orientationGamma = 0;
  7756. this._orientationBeta = 0;
  7757. this._initialOrientationGamma = 0;
  7758. this._initialOrientationBeta = 0;
  7759. this.angularSensibility = 10000.0;
  7760. this.moveSensibility = 50.0;
  7761. window.addEventListener("resize", function () {
  7762. _this._initialOrientationGamma = null;
  7763. }, false);
  7764. }
  7765. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7766. var _this = this;
  7767. if (this._attachedCanvas) {
  7768. return;
  7769. }
  7770. this._attachedCanvas = canvas;
  7771. if (!this._orientationChanged) {
  7772. this._orientationChanged = function (evt) {
  7773. if (!_this._initialOrientationGamma) {
  7774. _this._initialOrientationGamma = evt.gamma;
  7775. _this._initialOrientationBeta = evt.beta;
  7776. }
  7777. _this._orientationGamma = evt.gamma;
  7778. _this._orientationBeta = evt.beta;
  7779. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7780. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7781. };
  7782. }
  7783. window.addEventListener("deviceorientation", this._orientationChanged);
  7784. };
  7785. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7786. if (this._attachedCanvas != canvas) {
  7787. return;
  7788. }
  7789. window.removeEventListener("deviceorientation", this._orientationChanged);
  7790. this._attachedCanvas = null;
  7791. this._orientationGamma = 0;
  7792. this._orientationBeta = 0;
  7793. this._initialOrientationGamma = 0;
  7794. this._initialOrientationBeta = 0;
  7795. };
  7796. DeviceOrientationCamera.prototype._checkInputs = function () {
  7797. if (!this._offsetX) {
  7798. return;
  7799. }
  7800. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7801. var speed = this._computeLocalCameraSpeed();
  7802. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7803. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7804. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7805. };
  7806. return DeviceOrientationCamera;
  7807. })(BABYLON.FreeCamera);
  7808. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7809. })(BABYLON || (BABYLON = {}));
  7810. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7811. var BABYLON;
  7812. (function (BABYLON) {
  7813. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7814. var ArcRotateCamera = (function (_super) {
  7815. __extends(ArcRotateCamera, _super);
  7816. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7817. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7818. this.alpha = alpha;
  7819. this.beta = beta;
  7820. this.radius = radius;
  7821. this.target = target;
  7822. this.inertialAlphaOffset = 0;
  7823. this.inertialBetaOffset = 0;
  7824. this.inertialRadiusOffset = 0;
  7825. this.lowerAlphaLimit = null;
  7826. this.upperAlphaLimit = null;
  7827. this.lowerBetaLimit = 0.01;
  7828. this.upperBetaLimit = Math.PI;
  7829. this.lowerRadiusLimit = null;
  7830. this.upperRadiusLimit = null;
  7831. this.angularSensibility = 1000.0;
  7832. this.wheelPrecision = 3.0;
  7833. this.pinchPrecision = 2.0;
  7834. this.keysUp = [38];
  7835. this.keysDown = [40];
  7836. this.keysLeft = [37];
  7837. this.keysRight = [39];
  7838. this.zoomOnFactor = 1;
  7839. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7840. this._keys = [];
  7841. this._viewMatrix = new BABYLON.Matrix();
  7842. this.checkCollisions = false;
  7843. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7844. this._collider = new BABYLON.Collider();
  7845. this._previousPosition = BABYLON.Vector3.Zero();
  7846. this._collisionVelocity = BABYLON.Vector3.Zero();
  7847. this._newPosition = BABYLON.Vector3.Zero();
  7848. if (!this.target) {
  7849. this.target = BABYLON.Vector3.Zero();
  7850. }
  7851. this.getViewMatrix();
  7852. }
  7853. ArcRotateCamera.prototype._getTargetPosition = function () {
  7854. return this.target.position || this.target;
  7855. };
  7856. // Cache
  7857. ArcRotateCamera.prototype._initCache = function () {
  7858. _super.prototype._initCache.call(this);
  7859. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7860. this._cache.alpha = undefined;
  7861. this._cache.beta = undefined;
  7862. this._cache.radius = undefined;
  7863. this._cache.targetScreenOffset = undefined;
  7864. };
  7865. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7866. if (!ignoreParentClass) {
  7867. _super.prototype._updateCache.call(this);
  7868. }
  7869. this._cache.target.copyFrom(this._getTargetPosition());
  7870. this._cache.alpha = this.alpha;
  7871. this._cache.beta = this.beta;
  7872. this._cache.radius = this.radius;
  7873. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7874. };
  7875. // Synchronized
  7876. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7877. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7878. return false;
  7879. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  7880. };
  7881. // Methods
  7882. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7883. var _this = this;
  7884. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7885. var previousPinchDistance = 0;
  7886. var pointers = new BABYLON.SmartCollection();
  7887. if (this._attachedElement) {
  7888. return;
  7889. }
  7890. this._attachedElement = element;
  7891. var engine = this.getEngine();
  7892. if (this._onPointerDown === undefined) {
  7893. this._onPointerDown = function (evt) {
  7894. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7895. cacheSoloPointer = pointers.item(evt.pointerId);
  7896. if (!noPreventDefault) {
  7897. evt.preventDefault();
  7898. }
  7899. };
  7900. this._onPointerUp = function (evt) {
  7901. cacheSoloPointer = null;
  7902. previousPinchDistance = 0;
  7903. pointers.remove(evt.pointerId);
  7904. if (!noPreventDefault) {
  7905. evt.preventDefault();
  7906. }
  7907. };
  7908. this._onPointerMove = function (evt) {
  7909. if (!noPreventDefault) {
  7910. evt.preventDefault();
  7911. }
  7912. switch (pointers.count) {
  7913. case 1:
  7914. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7915. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7916. var offsetX = evt.clientX - cacheSoloPointer.x;
  7917. var offsetY = evt.clientY - cacheSoloPointer.y;
  7918. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7919. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7920. //pointers.item(evt.pointerId).x = evt.clientX;
  7921. //pointers.item(evt.pointerId).y = evt.clientY;
  7922. cacheSoloPointer.x = evt.clientX;
  7923. cacheSoloPointer.y = evt.clientY;
  7924. break;
  7925. case 2:
  7926. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7927. pointers.item(evt.pointerId).x = evt.clientX;
  7928. pointers.item(evt.pointerId).y = evt.clientY;
  7929. var direction = 1;
  7930. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7931. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7932. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7933. if (previousPinchDistance === 0) {
  7934. previousPinchDistance = pinchSquaredDistance;
  7935. return;
  7936. }
  7937. if (pinchSquaredDistance !== previousPinchDistance) {
  7938. if (pinchSquaredDistance > previousPinchDistance) {
  7939. direction = -1;
  7940. }
  7941. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7942. previousPinchDistance = pinchSquaredDistance;
  7943. }
  7944. break;
  7945. default:
  7946. if (pointers.item(evt.pointerId)) {
  7947. pointers.item(evt.pointerId).x = evt.clientX;
  7948. pointers.item(evt.pointerId).y = evt.clientY;
  7949. }
  7950. }
  7951. };
  7952. this._onMouseMove = function (evt) {
  7953. if (!engine.isPointerLock) {
  7954. return;
  7955. }
  7956. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7957. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7958. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7959. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7960. if (!noPreventDefault) {
  7961. evt.preventDefault();
  7962. }
  7963. };
  7964. this._wheel = function (event) {
  7965. var delta = 0;
  7966. if (event.wheelDelta) {
  7967. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7968. }
  7969. else if (event.detail) {
  7970. delta = -event.detail / _this.wheelPrecision;
  7971. }
  7972. if (delta)
  7973. _this.inertialRadiusOffset += delta;
  7974. if (event.preventDefault) {
  7975. if (!noPreventDefault) {
  7976. event.preventDefault();
  7977. }
  7978. }
  7979. };
  7980. this._onKeyDown = function (evt) {
  7981. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7982. var index = _this._keys.indexOf(evt.keyCode);
  7983. if (index === -1) {
  7984. _this._keys.push(evt.keyCode);
  7985. }
  7986. if (evt.preventDefault) {
  7987. if (!noPreventDefault) {
  7988. evt.preventDefault();
  7989. }
  7990. }
  7991. }
  7992. };
  7993. this._onKeyUp = function (evt) {
  7994. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7995. var index = _this._keys.indexOf(evt.keyCode);
  7996. if (index >= 0) {
  7997. _this._keys.splice(index, 1);
  7998. }
  7999. if (evt.preventDefault) {
  8000. if (!noPreventDefault) {
  8001. evt.preventDefault();
  8002. }
  8003. }
  8004. }
  8005. };
  8006. this._onLostFocus = function () {
  8007. _this._keys = [];
  8008. pointers.empty();
  8009. previousPinchDistance = 0;
  8010. cacheSoloPointer = null;
  8011. };
  8012. this._onGestureStart = function (e) {
  8013. if (window.MSGesture === undefined) {
  8014. return;
  8015. }
  8016. if (!_this._MSGestureHandler) {
  8017. _this._MSGestureHandler = new MSGesture();
  8018. _this._MSGestureHandler.target = element;
  8019. }
  8020. _this._MSGestureHandler.addPointer(e.pointerId);
  8021. };
  8022. this._onGesture = function (e) {
  8023. _this.radius *= e.scale;
  8024. if (e.preventDefault) {
  8025. if (!noPreventDefault) {
  8026. e.stopPropagation();
  8027. e.preventDefault();
  8028. }
  8029. }
  8030. };
  8031. this._reset = function () {
  8032. _this._keys = [];
  8033. _this.inertialAlphaOffset = 0;
  8034. _this.inertialBetaOffset = 0;
  8035. _this.inertialRadiusOffset = 0;
  8036. pointers.empty();
  8037. previousPinchDistance = 0;
  8038. cacheSoloPointer = null;
  8039. };
  8040. }
  8041. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8042. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8043. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  8044. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8045. element.addEventListener("mousemove", this._onMouseMove, false);
  8046. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  8047. element.addEventListener("MSGestureChange", this._onGesture, false);
  8048. element.addEventListener('mousewheel', this._wheel, false);
  8049. element.addEventListener('DOMMouseScroll', this._wheel, false);
  8050. BABYLON.Tools.RegisterTopRootEvents([
  8051. { name: "keydown", handler: this._onKeyDown },
  8052. { name: "keyup", handler: this._onKeyUp },
  8053. { name: "blur", handler: this._onLostFocus }
  8054. ]);
  8055. };
  8056. ArcRotateCamera.prototype.detachControl = function (element) {
  8057. if (this._attachedElement !== element) {
  8058. return;
  8059. }
  8060. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8061. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8062. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8063. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8064. element.removeEventListener("mousemove", this._onMouseMove);
  8065. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8066. element.removeEventListener("MSGestureChange", this._onGesture);
  8067. element.removeEventListener('mousewheel', this._wheel);
  8068. element.removeEventListener('DOMMouseScroll', this._wheel);
  8069. BABYLON.Tools.UnregisterTopRootEvents([
  8070. { name: "keydown", handler: this._onKeyDown },
  8071. { name: "keyup", handler: this._onKeyUp },
  8072. { name: "blur", handler: this._onLostFocus }
  8073. ]);
  8074. this._MSGestureHandler = null;
  8075. this._attachedElement = null;
  8076. if (this._reset) {
  8077. this._reset();
  8078. }
  8079. };
  8080. ArcRotateCamera.prototype._update = function () {
  8081. for (var index = 0; index < this._keys.length; index++) {
  8082. var keyCode = this._keys[index];
  8083. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8084. this.inertialAlphaOffset -= 0.01;
  8085. }
  8086. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8087. this.inertialBetaOffset -= 0.01;
  8088. }
  8089. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8090. this.inertialAlphaOffset += 0.01;
  8091. }
  8092. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8093. this.inertialBetaOffset += 0.01;
  8094. }
  8095. }
  8096. // Inertia
  8097. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8098. this.alpha += this.inertialAlphaOffset;
  8099. this.beta += this.inertialBetaOffset;
  8100. this.radius -= this.inertialRadiusOffset;
  8101. this.inertialAlphaOffset *= this.inertia;
  8102. this.inertialBetaOffset *= this.inertia;
  8103. this.inertialRadiusOffset *= this.inertia;
  8104. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8105. this.inertialAlphaOffset = 0;
  8106. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8107. this.inertialBetaOffset = 0;
  8108. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8109. this.inertialRadiusOffset = 0;
  8110. }
  8111. // Limits
  8112. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8113. this.alpha = this.lowerAlphaLimit;
  8114. }
  8115. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8116. this.alpha = this.upperAlphaLimit;
  8117. }
  8118. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8119. this.beta = this.lowerBetaLimit;
  8120. }
  8121. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8122. this.beta = this.upperBetaLimit;
  8123. }
  8124. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8125. this.radius = this.lowerRadiusLimit;
  8126. }
  8127. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8128. this.radius = this.upperRadiusLimit;
  8129. }
  8130. };
  8131. ArcRotateCamera.prototype.setPosition = function (position) {
  8132. var radiusv3 = position.subtract(this._getTargetPosition());
  8133. this.radius = radiusv3.length();
  8134. // Alpha
  8135. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8136. if (radiusv3.z < 0) {
  8137. this.alpha = 2 * Math.PI - this.alpha;
  8138. }
  8139. // Beta
  8140. this.beta = Math.acos(radiusv3.y / this.radius);
  8141. };
  8142. ArcRotateCamera.prototype._getViewMatrix = function () {
  8143. // Compute
  8144. var cosa = Math.cos(this.alpha);
  8145. var sina = Math.sin(this.alpha);
  8146. var cosb = Math.cos(this.beta);
  8147. var sinb = Math.sin(this.beta);
  8148. var target = this._getTargetPosition();
  8149. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8150. if (this.checkCollisions) {
  8151. this._collider.radius = this.collisionRadius;
  8152. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8153. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8154. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8155. this.position.copyFrom(this._previousPosition);
  8156. this.alpha = this._previousAlpha;
  8157. this.beta = this._previousBeta;
  8158. this.radius = this._previousRadius;
  8159. if (this.onCollide) {
  8160. this.onCollide(this._collider.collidedMesh);
  8161. }
  8162. }
  8163. }
  8164. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8165. this._previousAlpha = this.alpha;
  8166. this._previousBeta = this.beta;
  8167. this._previousRadius = this.radius;
  8168. this._previousPosition.copyFrom(this.position);
  8169. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8170. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8171. return this._viewMatrix;
  8172. };
  8173. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8174. meshes = meshes || this.getScene().meshes;
  8175. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8176. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8177. this.radius = distance * this.zoomOnFactor;
  8178. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8179. };
  8180. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8181. var meshesOrMinMaxVector;
  8182. var distance;
  8183. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8184. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8185. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8186. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8187. }
  8188. else {
  8189. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8190. distance = meshesOrMinMaxVectorAndDistance.distance;
  8191. }
  8192. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8193. this.maxZ = distance * 2;
  8194. };
  8195. return ArcRotateCamera;
  8196. })(BABYLON.Camera);
  8197. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8198. })(BABYLON || (BABYLON = {}));
  8199. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8200. (function (BABYLON) {
  8201. /**
  8202. * Represents a scene to be rendered by the engine.
  8203. * @see http://doc.babylonjs.com/page.php?p=21911
  8204. */
  8205. var Scene = (function () {
  8206. /**
  8207. * @constructor
  8208. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8209. */
  8210. function Scene(engine) {
  8211. // Members
  8212. this.autoClear = true;
  8213. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8214. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8215. this.forceWireframe = false;
  8216. this.forcePointsCloud = false;
  8217. this.forceShowBoundingBoxes = false;
  8218. this.animationsEnabled = true;
  8219. 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
  8220. // Fog
  8221. /**
  8222. * is fog enabled on this scene.
  8223. * @type {boolean}
  8224. */
  8225. this.fogEnabled = true;
  8226. this.fogMode = Scene.FOGMODE_NONE;
  8227. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8228. this.fogDensity = 0.1;
  8229. this.fogStart = 0;
  8230. this.fogEnd = 1000.0;
  8231. // Lights
  8232. /**
  8233. * is shadow enabled on this scene.
  8234. * @type {boolean}
  8235. */
  8236. this.shadowsEnabled = true;
  8237. /**
  8238. * is light enabled on this scene.
  8239. * @type {boolean}
  8240. */
  8241. this.lightsEnabled = true;
  8242. /**
  8243. * All of the lights added to this scene.
  8244. * @see BABYLON.Light
  8245. * @type {BABYLON.Light[]}
  8246. */
  8247. this.lights = new Array();
  8248. // Cameras
  8249. /**
  8250. * All of the cameras added to this scene.
  8251. * @see BABYLON.Camera
  8252. * @type {BABYLON.Camera[]}
  8253. */
  8254. this.cameras = new Array();
  8255. this.activeCameras = new Array();
  8256. // Meshes
  8257. /**
  8258. * All of the (abstract) meshes added to this scene.
  8259. * @see BABYLON.AbstractMesh
  8260. * @type {BABYLON.AbstractMesh[]}
  8261. */
  8262. this.meshes = new Array();
  8263. // Geometries
  8264. this._geometries = new Array();
  8265. this.materials = new Array();
  8266. this.multiMaterials = new Array();
  8267. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8268. // Textures
  8269. this.texturesEnabled = true;
  8270. this.textures = new Array();
  8271. // Particles
  8272. this.particlesEnabled = true;
  8273. this.particleSystems = new Array();
  8274. // Sprites
  8275. this.spritesEnabled = true;
  8276. this.spriteManagers = new Array();
  8277. // Layers
  8278. this.layers = new Array();
  8279. // Skeletons
  8280. this.skeletonsEnabled = true;
  8281. this.skeletons = new Array();
  8282. // Lens flares
  8283. this.lensFlaresEnabled = true;
  8284. this.lensFlareSystems = new Array();
  8285. // Collisions
  8286. this.collisionsEnabled = true;
  8287. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8288. // Postprocesses
  8289. this.postProcessesEnabled = true;
  8290. // Customs render targets
  8291. this.renderTargetsEnabled = true;
  8292. this.dumpNextRenderTargets = false;
  8293. this.customRenderTargets = new Array();
  8294. // Imported meshes
  8295. this.importedMeshesFiles = new Array();
  8296. this._actionManagers = new Array();
  8297. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8298. // Procedural textures
  8299. this.proceduralTexturesEnabled = true;
  8300. this._proceduralTextures = new Array();
  8301. this.soundTracks = new Array();
  8302. this._audioEnabled = true;
  8303. this._headphone = false;
  8304. this._totalVertices = 0;
  8305. this._activeIndices = 0;
  8306. this._activeParticles = 0;
  8307. this._lastFrameDuration = 0;
  8308. this._evaluateActiveMeshesDuration = 0;
  8309. this._renderTargetsDuration = 0;
  8310. this._particlesDuration = 0;
  8311. this._renderDuration = 0;
  8312. this._spritesDuration = 0;
  8313. this._animationRatio = 0;
  8314. this._renderId = 0;
  8315. this._executeWhenReadyTimeoutId = -1;
  8316. this._toBeDisposed = new BABYLON.SmartArray(256);
  8317. this._onReadyCallbacks = new Array();
  8318. this._pendingData = []; //ANY
  8319. this._onBeforeRenderCallbacks = new Array();
  8320. this._onAfterRenderCallbacks = new Array();
  8321. this._activeMeshes = new BABYLON.SmartArray(256);
  8322. this._processedMaterials = new BABYLON.SmartArray(256);
  8323. this._renderTargets = new BABYLON.SmartArray(256);
  8324. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8325. this._activeSkeletons = new BABYLON.SmartArray(32);
  8326. this._activeBones = 0;
  8327. this._activeAnimatables = new Array();
  8328. this._transformMatrix = BABYLON.Matrix.Zero();
  8329. this._scaledPosition = BABYLON.Vector3.Zero();
  8330. this._scaledVelocity = BABYLON.Vector3.Zero();
  8331. this._uniqueIdCounter = 0;
  8332. this._engine = engine;
  8333. engine.scenes.push(this);
  8334. this._renderingManager = new BABYLON.RenderingManager(this);
  8335. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8336. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8337. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8338. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8339. this.attachControl();
  8340. this._debugLayer = new BABYLON.DebugLayer(this);
  8341. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8342. //simplification queue
  8343. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8344. }
  8345. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8346. get: function () {
  8347. return Scene._FOGMODE_NONE;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8353. get: function () {
  8354. return Scene._FOGMODE_EXP;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8360. get: function () {
  8361. return Scene._FOGMODE_EXP2;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8367. get: function () {
  8368. return Scene._FOGMODE_LINEAR;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Scene.prototype, "debugLayer", {
  8374. // Properties
  8375. get: function () {
  8376. return this._debugLayer;
  8377. },
  8378. enumerable: true,
  8379. configurable: true
  8380. });
  8381. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8382. /**
  8383. * The mesh that is currently under the pointer.
  8384. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8385. */
  8386. get: function () {
  8387. return this._meshUnderPointer;
  8388. },
  8389. enumerable: true,
  8390. configurable: true
  8391. });
  8392. Object.defineProperty(Scene.prototype, "pointerX", {
  8393. /**
  8394. * Current on-screen X position of the pointer
  8395. * @return {number} X position of the pointer
  8396. */
  8397. get: function () {
  8398. return this._pointerX;
  8399. },
  8400. enumerable: true,
  8401. configurable: true
  8402. });
  8403. Object.defineProperty(Scene.prototype, "pointerY", {
  8404. /**
  8405. * Current on-screen Y position of the pointer
  8406. * @return {number} Y position of the pointer
  8407. */
  8408. get: function () {
  8409. return this._pointerY;
  8410. },
  8411. enumerable: true,
  8412. configurable: true
  8413. });
  8414. Scene.prototype.getCachedMaterial = function () {
  8415. return this._cachedMaterial;
  8416. };
  8417. Scene.prototype.getBoundingBoxRenderer = function () {
  8418. return this._boundingBoxRenderer;
  8419. };
  8420. Scene.prototype.getOutlineRenderer = function () {
  8421. return this._outlineRenderer;
  8422. };
  8423. Scene.prototype.getEngine = function () {
  8424. return this._engine;
  8425. };
  8426. Scene.prototype.getTotalVertices = function () {
  8427. return this._totalVertices;
  8428. };
  8429. Scene.prototype.getActiveIndices = function () {
  8430. return this._activeIndices;
  8431. };
  8432. Scene.prototype.getActiveParticles = function () {
  8433. return this._activeParticles;
  8434. };
  8435. Scene.prototype.getActiveBones = function () {
  8436. return this._activeBones;
  8437. };
  8438. // Stats
  8439. Scene.prototype.getLastFrameDuration = function () {
  8440. return this._lastFrameDuration;
  8441. };
  8442. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8443. return this._evaluateActiveMeshesDuration;
  8444. };
  8445. Scene.prototype.getActiveMeshes = function () {
  8446. return this._activeMeshes;
  8447. };
  8448. Scene.prototype.getRenderTargetsDuration = function () {
  8449. return this._renderTargetsDuration;
  8450. };
  8451. Scene.prototype.getRenderDuration = function () {
  8452. return this._renderDuration;
  8453. };
  8454. Scene.prototype.getParticlesDuration = function () {
  8455. return this._particlesDuration;
  8456. };
  8457. Scene.prototype.getSpritesDuration = function () {
  8458. return this._spritesDuration;
  8459. };
  8460. Scene.prototype.getAnimationRatio = function () {
  8461. return this._animationRatio;
  8462. };
  8463. Scene.prototype.getRenderId = function () {
  8464. return this._renderId;
  8465. };
  8466. Scene.prototype.incrementRenderId = function () {
  8467. this._renderId++;
  8468. };
  8469. Scene.prototype._updatePointerPosition = function (evt) {
  8470. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8471. this._pointerX = evt.clientX - canvasRect.left;
  8472. this._pointerY = evt.clientY - canvasRect.top;
  8473. if (this.cameraToUseForPointers) {
  8474. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8475. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8476. }
  8477. };
  8478. // Pointers handling
  8479. Scene.prototype.attachControl = function () {
  8480. var _this = this;
  8481. this._onPointerMove = function (evt) {
  8482. var canvas = _this._engine.getRenderingCanvas();
  8483. _this._updatePointerPosition(evt);
  8484. 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);
  8485. if (pickResult.hit) {
  8486. _this._meshUnderPointer = pickResult.pickedMesh;
  8487. _this.setPointerOverMesh(pickResult.pickedMesh);
  8488. canvas.style.cursor = "pointer";
  8489. }
  8490. else {
  8491. _this.setPointerOverMesh(null);
  8492. canvas.style.cursor = "";
  8493. _this._meshUnderPointer = null;
  8494. }
  8495. };
  8496. this._onPointerDown = function (evt) {
  8497. var predicate = null;
  8498. if (!_this.onPointerDown) {
  8499. predicate = function (mesh) {
  8500. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8501. };
  8502. }
  8503. _this._updatePointerPosition(evt);
  8504. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8505. if (pickResult.hit) {
  8506. if (pickResult.pickedMesh.actionManager) {
  8507. switch (evt.button) {
  8508. case 0:
  8509. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8510. break;
  8511. case 1:
  8512. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8513. break;
  8514. case 2:
  8515. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8516. break;
  8517. }
  8518. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8519. }
  8520. }
  8521. if (_this.onPointerDown) {
  8522. _this.onPointerDown(evt, pickResult);
  8523. }
  8524. };
  8525. this._onPointerUp = function (evt) {
  8526. var predicate = null;
  8527. if (!_this.onPointerUp) {
  8528. predicate = function (mesh) {
  8529. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  8530. };
  8531. }
  8532. _this._updatePointerPosition(evt);
  8533. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8534. if (pickResult.hit) {
  8535. if (pickResult.pickedMesh.actionManager) {
  8536. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8537. }
  8538. }
  8539. if (_this.onPointerUp) {
  8540. _this.onPointerUp(evt, pickResult);
  8541. }
  8542. };
  8543. this._onKeyDown = function (evt) {
  8544. if (_this.actionManager) {
  8545. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8546. }
  8547. };
  8548. this._onKeyUp = function (evt) {
  8549. if (_this.actionManager) {
  8550. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8551. }
  8552. };
  8553. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8554. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8555. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8556. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8557. BABYLON.Tools.RegisterTopRootEvents([
  8558. { name: "keydown", handler: this._onKeyDown },
  8559. { name: "keyup", handler: this._onKeyUp }
  8560. ]);
  8561. };
  8562. Scene.prototype.detachControl = function () {
  8563. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8564. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8565. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8566. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  8567. BABYLON.Tools.UnregisterTopRootEvents([
  8568. { name: "keydown", handler: this._onKeyDown },
  8569. { name: "keyup", handler: this._onKeyUp }
  8570. ]);
  8571. };
  8572. // Ready
  8573. Scene.prototype.isReady = function () {
  8574. if (this._pendingData.length > 0) {
  8575. return false;
  8576. }
  8577. for (var index = 0; index < this._geometries.length; index++) {
  8578. var geometry = this._geometries[index];
  8579. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8580. return false;
  8581. }
  8582. }
  8583. for (index = 0; index < this.meshes.length; index++) {
  8584. var mesh = this.meshes[index];
  8585. if (!mesh.isReady()) {
  8586. return false;
  8587. }
  8588. var mat = mesh.material;
  8589. if (mat) {
  8590. if (!mat.isReady(mesh)) {
  8591. return false;
  8592. }
  8593. }
  8594. }
  8595. return true;
  8596. };
  8597. Scene.prototype.resetCachedMaterial = function () {
  8598. this._cachedMaterial = null;
  8599. };
  8600. Scene.prototype.registerBeforeRender = function (func) {
  8601. this._onBeforeRenderCallbacks.push(func);
  8602. };
  8603. Scene.prototype.unregisterBeforeRender = function (func) {
  8604. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8605. if (index > -1) {
  8606. this._onBeforeRenderCallbacks.splice(index, 1);
  8607. }
  8608. };
  8609. Scene.prototype.registerAfterRender = function (func) {
  8610. this._onAfterRenderCallbacks.push(func);
  8611. };
  8612. Scene.prototype.unregisterAfterRender = function (func) {
  8613. var index = this._onAfterRenderCallbacks.indexOf(func);
  8614. if (index > -1) {
  8615. this._onAfterRenderCallbacks.splice(index, 1);
  8616. }
  8617. };
  8618. Scene.prototype._addPendingData = function (data) {
  8619. this._pendingData.push(data);
  8620. };
  8621. Scene.prototype._removePendingData = function (data) {
  8622. var index = this._pendingData.indexOf(data);
  8623. if (index !== -1) {
  8624. this._pendingData.splice(index, 1);
  8625. }
  8626. };
  8627. Scene.prototype.getWaitingItemsCount = function () {
  8628. return this._pendingData.length;
  8629. };
  8630. /**
  8631. * Registers a function to be executed when the scene is ready.
  8632. * @param {Function} func - the function to be executed.
  8633. */
  8634. Scene.prototype.executeWhenReady = function (func) {
  8635. var _this = this;
  8636. this._onReadyCallbacks.push(func);
  8637. if (this._executeWhenReadyTimeoutId !== -1) {
  8638. return;
  8639. }
  8640. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8641. _this._checkIsReady();
  8642. }, 150);
  8643. };
  8644. Scene.prototype._checkIsReady = function () {
  8645. var _this = this;
  8646. if (this.isReady()) {
  8647. this._onReadyCallbacks.forEach(function (func) {
  8648. func();
  8649. });
  8650. this._onReadyCallbacks = [];
  8651. this._executeWhenReadyTimeoutId = -1;
  8652. return;
  8653. }
  8654. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8655. _this._checkIsReady();
  8656. }, 150);
  8657. };
  8658. // Animations
  8659. /**
  8660. * Will start the animation sequence of a given target
  8661. * @param target - the target
  8662. * @param {number} from - from which frame should animation start
  8663. * @param {number} to - till which frame should animation run.
  8664. * @param {boolean} [loop] - should the animation loop
  8665. * @param {number} [speedRatio] - the speed in which to run the animation
  8666. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8667. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8668. * @return {BABYLON.Animatable} the animatable object created for this animation
  8669. * @see BABYLON.Animatable
  8670. * @see http://doc.babylonjs.com/page.php?p=22081
  8671. */
  8672. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8673. if (speedRatio === undefined) {
  8674. speedRatio = 1.0;
  8675. }
  8676. this.stopAnimation(target);
  8677. if (!animatable) {
  8678. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8679. }
  8680. // Local animations
  8681. if (target.animations) {
  8682. animatable.appendAnimations(target, target.animations);
  8683. }
  8684. // Children animations
  8685. if (target.getAnimatables) {
  8686. var animatables = target.getAnimatables();
  8687. for (var index = 0; index < animatables.length; index++) {
  8688. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8689. }
  8690. }
  8691. return animatable;
  8692. };
  8693. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8694. if (speedRatio === undefined) {
  8695. speedRatio = 1.0;
  8696. }
  8697. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8698. return animatable;
  8699. };
  8700. Scene.prototype.getAnimatableByTarget = function (target) {
  8701. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8702. if (this._activeAnimatables[index].target === target) {
  8703. return this._activeAnimatables[index];
  8704. }
  8705. }
  8706. return null;
  8707. };
  8708. /**
  8709. * Will stop the animation of the given target
  8710. * @param target - the target
  8711. * @see beginAnimation
  8712. */
  8713. Scene.prototype.stopAnimation = function (target) {
  8714. var animatable = this.getAnimatableByTarget(target);
  8715. if (animatable) {
  8716. animatable.stop();
  8717. }
  8718. };
  8719. Scene.prototype._animate = function () {
  8720. if (!this.animationsEnabled) {
  8721. return;
  8722. }
  8723. if (!this._animationStartDate) {
  8724. this._animationStartDate = BABYLON.Tools.Now;
  8725. }
  8726. // Getting time
  8727. var now = BABYLON.Tools.Now;
  8728. var delay = now - this._animationStartDate;
  8729. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8730. this._activeAnimatables[index]._animate(delay);
  8731. }
  8732. };
  8733. // Matrix
  8734. Scene.prototype.getViewMatrix = function () {
  8735. return this._viewMatrix;
  8736. };
  8737. Scene.prototype.getProjectionMatrix = function () {
  8738. return this._projectionMatrix;
  8739. };
  8740. Scene.prototype.getTransformMatrix = function () {
  8741. return this._transformMatrix;
  8742. };
  8743. Scene.prototype.setTransformMatrix = function (view, projection) {
  8744. this._viewMatrix = view;
  8745. this._projectionMatrix = projection;
  8746. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8747. };
  8748. // Methods
  8749. Scene.prototype.addMesh = function (newMesh) {
  8750. newMesh.uniqueId = this._uniqueIdCounter++;
  8751. var position = this.meshes.push(newMesh);
  8752. if (this.onNewMeshAdded) {
  8753. this.onNewMeshAdded(newMesh, position, this);
  8754. }
  8755. };
  8756. Scene.prototype.removeMesh = function (toRemove) {
  8757. var index = this.meshes.indexOf(toRemove);
  8758. if (index !== -1) {
  8759. // Remove from the scene if mesh found
  8760. this.meshes.splice(index, 1);
  8761. }
  8762. if (this.onMeshRemoved) {
  8763. this.onMeshRemoved(toRemove);
  8764. }
  8765. return index;
  8766. };
  8767. Scene.prototype.removeLight = function (toRemove) {
  8768. var index = this.lights.indexOf(toRemove);
  8769. if (index !== -1) {
  8770. // Remove from the scene if mesh found
  8771. this.lights.splice(index, 1);
  8772. }
  8773. if (this.onLightRemoved) {
  8774. this.onLightRemoved(toRemove);
  8775. }
  8776. return index;
  8777. };
  8778. Scene.prototype.removeCamera = function (toRemove) {
  8779. var index = this.cameras.indexOf(toRemove);
  8780. if (index !== -1) {
  8781. // Remove from the scene if mesh found
  8782. this.cameras.splice(index, 1);
  8783. }
  8784. // Remove from activeCameras
  8785. var index2 = this.activeCameras.indexOf(toRemove);
  8786. if (index2 !== -1) {
  8787. // Remove from the scene if mesh found
  8788. this.activeCameras.splice(index2, 1);
  8789. }
  8790. // Reset the activeCamera
  8791. if (this.activeCamera === toRemove) {
  8792. if (this.cameras.length > 0) {
  8793. this.activeCamera = this.cameras[0];
  8794. }
  8795. else {
  8796. this.activeCamera = null;
  8797. }
  8798. }
  8799. if (this.onCameraRemoved) {
  8800. this.onCameraRemoved(toRemove);
  8801. }
  8802. return index;
  8803. };
  8804. Scene.prototype.addLight = function (newLight) {
  8805. newLight.uniqueId = this._uniqueIdCounter++;
  8806. var position = this.lights.push(newLight);
  8807. if (this.onNewLightAdded) {
  8808. this.onNewLightAdded(newLight, position, this);
  8809. }
  8810. };
  8811. Scene.prototype.addCamera = function (newCamera) {
  8812. newCamera.uniqueId = this._uniqueIdCounter++;
  8813. var position = this.cameras.push(newCamera);
  8814. if (this.onNewCameraAdded) {
  8815. this.onNewCameraAdded(newCamera, position, this);
  8816. }
  8817. };
  8818. /**
  8819. * sets the active camera of the scene using its ID
  8820. * @param {string} id - the camera's ID
  8821. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8822. * @see activeCamera
  8823. */
  8824. Scene.prototype.setActiveCameraByID = function (id) {
  8825. var camera = this.getCameraByID(id);
  8826. if (camera) {
  8827. this.activeCamera = camera;
  8828. return camera;
  8829. }
  8830. return null;
  8831. };
  8832. /**
  8833. * sets the active camera of the scene using its name
  8834. * @param {string} name - the camera's name
  8835. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8836. * @see activeCamera
  8837. */
  8838. Scene.prototype.setActiveCameraByName = function (name) {
  8839. var camera = this.getCameraByName(name);
  8840. if (camera) {
  8841. this.activeCamera = camera;
  8842. return camera;
  8843. }
  8844. return null;
  8845. };
  8846. /**
  8847. * get a material using its id
  8848. * @param {string} the material's ID
  8849. * @return {BABYLON.Material|null} the material or null if none found.
  8850. */
  8851. Scene.prototype.getMaterialByID = function (id) {
  8852. for (var index = 0; index < this.materials.length; index++) {
  8853. if (this.materials[index].id === id) {
  8854. return this.materials[index];
  8855. }
  8856. }
  8857. return null;
  8858. };
  8859. /**
  8860. * get a material using its name
  8861. * @param {string} the material's name
  8862. * @return {BABYLON.Material|null} the material or null if none found.
  8863. */
  8864. Scene.prototype.getMaterialByName = function (name) {
  8865. for (var index = 0; index < this.materials.length; index++) {
  8866. if (this.materials[index].name === name) {
  8867. return this.materials[index];
  8868. }
  8869. }
  8870. return null;
  8871. };
  8872. Scene.prototype.getCameraByID = function (id) {
  8873. for (var index = 0; index < this.cameras.length; index++) {
  8874. if (this.cameras[index].id === id) {
  8875. return this.cameras[index];
  8876. }
  8877. }
  8878. return null;
  8879. };
  8880. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8881. for (var index = 0; index < this.cameras.length; index++) {
  8882. if (this.cameras[index].uniqueId === uniqueId) {
  8883. return this.cameras[index];
  8884. }
  8885. }
  8886. return null;
  8887. };
  8888. /**
  8889. * get a camera using its name
  8890. * @param {string} the camera's name
  8891. * @return {BABYLON.Camera|null} the camera or null if none found.
  8892. */
  8893. Scene.prototype.getCameraByName = function (name) {
  8894. for (var index = 0; index < this.cameras.length; index++) {
  8895. if (this.cameras[index].name === name) {
  8896. return this.cameras[index];
  8897. }
  8898. }
  8899. return null;
  8900. };
  8901. /**
  8902. * get a light node using its name
  8903. * @param {string} the light's name
  8904. * @return {BABYLON.Light|null} the light or null if none found.
  8905. */
  8906. Scene.prototype.getLightByName = function (name) {
  8907. for (var index = 0; index < this.lights.length; index++) {
  8908. if (this.lights[index].name === name) {
  8909. return this.lights[index];
  8910. }
  8911. }
  8912. return null;
  8913. };
  8914. /**
  8915. * get a light node using its ID
  8916. * @param {string} the light's id
  8917. * @return {BABYLON.Light|null} the light or null if none found.
  8918. */
  8919. Scene.prototype.getLightByID = function (id) {
  8920. for (var index = 0; index < this.lights.length; index++) {
  8921. if (this.lights[index].id === id) {
  8922. return this.lights[index];
  8923. }
  8924. }
  8925. return null;
  8926. };
  8927. /**
  8928. * get a light node using its scene-generated unique ID
  8929. * @param {number} the light's unique id
  8930. * @return {BABYLON.Light|null} the light or null if none found.
  8931. */
  8932. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8933. for (var index = 0; index < this.lights.length; index++) {
  8934. if (this.lights[index].uniqueId === uniqueId) {
  8935. return this.lights[index];
  8936. }
  8937. }
  8938. return null;
  8939. };
  8940. /**
  8941. * get a geometry using its ID
  8942. * @param {string} the geometry's id
  8943. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8944. */
  8945. Scene.prototype.getGeometryByID = function (id) {
  8946. for (var index = 0; index < this._geometries.length; index++) {
  8947. if (this._geometries[index].id === id) {
  8948. return this._geometries[index];
  8949. }
  8950. }
  8951. return null;
  8952. };
  8953. /**
  8954. * add a new geometry to this scene.
  8955. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8956. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8957. * @return {boolean} was the geometry added or not
  8958. */
  8959. Scene.prototype.pushGeometry = function (geometry, force) {
  8960. if (!force && this.getGeometryByID(geometry.id)) {
  8961. return false;
  8962. }
  8963. this._geometries.push(geometry);
  8964. if (this.onGeometryAdded) {
  8965. this.onGeometryAdded(geometry);
  8966. }
  8967. return true;
  8968. };
  8969. /**
  8970. * Removes an existing geometry
  8971. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  8972. * @return {boolean} was the geometry removed or not
  8973. */
  8974. Scene.prototype.removeGeometry = function (geometry) {
  8975. var index = this._geometries.indexOf(geometry);
  8976. if (index > -1) {
  8977. this._geometries.splice(index, 1);
  8978. if (this.onGeometryRemoved) {
  8979. this.onGeometryRemoved(geometry);
  8980. }
  8981. return true;
  8982. }
  8983. return false;
  8984. };
  8985. Scene.prototype.getGeometries = function () {
  8986. return this._geometries;
  8987. };
  8988. /**
  8989. * Get the first added mesh found of a given ID
  8990. * @param {string} id - the id to search for
  8991. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8992. */
  8993. Scene.prototype.getMeshByID = function (id) {
  8994. for (var index = 0; index < this.meshes.length; index++) {
  8995. if (this.meshes[index].id === id) {
  8996. return this.meshes[index];
  8997. }
  8998. }
  8999. return null;
  9000. };
  9001. /**
  9002. * Get a mesh with its auto-generated unique id
  9003. * @param {number} uniqueId - the unique id to search for
  9004. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  9005. */
  9006. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  9007. for (var index = 0; index < this.meshes.length; index++) {
  9008. if (this.meshes[index].uniqueId === uniqueId) {
  9009. return this.meshes[index];
  9010. }
  9011. }
  9012. return null;
  9013. };
  9014. /**
  9015. * Get a the last added mesh found of a given ID
  9016. * @param {string} id - the id to search for
  9017. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  9018. */
  9019. Scene.prototype.getLastMeshByID = function (id) {
  9020. for (var index = this.meshes.length - 1; index >= 0; index--) {
  9021. if (this.meshes[index].id === id) {
  9022. return this.meshes[index];
  9023. }
  9024. }
  9025. return null;
  9026. };
  9027. /**
  9028. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  9029. * @param {string} id - the id to search for
  9030. * @return {BABYLON.Node|null} the node found or null if not found at all.
  9031. */
  9032. Scene.prototype.getLastEntryByID = function (id) {
  9033. for (var index = this.meshes.length - 1; index >= 0; index--) {
  9034. if (this.meshes[index].id === id) {
  9035. return this.meshes[index];
  9036. }
  9037. }
  9038. for (index = this.cameras.length - 1; index >= 0; index--) {
  9039. if (this.cameras[index].id === id) {
  9040. return this.cameras[index];
  9041. }
  9042. }
  9043. for (index = this.lights.length - 1; index >= 0; index--) {
  9044. if (this.lights[index].id === id) {
  9045. return this.lights[index];
  9046. }
  9047. }
  9048. return null;
  9049. };
  9050. Scene.prototype.getNodeByName = function (name) {
  9051. var mesh = this.getMeshByName(name);
  9052. if (mesh) {
  9053. return mesh;
  9054. }
  9055. var light = this.getLightByName(name);
  9056. if (light) {
  9057. return light;
  9058. }
  9059. return this.getCameraByName(name);
  9060. };
  9061. Scene.prototype.getMeshByName = function (name) {
  9062. for (var index = 0; index < this.meshes.length; index++) {
  9063. if (this.meshes[index].name === name) {
  9064. return this.meshes[index];
  9065. }
  9066. }
  9067. return null;
  9068. };
  9069. Scene.prototype.getSoundByName = function (name) {
  9070. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  9071. if (this.mainSoundTrack.soundCollection[index].name === name) {
  9072. return this.mainSoundTrack.soundCollection[index];
  9073. }
  9074. }
  9075. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  9076. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  9077. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  9078. return this.soundTracks[sdIndex].soundCollection[index];
  9079. }
  9080. }
  9081. }
  9082. return null;
  9083. };
  9084. Scene.prototype.getLastSkeletonByID = function (id) {
  9085. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  9086. if (this.skeletons[index].id === id) {
  9087. return this.skeletons[index];
  9088. }
  9089. }
  9090. return null;
  9091. };
  9092. Scene.prototype.getSkeletonById = function (id) {
  9093. for (var index = 0; index < this.skeletons.length; index++) {
  9094. if (this.skeletons[index].id === id) {
  9095. return this.skeletons[index];
  9096. }
  9097. }
  9098. return null;
  9099. };
  9100. Scene.prototype.getSkeletonByName = function (name) {
  9101. for (var index = 0; index < this.skeletons.length; index++) {
  9102. if (this.skeletons[index].name === name) {
  9103. return this.skeletons[index];
  9104. }
  9105. }
  9106. return null;
  9107. };
  9108. Scene.prototype.isActiveMesh = function (mesh) {
  9109. return (this._activeMeshes.indexOf(mesh) !== -1);
  9110. };
  9111. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9112. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9113. var material = subMesh.getMaterial();
  9114. if (mesh.showSubMeshesBoundingBox) {
  9115. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9116. }
  9117. if (material) {
  9118. // Render targets
  9119. if (material.getRenderTargetTextures) {
  9120. if (this._processedMaterials.indexOf(material) === -1) {
  9121. this._processedMaterials.push(material);
  9122. this._renderTargets.concat(material.getRenderTargetTextures());
  9123. }
  9124. }
  9125. // Dispatch
  9126. this._activeIndices += subMesh.indexCount;
  9127. this._renderingManager.dispatch(subMesh);
  9128. }
  9129. }
  9130. };
  9131. Scene.prototype._evaluateActiveMeshes = function () {
  9132. this.activeCamera._activeMeshes.reset();
  9133. this._activeMeshes.reset();
  9134. this._renderingManager.reset();
  9135. this._processedMaterials.reset();
  9136. this._activeParticleSystems.reset();
  9137. this._activeSkeletons.reset();
  9138. this._boundingBoxRenderer.reset();
  9139. if (!this._frustumPlanes) {
  9140. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9141. }
  9142. else {
  9143. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9144. }
  9145. // Meshes
  9146. var meshes;
  9147. var len;
  9148. if (this._selectionOctree) {
  9149. var selection = this._selectionOctree.select(this._frustumPlanes);
  9150. meshes = selection.data;
  9151. len = selection.length;
  9152. }
  9153. else {
  9154. len = this.meshes.length;
  9155. meshes = this.meshes;
  9156. }
  9157. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9158. var mesh = meshes[meshIndex];
  9159. if (mesh.isBlocked) {
  9160. continue;
  9161. }
  9162. this._totalVertices += mesh.getTotalVertices();
  9163. if (!mesh.isReady() || !mesh.isEnabled()) {
  9164. continue;
  9165. }
  9166. mesh.computeWorldMatrix();
  9167. // Intersections
  9168. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9169. this._meshesForIntersections.pushNoDuplicate(mesh);
  9170. }
  9171. // Switch to current LOD
  9172. var meshLOD = mesh.getLOD(this.activeCamera);
  9173. if (!meshLOD) {
  9174. continue;
  9175. }
  9176. mesh._preActivate();
  9177. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9178. this._activeMeshes.push(mesh);
  9179. this.activeCamera._activeMeshes.push(mesh);
  9180. mesh._activate(this._renderId);
  9181. this._activeMesh(meshLOD);
  9182. }
  9183. }
  9184. // Particle systems
  9185. var beforeParticlesDate = BABYLON.Tools.Now;
  9186. if (this.particlesEnabled) {
  9187. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9188. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9189. var particleSystem = this.particleSystems[particleIndex];
  9190. if (!particleSystem.isStarted()) {
  9191. continue;
  9192. }
  9193. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9194. this._activeParticleSystems.push(particleSystem);
  9195. particleSystem.animate();
  9196. }
  9197. }
  9198. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9199. }
  9200. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9201. };
  9202. Scene.prototype._activeMesh = function (mesh) {
  9203. if (mesh.skeleton && this.skeletonsEnabled) {
  9204. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9205. }
  9206. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9207. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9208. }
  9209. if (mesh && mesh.subMeshes) {
  9210. // Submeshes Octrees
  9211. var len;
  9212. var subMeshes;
  9213. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9214. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9215. len = intersections.length;
  9216. subMeshes = intersections.data;
  9217. }
  9218. else {
  9219. subMeshes = mesh.subMeshes;
  9220. len = subMeshes.length;
  9221. }
  9222. for (var subIndex = 0; subIndex < len; subIndex++) {
  9223. var subMesh = subMeshes[subIndex];
  9224. this._evaluateSubMesh(subMesh, mesh);
  9225. }
  9226. }
  9227. };
  9228. Scene.prototype.updateTransformMatrix = function (force) {
  9229. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9230. };
  9231. Scene.prototype._renderForCamera = function (camera) {
  9232. var engine = this._engine;
  9233. this.activeCamera = camera;
  9234. if (!this.activeCamera)
  9235. throw new Error("Active camera not set");
  9236. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9237. // Viewport
  9238. engine.setViewport(this.activeCamera.viewport);
  9239. // Camera
  9240. this._renderId++;
  9241. this.updateTransformMatrix();
  9242. if (this.beforeCameraRender) {
  9243. this.beforeCameraRender(this.activeCamera);
  9244. }
  9245. // Meshes
  9246. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9247. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9248. this._evaluateActiveMeshes();
  9249. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9250. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9251. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9252. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9253. skeleton.prepare();
  9254. }
  9255. // Render targets
  9256. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9257. if (this.renderTargetsEnabled) {
  9258. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9259. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9260. var renderTarget = this._renderTargets.data[renderIndex];
  9261. if (renderTarget._shouldRender()) {
  9262. this._renderId++;
  9263. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9264. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9265. }
  9266. }
  9267. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9268. this._renderId++;
  9269. }
  9270. if (this._renderTargets.length > 0) {
  9271. engine.restoreDefaultFramebuffer();
  9272. }
  9273. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9274. // Prepare Frame
  9275. this.postProcessManager._prepareFrame();
  9276. var beforeRenderDate = BABYLON.Tools.Now;
  9277. // Backgrounds
  9278. if (this.layers.length) {
  9279. engine.setDepthBuffer(false);
  9280. var layerIndex;
  9281. var layer;
  9282. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9283. layer = this.layers[layerIndex];
  9284. if (layer.isBackground) {
  9285. layer.render();
  9286. }
  9287. }
  9288. engine.setDepthBuffer(true);
  9289. }
  9290. // Render
  9291. BABYLON.Tools.StartPerformanceCounter("Main render");
  9292. this._renderingManager.render(null, null, true, true);
  9293. BABYLON.Tools.EndPerformanceCounter("Main render");
  9294. // Bounding boxes
  9295. this._boundingBoxRenderer.render();
  9296. // Lens flares
  9297. if (this.lensFlaresEnabled) {
  9298. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9299. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9300. this.lensFlareSystems[lensFlareSystemIndex].render();
  9301. }
  9302. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9303. }
  9304. // Foregrounds
  9305. if (this.layers.length) {
  9306. engine.setDepthBuffer(false);
  9307. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9308. layer = this.layers[layerIndex];
  9309. if (!layer.isBackground) {
  9310. layer.render();
  9311. }
  9312. }
  9313. engine.setDepthBuffer(true);
  9314. }
  9315. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9316. // Finalize frame
  9317. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9318. // Update camera
  9319. this.activeCamera._updateFromScene();
  9320. // Reset some special arrays
  9321. this._renderTargets.reset();
  9322. if (this.afterCameraRender) {
  9323. this.afterCameraRender(this.activeCamera);
  9324. }
  9325. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9326. };
  9327. Scene.prototype._processSubCameras = function (camera) {
  9328. if (camera.subCameras.length === 0) {
  9329. this._renderForCamera(camera);
  9330. return;
  9331. }
  9332. for (var index = 0; index < camera.subCameras.length; index++) {
  9333. this._renderForCamera(camera.subCameras[index]);
  9334. }
  9335. this.activeCamera = camera;
  9336. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9337. // Update camera
  9338. this.activeCamera._updateFromScene();
  9339. };
  9340. Scene.prototype._checkIntersections = function () {
  9341. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9342. var sourceMesh = this._meshesForIntersections.data[index];
  9343. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9344. var action = sourceMesh.actionManager.actions[actionIndex];
  9345. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9346. var parameters = action.getTriggerParameter();
  9347. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9348. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9349. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9350. if (areIntersecting && currentIntersectionInProgress === -1) {
  9351. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9352. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9353. sourceMesh._intersectionsInProgress.push(otherMesh);
  9354. }
  9355. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9356. sourceMesh._intersectionsInProgress.push(otherMesh);
  9357. }
  9358. }
  9359. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9360. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9361. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9362. if (indexOfOther > -1) {
  9363. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9364. }
  9365. }
  9366. }
  9367. }
  9368. }
  9369. };
  9370. Scene.prototype.render = function () {
  9371. var startDate = BABYLON.Tools.Now;
  9372. this._particlesDuration = 0;
  9373. this._spritesDuration = 0;
  9374. this._activeParticles = 0;
  9375. this._renderDuration = 0;
  9376. this._renderTargetsDuration = 0;
  9377. this._evaluateActiveMeshesDuration = 0;
  9378. this._totalVertices = 0;
  9379. this._activeIndices = 0;
  9380. this._activeBones = 0;
  9381. this.getEngine().resetDrawCalls();
  9382. this._meshesForIntersections.reset();
  9383. this.resetCachedMaterial();
  9384. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9385. // Actions
  9386. if (this.actionManager) {
  9387. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9388. }
  9389. //Simplification Queue
  9390. if (!this.simplificationQueue.running) {
  9391. this.simplificationQueue.executeNext();
  9392. }
  9393. // Before render
  9394. if (this.beforeRender) {
  9395. this.beforeRender();
  9396. }
  9397. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9398. this._onBeforeRenderCallbacks[callbackIndex]();
  9399. }
  9400. // Animations
  9401. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9402. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9403. this._animate();
  9404. // Physics
  9405. if (this._physicsEngine) {
  9406. BABYLON.Tools.StartPerformanceCounter("Physics");
  9407. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9408. BABYLON.Tools.EndPerformanceCounter("Physics");
  9409. }
  9410. // Customs render targets
  9411. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9412. var engine = this.getEngine();
  9413. var currentActiveCamera = this.activeCamera;
  9414. if (this.renderTargetsEnabled) {
  9415. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9416. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9417. var renderTarget = this.customRenderTargets[customIndex];
  9418. if (renderTarget._shouldRender()) {
  9419. this._renderId++;
  9420. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9421. if (!this.activeCamera)
  9422. throw new Error("Active camera not set");
  9423. // Viewport
  9424. engine.setViewport(this.activeCamera.viewport);
  9425. // Camera
  9426. this.updateTransformMatrix();
  9427. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9428. }
  9429. }
  9430. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9431. this._renderId++;
  9432. }
  9433. if (this.customRenderTargets.length > 0) {
  9434. engine.restoreDefaultFramebuffer();
  9435. }
  9436. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9437. this.activeCamera = currentActiveCamera;
  9438. // Procedural textures
  9439. if (this.proceduralTexturesEnabled) {
  9440. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9441. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9442. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9443. if (proceduralTexture._shouldRender()) {
  9444. proceduralTexture.render();
  9445. }
  9446. }
  9447. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9448. }
  9449. // Clear
  9450. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9451. // Shadows
  9452. if (this.shadowsEnabled) {
  9453. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9454. var light = this.lights[lightIndex];
  9455. var shadowGenerator = light.getShadowGenerator();
  9456. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9457. this._renderTargets.push(shadowGenerator.getShadowMap());
  9458. }
  9459. }
  9460. }
  9461. // Depth renderer
  9462. if (this._depthRenderer) {
  9463. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9464. }
  9465. // RenderPipeline
  9466. this.postProcessRenderPipelineManager.update();
  9467. // Multi-cameras?
  9468. if (this.activeCameras.length > 0) {
  9469. var currentRenderId = this._renderId;
  9470. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9471. this._renderId = currentRenderId;
  9472. this._processSubCameras(this.activeCameras[cameraIndex]);
  9473. }
  9474. }
  9475. else {
  9476. if (!this.activeCamera) {
  9477. throw new Error("No camera defined");
  9478. }
  9479. this._processSubCameras(this.activeCamera);
  9480. }
  9481. // Intersection checks
  9482. this._checkIntersections();
  9483. // Update the audio listener attached to the camera
  9484. this._updateAudioParameters();
  9485. // After render
  9486. if (this.afterRender) {
  9487. this.afterRender();
  9488. }
  9489. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9490. this._onAfterRenderCallbacks[callbackIndex]();
  9491. }
  9492. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9493. this._toBeDisposed.data[index].dispose();
  9494. this._toBeDisposed[index] = null;
  9495. }
  9496. this._toBeDisposed.reset();
  9497. if (this.dumpNextRenderTargets) {
  9498. this.dumpNextRenderTargets = false;
  9499. }
  9500. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9501. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9502. };
  9503. Scene.prototype._updateAudioParameters = function () {
  9504. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9505. return;
  9506. }
  9507. var listeningCamera;
  9508. var audioEngine = BABYLON.Engine.audioEngine;
  9509. if (this.activeCameras.length > 0) {
  9510. listeningCamera = this.activeCameras[0];
  9511. }
  9512. else {
  9513. listeningCamera = this.activeCamera;
  9514. }
  9515. if (listeningCamera && audioEngine.canUseWebAudio) {
  9516. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9517. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9518. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9519. cameraDirection.normalize();
  9520. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9521. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9522. var sound = this.mainSoundTrack.soundCollection[i];
  9523. if (sound.useCustomAttenuation) {
  9524. sound.updateDistanceFromListener();
  9525. }
  9526. }
  9527. for (i = 0; i < this.soundTracks.length; i++) {
  9528. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9529. sound = this.soundTracks[i].soundCollection[j];
  9530. if (sound.useCustomAttenuation) {
  9531. sound.updateDistanceFromListener();
  9532. }
  9533. }
  9534. }
  9535. }
  9536. };
  9537. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9538. // Audio
  9539. get: function () {
  9540. return this._audioEnabled;
  9541. },
  9542. set: function (value) {
  9543. this._audioEnabled = value;
  9544. if (this._audioEnabled) {
  9545. this._enableAudio();
  9546. }
  9547. else {
  9548. this._disableAudio();
  9549. }
  9550. },
  9551. enumerable: true,
  9552. configurable: true
  9553. });
  9554. Scene.prototype._disableAudio = function () {
  9555. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9556. this.mainSoundTrack.soundCollection[i].pause();
  9557. }
  9558. for (i = 0; i < this.soundTracks.length; i++) {
  9559. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9560. this.soundTracks[i].soundCollection[j].pause();
  9561. }
  9562. }
  9563. };
  9564. Scene.prototype._enableAudio = function () {
  9565. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9566. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9567. this.mainSoundTrack.soundCollection[i].play();
  9568. }
  9569. }
  9570. for (i = 0; i < this.soundTracks.length; i++) {
  9571. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9572. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9573. this.soundTracks[i].soundCollection[j].play();
  9574. }
  9575. }
  9576. }
  9577. };
  9578. Object.defineProperty(Scene.prototype, "headphone", {
  9579. get: function () {
  9580. return this._headphone;
  9581. },
  9582. set: function (value) {
  9583. this._headphone = value;
  9584. if (this._headphone) {
  9585. this._switchAudioModeForHeadphones();
  9586. }
  9587. else {
  9588. this._switchAudioModeForNormalSpeakers();
  9589. }
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Scene.prototype._switchAudioModeForHeadphones = function () {
  9595. this.mainSoundTrack.switchPanningModelToHRTF();
  9596. for (var i = 0; i < this.soundTracks.length; i++) {
  9597. this.soundTracks[i].switchPanningModelToHRTF();
  9598. }
  9599. };
  9600. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9601. this.mainSoundTrack.switchPanningModelToEqualPower();
  9602. for (var i = 0; i < this.soundTracks.length; i++) {
  9603. this.soundTracks[i].switchPanningModelToEqualPower();
  9604. }
  9605. };
  9606. Scene.prototype.enableDepthRenderer = function () {
  9607. if (this._depthRenderer) {
  9608. return this._depthRenderer;
  9609. }
  9610. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9611. return this._depthRenderer;
  9612. };
  9613. Scene.prototype.disableDepthRenderer = function () {
  9614. if (!this._depthRenderer) {
  9615. return;
  9616. }
  9617. this._depthRenderer.dispose();
  9618. this._depthRenderer = null;
  9619. };
  9620. Scene.prototype.dispose = function () {
  9621. this.beforeRender = null;
  9622. this.afterRender = null;
  9623. this.skeletons = [];
  9624. this._boundingBoxRenderer.dispose();
  9625. if (this._depthRenderer) {
  9626. this._depthRenderer.dispose();
  9627. }
  9628. // Debug layer
  9629. this.debugLayer.hide();
  9630. // Events
  9631. if (this.onDispose) {
  9632. this.onDispose();
  9633. }
  9634. this._onBeforeRenderCallbacks = [];
  9635. this._onAfterRenderCallbacks = [];
  9636. this.detachControl();
  9637. // Release sounds & sounds tracks
  9638. this.disposeSounds();
  9639. // Detach cameras
  9640. var canvas = this._engine.getRenderingCanvas();
  9641. var index;
  9642. for (index = 0; index < this.cameras.length; index++) {
  9643. this.cameras[index].detachControl(canvas);
  9644. }
  9645. while (this.lights.length) {
  9646. this.lights[0].dispose();
  9647. }
  9648. while (this.meshes.length) {
  9649. this.meshes[0].dispose(true);
  9650. }
  9651. while (this.cameras.length) {
  9652. this.cameras[0].dispose();
  9653. }
  9654. while (this.materials.length) {
  9655. this.materials[0].dispose();
  9656. }
  9657. while (this.particleSystems.length) {
  9658. this.particleSystems[0].dispose();
  9659. }
  9660. while (this.spriteManagers.length) {
  9661. this.spriteManagers[0].dispose();
  9662. }
  9663. while (this.layers.length) {
  9664. this.layers[0].dispose();
  9665. }
  9666. while (this.textures.length) {
  9667. this.textures[0].dispose();
  9668. }
  9669. // Post-processes
  9670. this.postProcessManager.dispose();
  9671. // Physics
  9672. if (this._physicsEngine) {
  9673. this.disablePhysicsEngine();
  9674. }
  9675. // Remove from engine
  9676. index = this._engine.scenes.indexOf(this);
  9677. if (index > -1) {
  9678. this._engine.scenes.splice(index, 1);
  9679. }
  9680. this._engine.wipeCaches();
  9681. };
  9682. // Release sounds & sounds tracks
  9683. Scene.prototype.disposeSounds = function () {
  9684. this.mainSoundTrack.dispose();
  9685. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9686. this.soundTracks[scIndex].dispose();
  9687. }
  9688. };
  9689. // Collisions
  9690. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9691. if (excludedMesh === void 0) { excludedMesh = null; }
  9692. position.divideToRef(collider.radius, this._scaledPosition);
  9693. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9694. collider.retry = 0;
  9695. collider.initialVelocity = this._scaledVelocity;
  9696. collider.initialPosition = this._scaledPosition;
  9697. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9698. finalPosition.multiplyInPlace(collider.radius);
  9699. };
  9700. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9701. if (excludedMesh === void 0) { excludedMesh = null; }
  9702. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9703. if (collider.retry >= maximumRetry) {
  9704. finalPosition.copyFrom(position);
  9705. return;
  9706. }
  9707. collider._initialize(position, velocity, closeDistance);
  9708. for (var index = 0; index < this.meshes.length; index++) {
  9709. var mesh = this.meshes[index];
  9710. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9711. mesh._checkCollision(collider);
  9712. }
  9713. }
  9714. if (!collider.collisionFound) {
  9715. position.addToRef(velocity, finalPosition);
  9716. return;
  9717. }
  9718. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9719. collider._getResponse(position, velocity);
  9720. }
  9721. if (velocity.length() <= closeDistance) {
  9722. finalPosition.copyFrom(position);
  9723. return;
  9724. }
  9725. collider.retry++;
  9726. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9727. };
  9728. // Octrees
  9729. Scene.prototype.getWorldExtends = function () {
  9730. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9731. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9732. for (var index = 0; index < this.meshes.length; index++) {
  9733. var mesh = this.meshes[index];
  9734. mesh.computeWorldMatrix(true);
  9735. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9736. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9737. BABYLON.Tools.CheckExtends(minBox, min, max);
  9738. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9739. }
  9740. return {
  9741. min: min,
  9742. max: max
  9743. };
  9744. };
  9745. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9746. if (maxCapacity === void 0) { maxCapacity = 64; }
  9747. if (maxDepth === void 0) { maxDepth = 2; }
  9748. if (!this._selectionOctree) {
  9749. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9750. }
  9751. var worldExtends = this.getWorldExtends();
  9752. // Update octree
  9753. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9754. return this._selectionOctree;
  9755. };
  9756. // Picking
  9757. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9758. var engine = this._engine;
  9759. if (!camera) {
  9760. if (!this.activeCamera)
  9761. throw new Error("Active camera not set");
  9762. camera = this.activeCamera;
  9763. }
  9764. var cameraViewport = camera.viewport;
  9765. var viewport = cameraViewport.toGlobal(engine);
  9766. // Moving coordinates to local viewport world
  9767. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9768. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9769. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9770. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9771. };
  9772. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9773. var pickingInfo = null;
  9774. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9775. var mesh = this.meshes[meshIndex];
  9776. if (predicate) {
  9777. if (!predicate(mesh)) {
  9778. continue;
  9779. }
  9780. }
  9781. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9782. continue;
  9783. }
  9784. var world = mesh.getWorldMatrix();
  9785. var ray = rayFunction(world);
  9786. var result = mesh.intersects(ray, fastCheck);
  9787. if (!result || !result.hit)
  9788. continue;
  9789. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9790. continue;
  9791. pickingInfo = result;
  9792. if (fastCheck) {
  9793. break;
  9794. }
  9795. }
  9796. return pickingInfo || new BABYLON.PickingInfo();
  9797. };
  9798. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9799. var _this = this;
  9800. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9801. /// <param name="x">X position on screen</param>
  9802. /// <param name="y">Y position on screen</param>
  9803. /// <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>
  9804. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9805. /// <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>
  9806. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9807. };
  9808. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9809. var _this = this;
  9810. return this._internalPick(function (world) {
  9811. if (!_this._pickWithRayInverseMatrix) {
  9812. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9813. }
  9814. world.invertToRef(_this._pickWithRayInverseMatrix);
  9815. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9816. }, predicate, fastCheck);
  9817. };
  9818. Scene.prototype.setPointerOverMesh = function (mesh) {
  9819. if (this._pointerOverMesh === mesh) {
  9820. return;
  9821. }
  9822. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9823. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9824. }
  9825. this._pointerOverMesh = mesh;
  9826. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9827. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9828. }
  9829. };
  9830. Scene.prototype.getPointerOverMesh = function () {
  9831. return this._pointerOverMesh;
  9832. };
  9833. // Physics
  9834. Scene.prototype.getPhysicsEngine = function () {
  9835. return this._physicsEngine;
  9836. };
  9837. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9838. if (this._physicsEngine) {
  9839. return true;
  9840. }
  9841. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9842. if (!this._physicsEngine.isSupported()) {
  9843. this._physicsEngine = null;
  9844. return false;
  9845. }
  9846. this._physicsEngine._initialize(gravity);
  9847. return true;
  9848. };
  9849. Scene.prototype.disablePhysicsEngine = function () {
  9850. if (!this._physicsEngine) {
  9851. return;
  9852. }
  9853. this._physicsEngine.dispose();
  9854. this._physicsEngine = undefined;
  9855. };
  9856. Scene.prototype.isPhysicsEnabled = function () {
  9857. return this._physicsEngine !== undefined;
  9858. };
  9859. Scene.prototype.setGravity = function (gravity) {
  9860. if (!this._physicsEngine) {
  9861. return;
  9862. }
  9863. this._physicsEngine._setGravity(gravity);
  9864. };
  9865. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9866. if (parts.parts) {
  9867. options = parts;
  9868. parts = parts.parts;
  9869. }
  9870. if (!this._physicsEngine) {
  9871. return null;
  9872. }
  9873. for (var index = 0; index < parts.length; index++) {
  9874. var mesh = parts[index].mesh;
  9875. mesh._physicImpostor = parts[index].impostor;
  9876. mesh._physicsMass = options.mass / parts.length;
  9877. mesh._physicsFriction = options.friction;
  9878. mesh._physicRestitution = options.restitution;
  9879. }
  9880. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9881. };
  9882. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9883. for (var index = 0; index < compound.parts.length; index++) {
  9884. var mesh = compound.parts[index].mesh;
  9885. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9886. this._physicsEngine._unregisterMesh(mesh);
  9887. }
  9888. };
  9889. // Misc.
  9890. Scene.prototype.createDefaultCameraOrLight = function () {
  9891. // Light
  9892. if (this.lights.length === 0) {
  9893. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9894. }
  9895. // Camera
  9896. if (!this.activeCamera) {
  9897. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9898. // Compute position
  9899. var worldExtends = this.getWorldExtends();
  9900. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9901. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9902. camera.setTarget(worldCenter);
  9903. this.activeCamera = camera;
  9904. }
  9905. };
  9906. // Tags
  9907. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9908. if (tagsQuery === undefined) {
  9909. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9910. return list;
  9911. }
  9912. var listByTags = [];
  9913. forEach = forEach || (function (item) {
  9914. return;
  9915. });
  9916. for (var i in list) {
  9917. var item = list[i];
  9918. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9919. listByTags.push(item);
  9920. forEach(item);
  9921. }
  9922. }
  9923. return listByTags;
  9924. };
  9925. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9926. return this._getByTags(this.meshes, tagsQuery, forEach);
  9927. };
  9928. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9929. return this._getByTags(this.cameras, tagsQuery, forEach);
  9930. };
  9931. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9932. return this._getByTags(this.lights, tagsQuery, forEach);
  9933. };
  9934. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9935. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9936. };
  9937. // Statics
  9938. Scene._FOGMODE_NONE = 0;
  9939. Scene._FOGMODE_EXP = 1;
  9940. Scene._FOGMODE_EXP2 = 2;
  9941. Scene._FOGMODE_LINEAR = 3;
  9942. Scene.MinDeltaTime = 1.0;
  9943. Scene.MaxDeltaTime = 1000.0;
  9944. return Scene;
  9945. })();
  9946. BABYLON.Scene = Scene;
  9947. })(BABYLON || (BABYLON = {}));
  9948. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9949. (function (BABYLON) {
  9950. var VertexBuffer = (function () {
  9951. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9952. if (engine instanceof BABYLON.Mesh) {
  9953. this._engine = engine.getScene().getEngine();
  9954. }
  9955. else {
  9956. this._engine = engine;
  9957. }
  9958. this._updatable = updatable;
  9959. this._data = data;
  9960. if (!postponeInternalCreation) {
  9961. this.create();
  9962. }
  9963. this._kind = kind;
  9964. if (stride) {
  9965. this._strideSize = stride;
  9966. return;
  9967. }
  9968. switch (kind) {
  9969. case VertexBuffer.PositionKind:
  9970. this._strideSize = 3;
  9971. break;
  9972. case VertexBuffer.NormalKind:
  9973. this._strideSize = 3;
  9974. break;
  9975. case VertexBuffer.UVKind:
  9976. this._strideSize = 2;
  9977. break;
  9978. case VertexBuffer.UV2Kind:
  9979. this._strideSize = 2;
  9980. break;
  9981. case VertexBuffer.ColorKind:
  9982. this._strideSize = 4;
  9983. break;
  9984. case VertexBuffer.MatricesIndicesKind:
  9985. this._strideSize = 4;
  9986. break;
  9987. case VertexBuffer.MatricesWeightsKind:
  9988. this._strideSize = 4;
  9989. break;
  9990. }
  9991. }
  9992. // Properties
  9993. VertexBuffer.prototype.isUpdatable = function () {
  9994. return this._updatable;
  9995. };
  9996. VertexBuffer.prototype.getData = function () {
  9997. return this._data;
  9998. };
  9999. VertexBuffer.prototype.getBuffer = function () {
  10000. return this._buffer;
  10001. };
  10002. VertexBuffer.prototype.getStrideSize = function () {
  10003. return this._strideSize;
  10004. };
  10005. // Methods
  10006. VertexBuffer.prototype.create = function (data) {
  10007. if (!data && this._buffer) {
  10008. return; // nothing to do
  10009. }
  10010. data = data || this._data;
  10011. if (!this._buffer) {
  10012. if (this._updatable) {
  10013. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  10014. }
  10015. else {
  10016. this._buffer = this._engine.createVertexBuffer(data);
  10017. }
  10018. }
  10019. if (this._updatable) {
  10020. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  10021. this._data = data;
  10022. }
  10023. };
  10024. VertexBuffer.prototype.update = function (data) {
  10025. this.create(data);
  10026. };
  10027. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  10028. if (!this._buffer) {
  10029. return;
  10030. }
  10031. if (this._updatable) {
  10032. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  10033. this._data = null;
  10034. }
  10035. };
  10036. VertexBuffer.prototype.dispose = function () {
  10037. if (!this._buffer) {
  10038. return;
  10039. }
  10040. if (this._engine._releaseBuffer(this._buffer)) {
  10041. this._buffer = null;
  10042. }
  10043. };
  10044. Object.defineProperty(VertexBuffer, "PositionKind", {
  10045. get: function () {
  10046. return VertexBuffer._PositionKind;
  10047. },
  10048. enumerable: true,
  10049. configurable: true
  10050. });
  10051. Object.defineProperty(VertexBuffer, "NormalKind", {
  10052. get: function () {
  10053. return VertexBuffer._NormalKind;
  10054. },
  10055. enumerable: true,
  10056. configurable: true
  10057. });
  10058. Object.defineProperty(VertexBuffer, "UVKind", {
  10059. get: function () {
  10060. return VertexBuffer._UVKind;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(VertexBuffer, "UV2Kind", {
  10066. get: function () {
  10067. return VertexBuffer._UV2Kind;
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Object.defineProperty(VertexBuffer, "ColorKind", {
  10073. get: function () {
  10074. return VertexBuffer._ColorKind;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  10080. get: function () {
  10081. return VertexBuffer._MatricesIndicesKind;
  10082. },
  10083. enumerable: true,
  10084. configurable: true
  10085. });
  10086. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  10087. get: function () {
  10088. return VertexBuffer._MatricesWeightsKind;
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. // Enums
  10094. VertexBuffer._PositionKind = "position";
  10095. VertexBuffer._NormalKind = "normal";
  10096. VertexBuffer._UVKind = "uv";
  10097. VertexBuffer._UV2Kind = "uv2";
  10098. VertexBuffer._ColorKind = "color";
  10099. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  10100. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  10101. return VertexBuffer;
  10102. })();
  10103. BABYLON.VertexBuffer = VertexBuffer;
  10104. })(BABYLON || (BABYLON = {}));
  10105. //# sourceMappingURL=babylon.vertexBuffer.js.map
  10106. var BABYLON;
  10107. (function (BABYLON) {
  10108. var AbstractMesh = (function (_super) {
  10109. __extends(AbstractMesh, _super);
  10110. function AbstractMesh(name, scene) {
  10111. _super.call(this, name, scene);
  10112. // Properties
  10113. this.definedFacingForward = true; // orientation for POV movement & rotation
  10114. this.position = new BABYLON.Vector3(0, 0, 0);
  10115. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10116. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10117. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10118. this.visibility = 1.0;
  10119. this.alphaIndex = Number.MAX_VALUE;
  10120. this.infiniteDistance = false;
  10121. this.isVisible = true;
  10122. this.isPickable = true;
  10123. this.showBoundingBox = false;
  10124. this.showSubMeshesBoundingBox = false;
  10125. this.onDispose = null;
  10126. this.checkCollisions = false;
  10127. this.isBlocker = false;
  10128. this.renderingGroupId = 0;
  10129. this.receiveShadows = false;
  10130. this.renderOutline = false;
  10131. this.outlineColor = BABYLON.Color3.Red();
  10132. this.outlineWidth = 0.02;
  10133. this.renderOverlay = false;
  10134. this.overlayColor = BABYLON.Color3.Red();
  10135. this.overlayAlpha = 0.5;
  10136. this.hasVertexAlpha = false;
  10137. this.useVertexColors = true;
  10138. this.applyFog = true;
  10139. this.useOctreeForRenderingSelection = true;
  10140. this.useOctreeForPicking = true;
  10141. this.useOctreeForCollisions = true;
  10142. this.layerMask = 0x0FFFFFFF;
  10143. this.alwaysSelectAsActiveMesh = false;
  10144. // Physics
  10145. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10146. // Collisions
  10147. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10148. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10149. this._collider = new BABYLON.Collider();
  10150. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10151. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10152. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10153. // Cache
  10154. this._localScaling = BABYLON.Matrix.Zero();
  10155. this._localRotation = BABYLON.Matrix.Zero();
  10156. this._localTranslation = BABYLON.Matrix.Zero();
  10157. this._localBillboard = BABYLON.Matrix.Zero();
  10158. this._localPivotScaling = BABYLON.Matrix.Zero();
  10159. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10160. this._localWorld = BABYLON.Matrix.Zero();
  10161. this._worldMatrix = BABYLON.Matrix.Zero();
  10162. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10163. this._absolutePosition = BABYLON.Vector3.Zero();
  10164. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10165. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10166. this._isDirty = false;
  10167. this._pivotMatrix = BABYLON.Matrix.Identity();
  10168. this._isDisposed = false;
  10169. this._renderId = 0;
  10170. this._intersectionsInProgress = new Array();
  10171. this._onAfterWorldMatrixUpdate = new Array();
  10172. this._isWorldMatrixFrozen = false;
  10173. scene.addMesh(this);
  10174. }
  10175. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10176. get: function () {
  10177. return AbstractMesh._BILLBOARDMODE_NONE;
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10183. get: function () {
  10184. return AbstractMesh._BILLBOARDMODE_X;
  10185. },
  10186. enumerable: true,
  10187. configurable: true
  10188. });
  10189. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10190. get: function () {
  10191. return AbstractMesh._BILLBOARDMODE_Y;
  10192. },
  10193. enumerable: true,
  10194. configurable: true
  10195. });
  10196. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10197. get: function () {
  10198. return AbstractMesh._BILLBOARDMODE_Z;
  10199. },
  10200. enumerable: true,
  10201. configurable: true
  10202. });
  10203. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10204. get: function () {
  10205. return AbstractMesh._BILLBOARDMODE_ALL;
  10206. },
  10207. enumerable: true,
  10208. configurable: true
  10209. });
  10210. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10211. // Methods
  10212. get: function () {
  10213. return false;
  10214. },
  10215. enumerable: true,
  10216. configurable: true
  10217. });
  10218. AbstractMesh.prototype.getLOD = function (camera) {
  10219. return this;
  10220. };
  10221. AbstractMesh.prototype.getTotalVertices = function () {
  10222. return 0;
  10223. };
  10224. AbstractMesh.prototype.getIndices = function () {
  10225. return null;
  10226. };
  10227. AbstractMesh.prototype.getVerticesData = function (kind) {
  10228. return null;
  10229. };
  10230. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10231. return false;
  10232. };
  10233. AbstractMesh.prototype.getBoundingInfo = function () {
  10234. if (this._masterMesh) {
  10235. return this._masterMesh.getBoundingInfo();
  10236. }
  10237. if (!this._boundingInfo) {
  10238. this._updateBoundingInfo();
  10239. }
  10240. return this._boundingInfo;
  10241. };
  10242. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10243. get: function () {
  10244. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10245. },
  10246. enumerable: true,
  10247. configurable: true
  10248. });
  10249. AbstractMesh.prototype._preActivate = function () {
  10250. };
  10251. AbstractMesh.prototype._activate = function (renderId) {
  10252. this._renderId = renderId;
  10253. };
  10254. AbstractMesh.prototype.getWorldMatrix = function () {
  10255. if (this._masterMesh) {
  10256. return this._masterMesh.getWorldMatrix();
  10257. }
  10258. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10259. this.computeWorldMatrix();
  10260. }
  10261. return this._worldMatrix;
  10262. };
  10263. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10264. get: function () {
  10265. return this._worldMatrix;
  10266. },
  10267. enumerable: true,
  10268. configurable: true
  10269. });
  10270. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10271. get: function () {
  10272. return this._absolutePosition;
  10273. },
  10274. enumerable: true,
  10275. configurable: true
  10276. });
  10277. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10278. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10279. this.computeWorldMatrix(true);
  10280. this._isWorldMatrixFrozen = true;
  10281. };
  10282. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10283. this._isWorldMatrixFrozen = false;
  10284. this.computeWorldMatrix(true);
  10285. };
  10286. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10287. get: function () {
  10288. return this._isWorldMatrixFrozen;
  10289. },
  10290. enumerable: true,
  10291. configurable: true
  10292. });
  10293. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10294. if (!this.rotationQuaternion) {
  10295. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10296. this.rotation = BABYLON.Vector3.Zero();
  10297. }
  10298. if (!space || space === 0 /* LOCAL */) {
  10299. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10300. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10301. }
  10302. else {
  10303. if (this.parent) {
  10304. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10305. invertParentWorldMatrix.invert();
  10306. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10307. }
  10308. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10309. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10310. }
  10311. };
  10312. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10313. var displacementVector = axis.scale(distance);
  10314. if (!space || space === 0 /* LOCAL */) {
  10315. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10316. this.setPositionWithLocalVector(tempV3);
  10317. }
  10318. else {
  10319. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10320. }
  10321. };
  10322. AbstractMesh.prototype.getAbsolutePosition = function () {
  10323. this.computeWorldMatrix();
  10324. return this._absolutePosition;
  10325. };
  10326. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10327. if (!absolutePosition) {
  10328. return;
  10329. }
  10330. var absolutePositionX;
  10331. var absolutePositionY;
  10332. var absolutePositionZ;
  10333. if (absolutePosition.x === undefined) {
  10334. if (arguments.length < 3) {
  10335. return;
  10336. }
  10337. absolutePositionX = arguments[0];
  10338. absolutePositionY = arguments[1];
  10339. absolutePositionZ = arguments[2];
  10340. }
  10341. else {
  10342. absolutePositionX = absolutePosition.x;
  10343. absolutePositionY = absolutePosition.y;
  10344. absolutePositionZ = absolutePosition.z;
  10345. }
  10346. if (this.parent) {
  10347. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10348. invertParentWorldMatrix.invert();
  10349. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10350. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10351. }
  10352. else {
  10353. this.position.x = absolutePositionX;
  10354. this.position.y = absolutePositionY;
  10355. this.position.z = absolutePositionZ;
  10356. }
  10357. };
  10358. // ================================== Point of View Movement =================================
  10359. /**
  10360. * Perform relative position change from the point of view of behind the front of the mesh.
  10361. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10362. * Supports definition of mesh facing forward or backward.
  10363. * @param {number} amountRight
  10364. * @param {number} amountUp
  10365. * @param {number} amountForward
  10366. */
  10367. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10368. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10369. };
  10370. /**
  10371. * Calculate relative position change from the point of view of behind the front of the mesh.
  10372. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10373. * Supports definition of mesh facing forward or backward.
  10374. * @param {number} amountRight
  10375. * @param {number} amountUp
  10376. * @param {number} amountForward
  10377. */
  10378. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10379. var rotMatrix = new BABYLON.Matrix();
  10380. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10381. rotQuaternion.toRotationMatrix(rotMatrix);
  10382. var translationDelta = BABYLON.Vector3.Zero();
  10383. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10384. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10385. return translationDelta;
  10386. };
  10387. // ================================== Point of View Rotation =================================
  10388. /**
  10389. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10390. * Supports definition of mesh facing forward or backward.
  10391. * @param {number} flipBack
  10392. * @param {number} twirlClockwise
  10393. * @param {number} tiltRight
  10394. */
  10395. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10396. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10397. };
  10398. /**
  10399. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10400. * Supports definition of mesh facing forward or backward.
  10401. * @param {number} flipBack
  10402. * @param {number} twirlClockwise
  10403. * @param {number} tiltRight
  10404. */
  10405. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10406. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10407. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10408. };
  10409. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10410. this._pivotMatrix = matrix;
  10411. this._cache.pivotMatrixUpdated = true;
  10412. };
  10413. AbstractMesh.prototype.getPivotMatrix = function () {
  10414. return this._pivotMatrix;
  10415. };
  10416. AbstractMesh.prototype._isSynchronized = function () {
  10417. if (this._isDirty) {
  10418. return false;
  10419. }
  10420. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10421. return false;
  10422. if (this._cache.pivotMatrixUpdated) {
  10423. return false;
  10424. }
  10425. if (this.infiniteDistance) {
  10426. return false;
  10427. }
  10428. if (!this._cache.position.equals(this.position))
  10429. return false;
  10430. if (this.rotationQuaternion) {
  10431. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10432. return false;
  10433. }
  10434. else {
  10435. if (!this._cache.rotation.equals(this.rotation))
  10436. return false;
  10437. }
  10438. if (!this._cache.scaling.equals(this.scaling))
  10439. return false;
  10440. return true;
  10441. };
  10442. AbstractMesh.prototype._initCache = function () {
  10443. _super.prototype._initCache.call(this);
  10444. this._cache.localMatrixUpdated = false;
  10445. this._cache.position = BABYLON.Vector3.Zero();
  10446. this._cache.scaling = BABYLON.Vector3.Zero();
  10447. this._cache.rotation = BABYLON.Vector3.Zero();
  10448. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10449. };
  10450. AbstractMesh.prototype.markAsDirty = function (property) {
  10451. if (property === "rotation") {
  10452. this.rotationQuaternion = null;
  10453. }
  10454. this._currentRenderId = Number.MAX_VALUE;
  10455. this._isDirty = true;
  10456. };
  10457. AbstractMesh.prototype._updateBoundingInfo = function () {
  10458. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10459. this._boundingInfo._update(this.worldMatrixFromCache);
  10460. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10461. };
  10462. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10463. if (!this.subMeshes) {
  10464. return;
  10465. }
  10466. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10467. var subMesh = this.subMeshes[subIndex];
  10468. subMesh.updateBoundingInfo(matrix);
  10469. }
  10470. };
  10471. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10472. if (this._isWorldMatrixFrozen) {
  10473. return this._worldMatrix;
  10474. }
  10475. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10476. return this._worldMatrix;
  10477. }
  10478. this._cache.position.copyFrom(this.position);
  10479. this._cache.scaling.copyFrom(this.scaling);
  10480. this._cache.pivotMatrixUpdated = false;
  10481. this._currentRenderId = this.getScene().getRenderId();
  10482. this._isDirty = false;
  10483. // Scaling
  10484. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10485. // Rotation
  10486. if (this.rotationQuaternion) {
  10487. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10488. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10489. }
  10490. else {
  10491. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10492. this._cache.rotation.copyFrom(this.rotation);
  10493. }
  10494. // Translation
  10495. if (this.infiniteDistance && !this.parent) {
  10496. var camera = this.getScene().activeCamera;
  10497. var cameraWorldMatrix = camera.getWorldMatrix();
  10498. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10499. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10500. }
  10501. else {
  10502. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10503. }
  10504. // Composing transformations
  10505. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10506. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10507. // Billboarding
  10508. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10509. var localPosition = this.position.clone();
  10510. var zero = this.getScene().activeCamera.globalPosition.clone();
  10511. if (this.parent && this.parent.position) {
  10512. localPosition.addInPlace(this.parent.position);
  10513. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10514. }
  10515. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  10516. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10517. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10518. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10519. zero.y = localPosition.y + 0.001;
  10520. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10521. zero.z = localPosition.z + 0.001;
  10522. }
  10523. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10524. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10525. this._localBillboard.invert();
  10526. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10527. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10528. }
  10529. // Local world
  10530. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10531. // Parent
  10532. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10533. this._markSyncedWithParent();
  10534. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10535. }
  10536. else {
  10537. this._worldMatrix.copyFrom(this._localWorld);
  10538. }
  10539. // Bounding info
  10540. this._updateBoundingInfo();
  10541. // Absolute position
  10542. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10543. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10544. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10545. }
  10546. return this._worldMatrix;
  10547. };
  10548. /**
  10549. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10550. * @param func: callback function to add
  10551. */
  10552. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10553. this._onAfterWorldMatrixUpdate.push(func);
  10554. };
  10555. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10556. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10557. if (index > -1) {
  10558. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10559. }
  10560. };
  10561. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10562. this.computeWorldMatrix();
  10563. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10564. };
  10565. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10566. this.computeWorldMatrix();
  10567. var invLocalWorldMatrix = this._localWorld.clone();
  10568. invLocalWorldMatrix.invert();
  10569. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10570. };
  10571. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10572. this.computeWorldMatrix();
  10573. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10574. };
  10575. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10576. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10577. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10578. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10579. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10580. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10581. /// <returns>Mesh oriented towards targetMesh</returns>
  10582. yawCor = yawCor || 0; // default to zero if undefined
  10583. pitchCor = pitchCor || 0;
  10584. rollCor = rollCor || 0;
  10585. var dv = targetPoint.subtract(this.position);
  10586. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10587. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10588. var pitch = Math.atan2(dv.y, len);
  10589. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10590. };
  10591. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10592. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10593. return false;
  10594. }
  10595. return true;
  10596. };
  10597. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10598. if (!camera) {
  10599. camera = this.getScene().activeCamera;
  10600. }
  10601. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10602. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10603. return false;
  10604. }
  10605. return true;
  10606. };
  10607. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10608. if (!this._boundingInfo || !mesh._boundingInfo) {
  10609. return false;
  10610. }
  10611. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10612. };
  10613. AbstractMesh.prototype.intersectsPoint = function (point) {
  10614. if (!this._boundingInfo) {
  10615. return false;
  10616. }
  10617. return this._boundingInfo.intersectsPoint(point);
  10618. };
  10619. // Physics
  10620. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10621. var physicsEngine = this.getScene().getPhysicsEngine();
  10622. if (!physicsEngine) {
  10623. return;
  10624. }
  10625. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10626. if (impostor.impostor) {
  10627. // Old API
  10628. options = impostor;
  10629. impostor = impostor.impostor;
  10630. }
  10631. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10632. physicsEngine._unregisterMesh(this);
  10633. return;
  10634. }
  10635. if (!options) {
  10636. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10637. }
  10638. else {
  10639. if (!options.mass && options.mass !== 0)
  10640. options.mass = 0;
  10641. if (!options.friction && options.friction !== 0)
  10642. options.friction = 0.2;
  10643. if (!options.restitution && options.restitution !== 0)
  10644. options.restitution = 0.2;
  10645. }
  10646. this._physicImpostor = impostor;
  10647. this._physicsMass = options.mass;
  10648. this._physicsFriction = options.friction;
  10649. this._physicRestitution = options.restitution;
  10650. return physicsEngine._registerMesh(this, impostor, options);
  10651. };
  10652. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10653. if (!this._physicImpostor) {
  10654. return BABYLON.PhysicsEngine.NoImpostor;
  10655. }
  10656. return this._physicImpostor;
  10657. };
  10658. AbstractMesh.prototype.getPhysicsMass = function () {
  10659. if (!this._physicsMass) {
  10660. return 0;
  10661. }
  10662. return this._physicsMass;
  10663. };
  10664. AbstractMesh.prototype.getPhysicsFriction = function () {
  10665. if (!this._physicsFriction) {
  10666. return 0;
  10667. }
  10668. return this._physicsFriction;
  10669. };
  10670. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10671. if (!this._physicRestitution) {
  10672. return 0;
  10673. }
  10674. return this._physicRestitution;
  10675. };
  10676. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10677. if (!camera) {
  10678. camera = this.getScene().activeCamera;
  10679. }
  10680. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10681. };
  10682. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10683. if (!camera) {
  10684. camera = this.getScene().activeCamera;
  10685. }
  10686. return this.absolutePosition.subtract(camera.position).length();
  10687. };
  10688. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10689. if (!this._physicImpostor) {
  10690. return;
  10691. }
  10692. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10693. };
  10694. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10695. if (!this._physicImpostor) {
  10696. return;
  10697. }
  10698. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10699. };
  10700. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10701. if (!this._physicImpostor) {
  10702. return;
  10703. }
  10704. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10705. };
  10706. // Collisions
  10707. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10708. var globalPosition = this.getAbsolutePosition();
  10709. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10710. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10711. this._collider.radius = this.ellipsoid;
  10712. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10713. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10714. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10715. this.position.addInPlace(this._diffPositionForCollisions);
  10716. }
  10717. };
  10718. // Submeshes octree
  10719. /**
  10720. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10721. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10722. */
  10723. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10724. if (maxCapacity === void 0) { maxCapacity = 64; }
  10725. if (maxDepth === void 0) { maxDepth = 2; }
  10726. if (!this._submeshesOctree) {
  10727. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10728. }
  10729. this.computeWorldMatrix(true);
  10730. // Update octree
  10731. var bbox = this.getBoundingInfo().boundingBox;
  10732. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10733. return this._submeshesOctree;
  10734. };
  10735. // Collisions
  10736. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10737. this._generatePointsArray();
  10738. // Transformation
  10739. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10740. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10741. subMesh._lastColliderWorldVertices = [];
  10742. subMesh._trianglePlanes = [];
  10743. var start = subMesh.verticesStart;
  10744. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10745. for (var i = start; i < end; i++) {
  10746. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10747. }
  10748. }
  10749. // Collide
  10750. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10751. };
  10752. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10753. var subMeshes;
  10754. var len;
  10755. // Octrees
  10756. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10757. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10758. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10759. len = intersections.length;
  10760. subMeshes = intersections.data;
  10761. }
  10762. else {
  10763. subMeshes = this.subMeshes;
  10764. len = subMeshes.length;
  10765. }
  10766. for (var index = 0; index < len; index++) {
  10767. var subMesh = subMeshes[index];
  10768. // Bounding test
  10769. if (len > 1 && !subMesh._checkCollision(collider))
  10770. continue;
  10771. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10772. }
  10773. };
  10774. AbstractMesh.prototype._checkCollision = function (collider) {
  10775. // Bounding box test
  10776. if (!this._boundingInfo._checkCollision(collider))
  10777. return;
  10778. // Transformation matrix
  10779. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10780. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10781. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10782. };
  10783. // Picking
  10784. AbstractMesh.prototype._generatePointsArray = function () {
  10785. return false;
  10786. };
  10787. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10788. var pickingInfo = new BABYLON.PickingInfo();
  10789. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10790. return pickingInfo;
  10791. }
  10792. if (!this._generatePointsArray()) {
  10793. return pickingInfo;
  10794. }
  10795. var intersectInfo = null;
  10796. // Octrees
  10797. var subMeshes;
  10798. var len;
  10799. if (this._submeshesOctree && this.useOctreeForPicking) {
  10800. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10801. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10802. len = intersections.length;
  10803. subMeshes = intersections.data;
  10804. }
  10805. else {
  10806. subMeshes = this.subMeshes;
  10807. len = subMeshes.length;
  10808. }
  10809. for (var index = 0; index < len; index++) {
  10810. var subMesh = subMeshes[index];
  10811. // Bounding test
  10812. if (len > 1 && !subMesh.canIntersects(ray))
  10813. continue;
  10814. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10815. if (currentIntersectInfo) {
  10816. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10817. intersectInfo = currentIntersectInfo;
  10818. intersectInfo.subMeshId = index;
  10819. if (fastCheck) {
  10820. break;
  10821. }
  10822. }
  10823. }
  10824. }
  10825. if (intersectInfo) {
  10826. // Get picked point
  10827. var world = this.getWorldMatrix();
  10828. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10829. var direction = ray.direction.clone();
  10830. direction = direction.scale(intersectInfo.distance);
  10831. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10832. var pickedPoint = worldOrigin.add(worldDirection);
  10833. // Return result
  10834. pickingInfo.hit = true;
  10835. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10836. pickingInfo.pickedPoint = pickedPoint;
  10837. pickingInfo.pickedMesh = this;
  10838. pickingInfo.bu = intersectInfo.bu;
  10839. pickingInfo.bv = intersectInfo.bv;
  10840. pickingInfo.faceId = intersectInfo.faceId;
  10841. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10842. return pickingInfo;
  10843. }
  10844. return pickingInfo;
  10845. };
  10846. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10847. return null;
  10848. };
  10849. AbstractMesh.prototype.releaseSubMeshes = function () {
  10850. if (this.subMeshes) {
  10851. while (this.subMeshes.length) {
  10852. this.subMeshes[0].dispose();
  10853. }
  10854. }
  10855. else {
  10856. this.subMeshes = new Array();
  10857. }
  10858. };
  10859. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10860. var index;
  10861. // Physics
  10862. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10863. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10864. }
  10865. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10866. var other = this._intersectionsInProgress[index];
  10867. var pos = other._intersectionsInProgress.indexOf(this);
  10868. other._intersectionsInProgress.splice(pos, 1);
  10869. }
  10870. this._intersectionsInProgress = [];
  10871. // SubMeshes
  10872. this.releaseSubMeshes();
  10873. // Remove from scene
  10874. this.getScene().removeMesh(this);
  10875. if (!doNotRecurse) {
  10876. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10877. if (this.getScene().particleSystems[index].emitter === this) {
  10878. this.getScene().particleSystems[index].dispose();
  10879. index--;
  10880. }
  10881. }
  10882. // Children
  10883. var objects = this.getScene().meshes.slice(0);
  10884. for (index = 0; index < objects.length; index++) {
  10885. if (objects[index].parent === this) {
  10886. objects[index].dispose();
  10887. }
  10888. }
  10889. }
  10890. else {
  10891. for (index = 0; index < this.getScene().meshes.length; index++) {
  10892. var obj = this.getScene().meshes[index];
  10893. if (obj.parent === this) {
  10894. obj.parent = null;
  10895. obj.computeWorldMatrix(true);
  10896. }
  10897. }
  10898. }
  10899. this._onAfterWorldMatrixUpdate = [];
  10900. this._isDisposed = true;
  10901. // Callback
  10902. if (this.onDispose) {
  10903. this.onDispose();
  10904. }
  10905. };
  10906. // Statics
  10907. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10908. AbstractMesh._BILLBOARDMODE_X = 1;
  10909. AbstractMesh._BILLBOARDMODE_Y = 2;
  10910. AbstractMesh._BILLBOARDMODE_Z = 4;
  10911. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10912. return AbstractMesh;
  10913. })(BABYLON.Node);
  10914. BABYLON.AbstractMesh = AbstractMesh;
  10915. })(BABYLON || (BABYLON = {}));
  10916. //# sourceMappingURL=babylon.abstractMesh.js.map
  10917. var BABYLON;
  10918. (function (BABYLON) {
  10919. var _InstancesBatch = (function () {
  10920. function _InstancesBatch() {
  10921. this.mustReturn = false;
  10922. this.visibleInstances = new Array();
  10923. this.renderSelf = new Array();
  10924. }
  10925. return _InstancesBatch;
  10926. })();
  10927. BABYLON._InstancesBatch = _InstancesBatch;
  10928. var Mesh = (function (_super) {
  10929. __extends(Mesh, _super);
  10930. /**
  10931. * @constructor
  10932. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10933. * @param {Scene} scene - The scene to add this mesh to.
  10934. * @param {Node} parent - The parent of this mesh, if it has one
  10935. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10936. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10937. * When false, achieved by calling a clone(), also passing False.
  10938. * This will make creation of children, recursive.
  10939. */
  10940. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10941. if (parent === void 0) { parent = null; }
  10942. _super.call(this, name, scene);
  10943. // Members
  10944. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10945. this.instances = new Array();
  10946. this._LODLevels = new Array();
  10947. this._onBeforeRenderCallbacks = new Array();
  10948. this._onAfterRenderCallbacks = new Array();
  10949. this._visibleInstances = {};
  10950. this._renderIdForInstances = new Array();
  10951. this._batchCache = new _InstancesBatch();
  10952. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10953. this._sideOrientation = Mesh._DEFAULTSIDE;
  10954. if (source) {
  10955. // Geometry
  10956. if (source._geometry) {
  10957. source._geometry.applyToMesh(this);
  10958. }
  10959. // Deep copy
  10960. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  10961. // Material
  10962. this.material = source.material;
  10963. if (!doNotCloneChildren) {
  10964. for (var index = 0; index < scene.meshes.length; index++) {
  10965. var mesh = scene.meshes[index];
  10966. if (mesh.parent === source) {
  10967. // doNotCloneChildren is always going to be False
  10968. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10969. }
  10970. }
  10971. }
  10972. for (index = 0; index < scene.particleSystems.length; index++) {
  10973. var system = scene.particleSystems[index];
  10974. if (system.emitter === source) {
  10975. system.clone(system.name, this);
  10976. }
  10977. }
  10978. this.computeWorldMatrix(true);
  10979. }
  10980. // Parent
  10981. if (parent !== null) {
  10982. this.parent = parent;
  10983. }
  10984. }
  10985. Object.defineProperty(Mesh, "FRONTSIDE", {
  10986. get: function () {
  10987. return Mesh._FRONTSIDE;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(Mesh, "BACKSIDE", {
  10993. get: function () {
  10994. return Mesh._BACKSIDE;
  10995. },
  10996. enumerable: true,
  10997. configurable: true
  10998. });
  10999. Object.defineProperty(Mesh, "DOUBLESIDE", {
  11000. get: function () {
  11001. return Mesh._DOUBLESIDE;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  11007. get: function () {
  11008. return Mesh._DEFAULTSIDE;
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  11014. // Methods
  11015. get: function () {
  11016. return this._LODLevels.length > 0;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Mesh.prototype._sortLODLevels = function () {
  11022. this._LODLevels.sort(function (a, b) {
  11023. if (a.distance < b.distance) {
  11024. return 1;
  11025. }
  11026. if (a.distance > b.distance) {
  11027. return -1;
  11028. }
  11029. return 0;
  11030. });
  11031. };
  11032. /**
  11033. * Add a mesh as LOD level triggered at the given distance.
  11034. * @param {number} distance - the distance from the center of the object to show this level
  11035. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  11036. * @return {BABYLON.Mesh} this mesh (for chaining)
  11037. */
  11038. Mesh.prototype.addLODLevel = function (distance, mesh) {
  11039. if (mesh && mesh._masterMesh) {
  11040. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  11041. return this;
  11042. }
  11043. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  11044. this._LODLevels.push(level);
  11045. if (mesh) {
  11046. mesh._masterMesh = this;
  11047. }
  11048. this._sortLODLevels();
  11049. return this;
  11050. };
  11051. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  11052. for (var index = 0; index < this._LODLevels.length; index++) {
  11053. var level = this._LODLevels[index];
  11054. if (level.distance === distance) {
  11055. return level.mesh;
  11056. }
  11057. }
  11058. return null;
  11059. };
  11060. /**
  11061. * Remove a mesh from the LOD array
  11062. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  11063. * @return {BABYLON.Mesh} this mesh (for chaining)
  11064. */
  11065. Mesh.prototype.removeLODLevel = function (mesh) {
  11066. for (var index = 0; index < this._LODLevels.length; index++) {
  11067. if (this._LODLevels[index].mesh === mesh) {
  11068. this._LODLevels.splice(index, 1);
  11069. if (mesh) {
  11070. mesh._masterMesh = null;
  11071. }
  11072. }
  11073. }
  11074. this._sortLODLevels();
  11075. return this;
  11076. };
  11077. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  11078. if (!this._LODLevels || this._LODLevels.length === 0) {
  11079. return this;
  11080. }
  11081. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  11082. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  11083. if (this.onLODLevelSelection) {
  11084. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  11085. }
  11086. return this;
  11087. }
  11088. for (var index = 0; index < this._LODLevels.length; index++) {
  11089. var level = this._LODLevels[index];
  11090. if (level.distance < distanceToCamera) {
  11091. if (level.mesh) {
  11092. level.mesh._preActivate();
  11093. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11094. }
  11095. if (this.onLODLevelSelection) {
  11096. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  11097. }
  11098. return level.mesh;
  11099. }
  11100. }
  11101. if (this.onLODLevelSelection) {
  11102. this.onLODLevelSelection(distanceToCamera, this, this);
  11103. }
  11104. return this;
  11105. };
  11106. Object.defineProperty(Mesh.prototype, "geometry", {
  11107. get: function () {
  11108. return this._geometry;
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. Mesh.prototype.getTotalVertices = function () {
  11114. if (!this._geometry) {
  11115. return 0;
  11116. }
  11117. return this._geometry.getTotalVertices();
  11118. };
  11119. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  11120. if (!this._geometry) {
  11121. return null;
  11122. }
  11123. return this._geometry.getVerticesData(kind, copyWhenShared);
  11124. };
  11125. Mesh.prototype.getVertexBuffer = function (kind) {
  11126. if (!this._geometry) {
  11127. return undefined;
  11128. }
  11129. return this._geometry.getVertexBuffer(kind);
  11130. };
  11131. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11132. if (!this._geometry) {
  11133. if (this._delayInfo) {
  11134. return this._delayInfo.indexOf(kind) !== -1;
  11135. }
  11136. return false;
  11137. }
  11138. return this._geometry.isVerticesDataPresent(kind);
  11139. };
  11140. Mesh.prototype.getVerticesDataKinds = function () {
  11141. if (!this._geometry) {
  11142. var result = [];
  11143. if (this._delayInfo) {
  11144. for (var kind in this._delayInfo) {
  11145. result.push(kind);
  11146. }
  11147. }
  11148. return result;
  11149. }
  11150. return this._geometry.getVerticesDataKinds();
  11151. };
  11152. Mesh.prototype.getTotalIndices = function () {
  11153. if (!this._geometry) {
  11154. return 0;
  11155. }
  11156. return this._geometry.getTotalIndices();
  11157. };
  11158. Mesh.prototype.getIndices = function (copyWhenShared) {
  11159. if (!this._geometry) {
  11160. return [];
  11161. }
  11162. return this._geometry.getIndices(copyWhenShared);
  11163. };
  11164. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11165. get: function () {
  11166. return this._masterMesh !== null && this._masterMesh !== undefined;
  11167. },
  11168. enumerable: true,
  11169. configurable: true
  11170. });
  11171. Mesh.prototype.isReady = function () {
  11172. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11173. return false;
  11174. }
  11175. return _super.prototype.isReady.call(this);
  11176. };
  11177. Mesh.prototype.isDisposed = function () {
  11178. return this._isDisposed;
  11179. };
  11180. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  11181. get: function () {
  11182. return this._sideOrientation;
  11183. },
  11184. set: function (sideO) {
  11185. this._sideOrientation = sideO;
  11186. },
  11187. enumerable: true,
  11188. configurable: true
  11189. });
  11190. // Methods
  11191. Mesh.prototype._preActivate = function () {
  11192. var sceneRenderId = this.getScene().getRenderId();
  11193. if (this._preActivateId === sceneRenderId) {
  11194. return;
  11195. }
  11196. this._preActivateId = sceneRenderId;
  11197. this._visibleInstances = null;
  11198. };
  11199. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11200. if (!this._visibleInstances) {
  11201. this._visibleInstances = {};
  11202. this._visibleInstances.defaultRenderId = renderId;
  11203. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11204. }
  11205. if (!this._visibleInstances[renderId]) {
  11206. this._visibleInstances[renderId] = new Array();
  11207. }
  11208. this._visibleInstances[renderId].push(instance);
  11209. };
  11210. Mesh.prototype.refreshBoundingInfo = function () {
  11211. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11212. if (data) {
  11213. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11214. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11215. }
  11216. if (this.subMeshes) {
  11217. for (var index = 0; index < this.subMeshes.length; index++) {
  11218. this.subMeshes[index].refreshBoundingInfo();
  11219. }
  11220. }
  11221. this._updateBoundingInfo();
  11222. };
  11223. Mesh.prototype._createGlobalSubMesh = function () {
  11224. var totalVertices = this.getTotalVertices();
  11225. if (!totalVertices || !this.getIndices()) {
  11226. return null;
  11227. }
  11228. this.releaseSubMeshes();
  11229. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11230. };
  11231. Mesh.prototype.subdivide = function (count) {
  11232. if (count < 1) {
  11233. return;
  11234. }
  11235. var totalIndices = this.getTotalIndices();
  11236. var subdivisionSize = (totalIndices / count) | 0;
  11237. var offset = 0;
  11238. while (subdivisionSize % 3 !== 0) {
  11239. subdivisionSize++;
  11240. }
  11241. this.releaseSubMeshes();
  11242. for (var index = 0; index < count; index++) {
  11243. if (offset >= totalIndices) {
  11244. break;
  11245. }
  11246. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11247. offset += subdivisionSize;
  11248. }
  11249. this.synchronizeInstances();
  11250. };
  11251. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11252. if (kind instanceof Array) {
  11253. var temp = data;
  11254. data = kind;
  11255. kind = temp;
  11256. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11257. }
  11258. if (!this._geometry) {
  11259. var vertexData = new BABYLON.VertexData();
  11260. vertexData.set(data, kind);
  11261. var scene = this.getScene();
  11262. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11263. }
  11264. else {
  11265. this._geometry.setVerticesData(kind, data, updatable, stride);
  11266. }
  11267. };
  11268. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11269. if (!this._geometry) {
  11270. return;
  11271. }
  11272. if (!makeItUnique) {
  11273. this._geometry.updateVerticesData(kind, data, updateExtends);
  11274. }
  11275. else {
  11276. this.makeGeometryUnique();
  11277. this.updateVerticesData(kind, data, updateExtends, false);
  11278. }
  11279. };
  11280. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11281. if (!this._geometry) {
  11282. return;
  11283. }
  11284. if (!makeItUnique) {
  11285. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11286. }
  11287. else {
  11288. this.makeGeometryUnique();
  11289. this.updateVerticesDataDirectly(kind, data, offset, false);
  11290. }
  11291. };
  11292. // Mesh positions update function :
  11293. // updates the mesh positions according to the positionFunction returned values.
  11294. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  11295. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  11296. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  11297. if (computeNormals === void 0) { computeNormals = true; }
  11298. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11299. positionFunction(positions);
  11300. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  11301. if (computeNormals) {
  11302. var indices = this.getIndices();
  11303. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11304. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  11305. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  11306. }
  11307. };
  11308. Mesh.prototype.makeGeometryUnique = function () {
  11309. if (!this._geometry) {
  11310. return;
  11311. }
  11312. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11313. geometry.applyToMesh(this);
  11314. };
  11315. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11316. if (!this._geometry) {
  11317. var vertexData = new BABYLON.VertexData();
  11318. vertexData.indices = indices;
  11319. var scene = this.getScene();
  11320. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11321. }
  11322. else {
  11323. this._geometry.setIndices(indices, totalVertices);
  11324. }
  11325. };
  11326. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11327. var engine = this.getScene().getEngine();
  11328. // Wireframe
  11329. var indexToBind;
  11330. switch (fillMode) {
  11331. case BABYLON.Material.PointFillMode:
  11332. indexToBind = null;
  11333. break;
  11334. case BABYLON.Material.WireFrameFillMode:
  11335. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11336. break;
  11337. default:
  11338. case BABYLON.Material.TriangleFillMode:
  11339. indexToBind = this._geometry.getIndexBuffer();
  11340. break;
  11341. }
  11342. // VBOs
  11343. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11344. };
  11345. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11346. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11347. return;
  11348. }
  11349. var engine = this.getScene().getEngine();
  11350. switch (fillMode) {
  11351. case BABYLON.Material.PointFillMode:
  11352. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11353. break;
  11354. case BABYLON.Material.WireFrameFillMode:
  11355. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11356. break;
  11357. default:
  11358. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11359. }
  11360. };
  11361. Mesh.prototype.registerBeforeRender = function (func) {
  11362. this._onBeforeRenderCallbacks.push(func);
  11363. };
  11364. Mesh.prototype.unregisterBeforeRender = function (func) {
  11365. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11366. if (index > -1) {
  11367. this._onBeforeRenderCallbacks.splice(index, 1);
  11368. }
  11369. };
  11370. Mesh.prototype.registerAfterRender = function (func) {
  11371. this._onAfterRenderCallbacks.push(func);
  11372. };
  11373. Mesh.prototype.unregisterAfterRender = function (func) {
  11374. var index = this._onAfterRenderCallbacks.indexOf(func);
  11375. if (index > -1) {
  11376. this._onAfterRenderCallbacks.splice(index, 1);
  11377. }
  11378. };
  11379. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11380. var scene = this.getScene();
  11381. this._batchCache.mustReturn = false;
  11382. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11383. this._batchCache.visibleInstances[subMeshId] = null;
  11384. if (this._visibleInstances) {
  11385. var currentRenderId = scene.getRenderId();
  11386. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11387. var selfRenderId = this._renderId;
  11388. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11389. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11390. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11391. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11392. }
  11393. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11394. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11395. this._batchCache.mustReturn = true;
  11396. return this._batchCache;
  11397. }
  11398. if (currentRenderId !== selfRenderId) {
  11399. this._batchCache.renderSelf[subMeshId] = false;
  11400. }
  11401. }
  11402. this._renderIdForInstances[subMeshId] = currentRenderId;
  11403. }
  11404. return this._batchCache;
  11405. };
  11406. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11407. var visibleInstances = batch.visibleInstances[subMesh._id];
  11408. var matricesCount = visibleInstances.length + 1;
  11409. var bufferSize = matricesCount * 16 * 4;
  11410. while (this._instancesBufferSize < bufferSize) {
  11411. this._instancesBufferSize *= 2;
  11412. }
  11413. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11414. if (this._worldMatricesInstancesBuffer) {
  11415. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11416. }
  11417. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11418. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11419. }
  11420. var offset = 0;
  11421. var instancesCount = 0;
  11422. var world = this.getWorldMatrix();
  11423. if (batch.renderSelf[subMesh._id]) {
  11424. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11425. offset += 16;
  11426. instancesCount++;
  11427. }
  11428. if (visibleInstances) {
  11429. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11430. var instance = visibleInstances[instanceIndex];
  11431. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11432. offset += 16;
  11433. instancesCount++;
  11434. }
  11435. }
  11436. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11437. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11438. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11439. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11440. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11441. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11442. this._draw(subMesh, fillMode, instancesCount);
  11443. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11444. };
  11445. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11446. var scene = this.getScene();
  11447. var engine = scene.getEngine();
  11448. if (hardwareInstancedRendering) {
  11449. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11450. }
  11451. else {
  11452. if (batch.renderSelf[subMesh._id]) {
  11453. // Draw
  11454. if (onBeforeDraw) {
  11455. onBeforeDraw(false, this.getWorldMatrix());
  11456. }
  11457. this._draw(subMesh, fillMode);
  11458. }
  11459. if (batch.visibleInstances[subMesh._id]) {
  11460. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11461. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11462. // World
  11463. var world = instance.getWorldMatrix();
  11464. if (onBeforeDraw) {
  11465. onBeforeDraw(true, world);
  11466. }
  11467. // Draw
  11468. this._draw(subMesh, fillMode);
  11469. }
  11470. }
  11471. }
  11472. };
  11473. Mesh.prototype.render = function (subMesh) {
  11474. var scene = this.getScene();
  11475. // Managing instances
  11476. var batch = this._getInstancesRenderList(subMesh._id);
  11477. if (batch.mustReturn) {
  11478. return;
  11479. }
  11480. // Checking geometry state
  11481. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11482. return;
  11483. }
  11484. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11485. this._onBeforeRenderCallbacks[callbackIndex](this);
  11486. }
  11487. var engine = scene.getEngine();
  11488. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11489. // Material
  11490. var effectiveMaterial = subMesh.getMaterial();
  11491. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11492. return;
  11493. }
  11494. // Outline - step 1
  11495. var savedDepthWrite = engine.getDepthWrite();
  11496. if (this.renderOutline) {
  11497. engine.setDepthWrite(false);
  11498. scene.getOutlineRenderer().render(subMesh, batch);
  11499. engine.setDepthWrite(savedDepthWrite);
  11500. }
  11501. effectiveMaterial._preBind();
  11502. var effect = effectiveMaterial.getEffect();
  11503. // Bind
  11504. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11505. this._bind(subMesh, effect, fillMode);
  11506. var world = this.getWorldMatrix();
  11507. effectiveMaterial.bind(world, this);
  11508. // Draw
  11509. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11510. if (isInstance) {
  11511. effectiveMaterial.bindOnlyWorldMatrix(world);
  11512. }
  11513. });
  11514. // Unbind
  11515. effectiveMaterial.unbind();
  11516. // Outline - step 2
  11517. if (this.renderOutline && savedDepthWrite) {
  11518. engine.setDepthWrite(true);
  11519. engine.setColorWrite(false);
  11520. scene.getOutlineRenderer().render(subMesh, batch);
  11521. engine.setColorWrite(true);
  11522. }
  11523. // Overlay
  11524. if (this.renderOverlay) {
  11525. var currentMode = engine.getAlphaMode();
  11526. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11527. scene.getOutlineRenderer().render(subMesh, batch, true);
  11528. engine.setAlphaMode(currentMode);
  11529. }
  11530. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11531. this._onAfterRenderCallbacks[callbackIndex](this);
  11532. }
  11533. };
  11534. Mesh.prototype.getEmittedParticleSystems = function () {
  11535. var results = new Array();
  11536. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11537. var particleSystem = this.getScene().particleSystems[index];
  11538. if (particleSystem.emitter === this) {
  11539. results.push(particleSystem);
  11540. }
  11541. }
  11542. return results;
  11543. };
  11544. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11545. var results = new Array();
  11546. var descendants = this.getDescendants();
  11547. descendants.push(this);
  11548. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11549. var particleSystem = this.getScene().particleSystems[index];
  11550. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11551. results.push(particleSystem);
  11552. }
  11553. }
  11554. return results;
  11555. };
  11556. Mesh.prototype.getChildren = function () {
  11557. var results = [];
  11558. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11559. var mesh = this.getScene().meshes[index];
  11560. if (mesh.parent === this) {
  11561. results.push(mesh);
  11562. }
  11563. }
  11564. return results;
  11565. };
  11566. Mesh.prototype._checkDelayState = function () {
  11567. var _this = this;
  11568. var that = this;
  11569. var scene = this.getScene();
  11570. if (this._geometry) {
  11571. this._geometry.load(scene);
  11572. }
  11573. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11574. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11575. scene._addPendingData(that);
  11576. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11577. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11578. if (data instanceof ArrayBuffer) {
  11579. _this._delayLoadingFunction(data, _this);
  11580. }
  11581. else {
  11582. _this._delayLoadingFunction(JSON.parse(data), _this);
  11583. }
  11584. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11585. scene._removePendingData(_this);
  11586. }, function () {
  11587. }, scene.database, getBinaryData);
  11588. }
  11589. };
  11590. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11591. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11592. return false;
  11593. }
  11594. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11595. return false;
  11596. }
  11597. this._checkDelayState();
  11598. return true;
  11599. };
  11600. Mesh.prototype.setMaterialByID = function (id) {
  11601. var materials = this.getScene().materials;
  11602. for (var index = 0; index < materials.length; index++) {
  11603. if (materials[index].id === id) {
  11604. this.material = materials[index];
  11605. return;
  11606. }
  11607. }
  11608. // Multi
  11609. var multiMaterials = this.getScene().multiMaterials;
  11610. for (index = 0; index < multiMaterials.length; index++) {
  11611. if (multiMaterials[index].id === id) {
  11612. this.material = multiMaterials[index];
  11613. return;
  11614. }
  11615. }
  11616. };
  11617. Mesh.prototype.getAnimatables = function () {
  11618. var results = [];
  11619. if (this.material) {
  11620. results.push(this.material);
  11621. }
  11622. if (this.skeleton) {
  11623. results.push(this.skeleton);
  11624. }
  11625. return results;
  11626. };
  11627. // Geometry
  11628. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11629. // Position
  11630. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11631. return;
  11632. }
  11633. this._resetPointsArrayCache();
  11634. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11635. var temp = [];
  11636. for (var index = 0; index < data.length; index += 3) {
  11637. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11638. }
  11639. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11640. // Normals
  11641. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11642. return;
  11643. }
  11644. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11645. temp = [];
  11646. for (index = 0; index < data.length; index += 3) {
  11647. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11648. }
  11649. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11650. };
  11651. // Cache
  11652. Mesh.prototype._resetPointsArrayCache = function () {
  11653. this._positions = null;
  11654. };
  11655. Mesh.prototype._generatePointsArray = function () {
  11656. if (this._positions)
  11657. return true;
  11658. this._positions = [];
  11659. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11660. if (!data) {
  11661. return false;
  11662. }
  11663. for (var index = 0; index < data.length; index += 3) {
  11664. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11665. }
  11666. return true;
  11667. };
  11668. // Clone
  11669. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11670. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11671. };
  11672. // Dispose
  11673. Mesh.prototype.dispose = function (doNotRecurse) {
  11674. if (this._geometry) {
  11675. this._geometry.releaseForMesh(this, true);
  11676. }
  11677. // Instances
  11678. if (this._worldMatricesInstancesBuffer) {
  11679. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11680. this._worldMatricesInstancesBuffer = null;
  11681. }
  11682. while (this.instances.length) {
  11683. this.instances[0].dispose();
  11684. }
  11685. _super.prototype.dispose.call(this, doNotRecurse);
  11686. };
  11687. // Geometric tools
  11688. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11689. var _this = this;
  11690. var scene = this.getScene();
  11691. var onload = function (img) {
  11692. // Getting height map data
  11693. var canvas = document.createElement("canvas");
  11694. var context = canvas.getContext("2d");
  11695. var heightMapWidth = img.width;
  11696. var heightMapHeight = img.height;
  11697. canvas.width = heightMapWidth;
  11698. canvas.height = heightMapHeight;
  11699. context.drawImage(img, 0, 0);
  11700. // Create VertexData from map data
  11701. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11702. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11703. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11704. //execute success callback, if set
  11705. if (onSuccess) {
  11706. onSuccess(_this);
  11707. }
  11708. };
  11709. BABYLON.Tools.LoadImage(url, onload, function () {
  11710. }, scene.database);
  11711. };
  11712. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11713. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11714. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11715. return;
  11716. }
  11717. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11718. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11719. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11720. var position = BABYLON.Vector3.Zero();
  11721. var normal = BABYLON.Vector3.Zero();
  11722. var uv = BABYLON.Vector2.Zero();
  11723. for (var index = 0; index < positions.length; index += 3) {
  11724. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11725. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11726. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11727. // Compute height
  11728. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11729. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11730. var pos = (u + v * heightMapWidth) * 4;
  11731. var r = buffer[pos] / 255.0;
  11732. var g = buffer[pos + 1] / 255.0;
  11733. var b = buffer[pos + 2] / 255.0;
  11734. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11735. normal.normalize();
  11736. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11737. position = position.add(normal);
  11738. position.toArray(positions, index);
  11739. }
  11740. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11741. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11742. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11743. };
  11744. Mesh.prototype.convertToFlatShadedMesh = function () {
  11745. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11746. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11747. var kinds = this.getVerticesDataKinds();
  11748. var vbs = [];
  11749. var data = [];
  11750. var newdata = [];
  11751. var updatableNormals = false;
  11752. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11753. var kind = kinds[kindIndex];
  11754. var vertexBuffer = this.getVertexBuffer(kind);
  11755. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11756. updatableNormals = vertexBuffer.isUpdatable();
  11757. kinds.splice(kindIndex, 1);
  11758. kindIndex--;
  11759. continue;
  11760. }
  11761. vbs[kind] = vertexBuffer;
  11762. data[kind] = vbs[kind].getData();
  11763. newdata[kind] = [];
  11764. }
  11765. // Save previous submeshes
  11766. var previousSubmeshes = this.subMeshes.slice(0);
  11767. var indices = this.getIndices();
  11768. var totalIndices = this.getTotalIndices();
  11769. for (var index = 0; index < totalIndices; index++) {
  11770. var vertexIndex = indices[index];
  11771. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11772. kind = kinds[kindIndex];
  11773. var stride = vbs[kind].getStrideSize();
  11774. for (var offset = 0; offset < stride; offset++) {
  11775. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11776. }
  11777. }
  11778. }
  11779. // Updating faces & normal
  11780. var normals = [];
  11781. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11782. for (index = 0; index < totalIndices; index += 3) {
  11783. indices[index] = index;
  11784. indices[index + 1] = index + 1;
  11785. indices[index + 2] = index + 2;
  11786. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11787. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11788. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11789. var p1p2 = p1.subtract(p2);
  11790. var p3p2 = p3.subtract(p2);
  11791. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11792. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11793. normals.push(normal.x);
  11794. normals.push(normal.y);
  11795. normals.push(normal.z);
  11796. }
  11797. }
  11798. this.setIndices(indices);
  11799. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11800. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11801. kind = kinds[kindIndex];
  11802. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11803. }
  11804. // Updating submeshes
  11805. this.releaseSubMeshes();
  11806. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11807. var previousOne = previousSubmeshes[submeshIndex];
  11808. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11809. }
  11810. this.synchronizeInstances();
  11811. };
  11812. // Instances
  11813. Mesh.prototype.createInstance = function (name) {
  11814. return new BABYLON.InstancedMesh(name, this);
  11815. };
  11816. Mesh.prototype.synchronizeInstances = function () {
  11817. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11818. var instance = this.instances[instanceIndex];
  11819. instance._syncSubMeshes();
  11820. }
  11821. };
  11822. /**
  11823. * Simplify the mesh according to the given array of settings.
  11824. * Function will return immediately and will simplify async.
  11825. * @param settings a collection of simplification settings.
  11826. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11827. * @param type the type of simplification to run.
  11828. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11829. */
  11830. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11831. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11832. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11833. this.getScene().simplificationQueue.addTask({
  11834. settings: settings,
  11835. parallelProcessing: parallelProcessing,
  11836. mesh: this,
  11837. simplificationType: simplificationType,
  11838. successCallback: successCallback
  11839. });
  11840. };
  11841. /**
  11842. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11843. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11844. * This should be used together with the simplification to avoid disappearing triangles.
  11845. * @param successCallback an optional success callback to be called after the optimization finished.
  11846. */
  11847. Mesh.prototype.optimizeIndices = function (successCallback) {
  11848. var _this = this;
  11849. var indices = this.getIndices();
  11850. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11851. var vectorPositions = [];
  11852. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11853. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11854. }
  11855. var dupes = [];
  11856. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11857. var realPos = vectorPositions.length - 1 - iteration;
  11858. var testedPosition = vectorPositions[realPos];
  11859. for (var j = 0; j < realPos; ++j) {
  11860. var againstPosition = vectorPositions[j];
  11861. if (testedPosition.equals(againstPosition)) {
  11862. dupes[realPos] = j;
  11863. break;
  11864. }
  11865. }
  11866. }, function () {
  11867. for (var i = 0; i < indices.length; ++i) {
  11868. indices[i] = dupes[indices[i]] || indices[i];
  11869. }
  11870. //indices are now reordered
  11871. var originalSubMeshes = _this.subMeshes.slice(0);
  11872. _this.setIndices(indices);
  11873. _this.subMeshes = originalSubMeshes;
  11874. if (successCallback) {
  11875. successCallback(_this);
  11876. }
  11877. });
  11878. };
  11879. // Statics
  11880. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  11881. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11882. if (ribbonInstance === void 0) { ribbonInstance = null; }
  11883. if (ribbonInstance) {
  11884. // positionFunction : ribbon case
  11885. // only pathArray and sideOrientation parameters are taken into account for positions update
  11886. var positionsOfRibbon = function (pathArray, sideOrientation) {
  11887. var positionFunction = function (positions) {
  11888. var minlg = pathArray[0].length;
  11889. var i = 0;
  11890. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  11891. for (var si = 1; si <= ns; si++) {
  11892. for (var p = 0; p < pathArray.length; p++) {
  11893. var path = pathArray[p];
  11894. var l = path.length;
  11895. minlg = (minlg < l) ? minlg : l;
  11896. var j = 0;
  11897. while (j < minlg) {
  11898. positions[i] = path[j].x;
  11899. positions[i + 1] = path[j].y;
  11900. positions[i + 2] = path[j].z;
  11901. j++;
  11902. i += 3;
  11903. }
  11904. }
  11905. }
  11906. };
  11907. return positionFunction;
  11908. };
  11909. var sideOrientation = ribbonInstance.sideOrientation;
  11910. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  11911. ribbonInstance.updateMeshPositions(positionFunction, true);
  11912. return ribbonInstance;
  11913. }
  11914. else {
  11915. var ribbon = new Mesh(name, scene);
  11916. ribbon.sideOrientation = sideOrientation;
  11917. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11918. vertexData.applyToMesh(ribbon, updatable);
  11919. return ribbon;
  11920. }
  11921. };
  11922. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  11923. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11924. var disc = new Mesh(name, scene);
  11925. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  11926. vertexData.applyToMesh(disc, updatable);
  11927. return disc;
  11928. };
  11929. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11930. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11931. var box = new Mesh(name, scene);
  11932. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11933. vertexData.applyToMesh(box, updatable);
  11934. return box;
  11935. };
  11936. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11937. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11938. var sphere = new Mesh(name, scene);
  11939. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11940. vertexData.applyToMesh(sphere, updatable);
  11941. return sphere;
  11942. };
  11943. // Cylinder and cone (Code inspired by SharpDX.org)
  11944. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11945. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11946. // subdivisions is a new parameter, we need to support old signature
  11947. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11948. if (scene !== undefined) {
  11949. updatable = scene;
  11950. }
  11951. scene = subdivisions;
  11952. subdivisions = 1;
  11953. }
  11954. var cylinder = new Mesh(name, scene);
  11955. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11956. vertexData.applyToMesh(cylinder, updatable);
  11957. return cylinder;
  11958. };
  11959. // Torus (Code from SharpDX.org)
  11960. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11961. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11962. var torus = new Mesh(name, scene);
  11963. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11964. vertexData.applyToMesh(torus, updatable);
  11965. return torus;
  11966. };
  11967. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11968. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11969. var torusKnot = new Mesh(name, scene);
  11970. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11971. vertexData.applyToMesh(torusKnot, updatable);
  11972. return torusKnot;
  11973. };
  11974. // Lines
  11975. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  11976. if (linesInstance === void 0) { linesInstance = null; }
  11977. if (linesInstance) {
  11978. var positionsOfLines = function (points) {
  11979. var positionFunction = function (positions) {
  11980. var i = 0;
  11981. for (var p = 0; p < points.length; p++) {
  11982. positions[i] = points[p].x;
  11983. positions[i + 1] = points[p].y;
  11984. positions[i + 2] = points[p].z;
  11985. i += 3;
  11986. }
  11987. };
  11988. return positionFunction;
  11989. };
  11990. var positionFunction = positionsOfLines(points);
  11991. linesInstance.updateMeshPositions(positionFunction, false);
  11992. return linesInstance;
  11993. }
  11994. // lines creation
  11995. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11996. var vertexData = BABYLON.VertexData.CreateLines(points);
  11997. vertexData.applyToMesh(lines, updatable);
  11998. return lines;
  11999. };
  12000. // Extrusion
  12001. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation, extrudedInstance) {
  12002. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12003. if (extrudedInstance === void 0) { extrudedInstance = null; }
  12004. scale = scale || 1;
  12005. rotation = rotation || 0;
  12006. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation, extrudedInstance);
  12007. return extruded;
  12008. };
  12009. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation, extrudedInstance) {
  12010. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12011. if (extrudedInstance === void 0) { extrudedInstance = null; }
  12012. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation, extrudedInstance);
  12013. return extrudedCustom;
  12014. };
  12015. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side, instance) {
  12016. // extrusion geometry
  12017. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, custom) {
  12018. var tangents = path3D.getTangents();
  12019. var normals = path3D.getNormals();
  12020. var binormals = path3D.getBinormals();
  12021. var distances = path3D.getDistances();
  12022. var angle = 0;
  12023. var returnScale = function (i, distance) {
  12024. return scale;
  12025. };
  12026. var returnRotation = function (i, distance) {
  12027. return rotation;
  12028. };
  12029. var rotate = custom ? rotateFunction : returnRotation;
  12030. var scl = custom ? scaleFunction : returnScale;
  12031. var index = 0;
  12032. for (var i = 0; i < curve.length; i++) {
  12033. var shapePath = new Array();
  12034. var angleStep = rotate(i, distances[i]);
  12035. var scaleRatio = scl(i, distances[i]);
  12036. for (var p = 0; p < shape.length; p++) {
  12037. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  12038. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  12039. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  12040. shapePath.push(rotated);
  12041. }
  12042. shapePaths[index] = shapePath;
  12043. angle += angleStep;
  12044. index++;
  12045. }
  12046. return shapePaths;
  12047. };
  12048. if (instance) {
  12049. var path3D = (instance.path3D).update(curve);
  12050. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, custom);
  12051. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  12052. return instance;
  12053. }
  12054. // extruded shape creation
  12055. var path3D = new BABYLON.Path3D(curve);
  12056. var newShapePaths = new Array();
  12057. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, custom);
  12058. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  12059. extrudedGeneric.pathArray = pathArray;
  12060. extrudedGeneric.path3D = path3D;
  12061. return extrudedGeneric;
  12062. };
  12063. // Plane & ground
  12064. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  12065. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12066. var plane = new Mesh(name, scene);
  12067. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  12068. vertexData.applyToMesh(plane, updatable);
  12069. return plane;
  12070. };
  12071. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  12072. var ground = new BABYLON.GroundMesh(name, scene);
  12073. ground._setReady(false);
  12074. ground._subdivisions = subdivisions;
  12075. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  12076. vertexData.applyToMesh(ground, updatable);
  12077. ground._setReady(true);
  12078. return ground;
  12079. };
  12080. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  12081. var tiledGround = new Mesh(name, scene);
  12082. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  12083. vertexData.applyToMesh(tiledGround, updatable);
  12084. return tiledGround;
  12085. };
  12086. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  12087. var ground = new BABYLON.GroundMesh(name, scene);
  12088. ground._subdivisions = subdivisions;
  12089. ground._setReady(false);
  12090. var onload = function (img) {
  12091. // Getting height map data
  12092. var canvas = document.createElement("canvas");
  12093. var context = canvas.getContext("2d");
  12094. var heightMapWidth = img.width;
  12095. var heightMapHeight = img.height;
  12096. canvas.width = heightMapWidth;
  12097. canvas.height = heightMapHeight;
  12098. context.drawImage(img, 0, 0);
  12099. // Create VertexData from map data
  12100. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  12101. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  12102. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  12103. vertexData.applyToMesh(ground, updatable);
  12104. ground._setReady(true);
  12105. //execute ready callback, if set
  12106. if (onReady) {
  12107. onReady(ground);
  12108. }
  12109. };
  12110. BABYLON.Tools.LoadImage(url, onload, function () {
  12111. }, scene.database);
  12112. return ground;
  12113. };
  12114. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, scene, updatable, sideOrientation, tubeInstance) {
  12115. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12116. if (tubeInstance === void 0) { tubeInstance = null; }
  12117. // tube geometry
  12118. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction) {
  12119. var tangents = path3D.getTangents();
  12120. var normals = path3D.getNormals();
  12121. var distances = path3D.getDistances();
  12122. var pi2 = Math.PI * 2;
  12123. var step = pi2 / tessellation;
  12124. var returnRadius = function (i, distance) { return radius; };
  12125. var radiusFunctionFinal = radiusFunction || returnRadius;
  12126. var circlePath;
  12127. var rad;
  12128. var normal;
  12129. var rotated;
  12130. var rotationMatrix;
  12131. var index = 0;
  12132. for (var i = 0; i < path.length; i++) {
  12133. rad = radiusFunctionFinal(i, distances[i]); // current radius
  12134. circlePath = Array(); // current circle array
  12135. normal = normals[i]; // current normal
  12136. for (var ang = 0; ang < pi2; ang += step) {
  12137. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  12138. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  12139. circlePath.push(rotated);
  12140. }
  12141. circlePaths[index] = circlePath;
  12142. index++;
  12143. }
  12144. return circlePaths;
  12145. };
  12146. if (tubeInstance) {
  12147. var path3D = (tubeInstance.path3D).update(path);
  12148. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction);
  12149. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  12150. return tubeInstance;
  12151. }
  12152. // tube creation
  12153. var path3D = new BABYLON.Path3D(path);
  12154. var newPathArray = new Array();
  12155. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction);
  12156. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  12157. tube.pathArray = pathArray;
  12158. tube.path3D = path3D;
  12159. tube.tessellation = tessellation;
  12160. return tube;
  12161. };
  12162. // Decals
  12163. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  12164. if (angle === void 0) { angle = 0; }
  12165. var indices = sourceMesh.getIndices();
  12166. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12167. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12168. // Getting correct rotation
  12169. if (!normal) {
  12170. var target = new BABYLON.Vector3(0, 0, 1);
  12171. var camera = sourceMesh.getScene().activeCamera;
  12172. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  12173. normal = camera.globalPosition.subtract(cameraWorldTarget);
  12174. }
  12175. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  12176. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  12177. var pitch = Math.atan2(normal.y, len);
  12178. // Matrix
  12179. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  12180. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  12181. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  12182. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  12183. var vertexData = new BABYLON.VertexData();
  12184. vertexData.indices = [];
  12185. vertexData.positions = [];
  12186. vertexData.normals = [];
  12187. vertexData.uvs = [];
  12188. var currentVertexDataIndex = 0;
  12189. var extractDecalVector3 = function (indexId) {
  12190. var vertexId = indices[indexId];
  12191. var result = new BABYLON.PositionNormalVertex();
  12192. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  12193. // Send vector to decal local world
  12194. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  12195. // Get normal
  12196. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  12197. return result;
  12198. };
  12199. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  12200. var clip = function (vertices, axis) {
  12201. if (vertices.length === 0) {
  12202. return vertices;
  12203. }
  12204. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  12205. var clipVertices = function (v0, v1) {
  12206. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  12207. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  12208. };
  12209. var result = new Array();
  12210. for (var index = 0; index < vertices.length; index += 3) {
  12211. var v1Out;
  12212. var v2Out;
  12213. var v3Out;
  12214. var total = 0;
  12215. var nV1, nV2, nV3, nV4;
  12216. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  12217. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  12218. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  12219. v1Out = d1 > 0;
  12220. v2Out = d2 > 0;
  12221. v3Out = d3 > 0;
  12222. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  12223. switch (total) {
  12224. case 0:
  12225. result.push(vertices[index]);
  12226. result.push(vertices[index + 1]);
  12227. result.push(vertices[index + 2]);
  12228. break;
  12229. case 1:
  12230. if (v1Out) {
  12231. nV1 = vertices[index + 1];
  12232. nV2 = vertices[index + 2];
  12233. nV3 = clipVertices(vertices[index], nV1);
  12234. nV4 = clipVertices(vertices[index], nV2);
  12235. }
  12236. if (v2Out) {
  12237. nV1 = vertices[index];
  12238. nV2 = vertices[index + 2];
  12239. nV3 = clipVertices(vertices[index + 1], nV1);
  12240. nV4 = clipVertices(vertices[index + 1], nV2);
  12241. result.push(nV3);
  12242. result.push(nV2.clone());
  12243. result.push(nV1.clone());
  12244. result.push(nV2.clone());
  12245. result.push(nV3.clone());
  12246. result.push(nV4);
  12247. break;
  12248. }
  12249. if (v3Out) {
  12250. nV1 = vertices[index];
  12251. nV2 = vertices[index + 1];
  12252. nV3 = clipVertices(vertices[index + 2], nV1);
  12253. nV4 = clipVertices(vertices[index + 2], nV2);
  12254. }
  12255. result.push(nV1.clone());
  12256. result.push(nV2.clone());
  12257. result.push(nV3);
  12258. result.push(nV4);
  12259. result.push(nV3.clone());
  12260. result.push(nV2.clone());
  12261. break;
  12262. case 2:
  12263. if (!v1Out) {
  12264. nV1 = vertices[index].clone();
  12265. nV2 = clipVertices(nV1, vertices[index + 1]);
  12266. nV3 = clipVertices(nV1, vertices[index + 2]);
  12267. result.push(nV1);
  12268. result.push(nV2);
  12269. result.push(nV3);
  12270. }
  12271. if (!v2Out) {
  12272. nV1 = vertices[index + 1].clone();
  12273. nV2 = clipVertices(nV1, vertices[index + 2]);
  12274. nV3 = clipVertices(nV1, vertices[index]);
  12275. result.push(nV1);
  12276. result.push(nV2);
  12277. result.push(nV3);
  12278. }
  12279. if (!v3Out) {
  12280. nV1 = vertices[index + 2].clone();
  12281. nV2 = clipVertices(nV1, vertices[index]);
  12282. nV3 = clipVertices(nV1, vertices[index + 1]);
  12283. result.push(nV1);
  12284. result.push(nV2);
  12285. result.push(nV3);
  12286. }
  12287. break;
  12288. case 3:
  12289. break;
  12290. }
  12291. }
  12292. return result;
  12293. };
  12294. for (var index = 0; index < indices.length; index += 3) {
  12295. var faceVertices = new Array();
  12296. faceVertices.push(extractDecalVector3(index));
  12297. faceVertices.push(extractDecalVector3(index + 1));
  12298. faceVertices.push(extractDecalVector3(index + 2));
  12299. // Clip
  12300. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12301. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12302. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12303. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12304. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12305. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12306. if (faceVertices.length === 0) {
  12307. continue;
  12308. }
  12309. // Add UVs and get back to world
  12310. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  12311. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12312. var vertex = faceVertices[vIndex];
  12313. vertexData.indices.push(currentVertexDataIndex);
  12314. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  12315. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12316. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12317. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12318. currentVertexDataIndex++;
  12319. }
  12320. }
  12321. // Return mesh
  12322. var decal = new Mesh(name, sourceMesh.getScene());
  12323. vertexData.applyToMesh(decal);
  12324. decal.position = position.clone();
  12325. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  12326. return decal;
  12327. };
  12328. // Tools
  12329. Mesh.MinMax = function (meshes) {
  12330. var minVector = null;
  12331. var maxVector = null;
  12332. for (var i in meshes) {
  12333. var mesh = meshes[i];
  12334. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12335. if (!minVector) {
  12336. minVector = boundingBox.minimumWorld;
  12337. maxVector = boundingBox.maximumWorld;
  12338. continue;
  12339. }
  12340. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12341. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12342. }
  12343. return {
  12344. min: minVector,
  12345. max: maxVector
  12346. };
  12347. };
  12348. Mesh.Center = function (meshesOrMinMaxVector) {
  12349. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12350. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12351. };
  12352. /**
  12353. * Merge the array of meshes into a single mesh for performance reasons.
  12354. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  12355. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  12356. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  12357. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  12358. */
  12359. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  12360. if (disposeSource === void 0) { disposeSource = true; }
  12361. if (!allow32BitsIndices) {
  12362. var totalVertices = 0;
  12363. for (var index = 0; index < meshes.length; index++) {
  12364. if (meshes[index]) {
  12365. totalVertices += meshes[index].getTotalVertices();
  12366. if (totalVertices > 65536) {
  12367. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12368. return null;
  12369. }
  12370. }
  12371. }
  12372. }
  12373. // Merge
  12374. var vertexData;
  12375. var otherVertexData;
  12376. var source;
  12377. for (index = 0; index < meshes.length; index++) {
  12378. if (meshes[index]) {
  12379. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  12380. otherVertexData.transform(meshes[index].getWorldMatrix());
  12381. if (vertexData) {
  12382. vertexData.merge(otherVertexData);
  12383. }
  12384. else {
  12385. vertexData = otherVertexData;
  12386. source = meshes[index];
  12387. }
  12388. }
  12389. }
  12390. if (!meshSubclass) {
  12391. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  12392. }
  12393. vertexData.applyToMesh(meshSubclass);
  12394. // Setting properties
  12395. meshSubclass.material = source.material;
  12396. meshSubclass.checkCollisions = source.checkCollisions;
  12397. // Cleaning
  12398. if (disposeSource) {
  12399. for (index = 0; index < meshes.length; index++) {
  12400. if (meshes[index]) {
  12401. meshes[index].dispose();
  12402. }
  12403. }
  12404. }
  12405. return meshSubclass;
  12406. };
  12407. // Consts
  12408. Mesh._FRONTSIDE = 0;
  12409. Mesh._BACKSIDE = 1;
  12410. Mesh._DOUBLESIDE = 2;
  12411. Mesh._DEFAULTSIDE = 0;
  12412. return Mesh;
  12413. })(BABYLON.AbstractMesh);
  12414. BABYLON.Mesh = Mesh;
  12415. })(BABYLON || (BABYLON = {}));
  12416. //# sourceMappingURL=babylon.mesh.js.map
  12417. var BABYLON;
  12418. (function (BABYLON) {
  12419. var GroundMesh = (function (_super) {
  12420. __extends(GroundMesh, _super);
  12421. function GroundMesh(name, scene) {
  12422. _super.call(this, name, scene);
  12423. this.generateOctree = false;
  12424. this._worldInverse = new BABYLON.Matrix();
  12425. }
  12426. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12427. get: function () {
  12428. return this._subdivisions;
  12429. },
  12430. enumerable: true,
  12431. configurable: true
  12432. });
  12433. GroundMesh.prototype.optimize = function (chunksCount) {
  12434. this.subdivide(this._subdivisions);
  12435. this.createOrUpdateSubmeshesOctree(32);
  12436. };
  12437. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12438. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12439. this.getWorldMatrix().invertToRef(this._worldInverse);
  12440. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12441. var pickInfo = this.intersects(ray);
  12442. if (pickInfo.hit) {
  12443. return pickInfo.pickedPoint.y;
  12444. }
  12445. return 0;
  12446. };
  12447. return GroundMesh;
  12448. })(BABYLON.Mesh);
  12449. BABYLON.GroundMesh = GroundMesh;
  12450. })(BABYLON || (BABYLON = {}));
  12451. //# sourceMappingURL=babylon.groundMesh.js.map
  12452. var BABYLON;
  12453. (function (BABYLON) {
  12454. /**
  12455. * Creates an instance based on a source mesh.
  12456. */
  12457. var InstancedMesh = (function (_super) {
  12458. __extends(InstancedMesh, _super);
  12459. function InstancedMesh(name, source) {
  12460. _super.call(this, name, source.getScene());
  12461. source.instances.push(this);
  12462. this._sourceMesh = source;
  12463. this.position.copyFrom(source.position);
  12464. this.rotation.copyFrom(source.rotation);
  12465. this.scaling.copyFrom(source.scaling);
  12466. if (source.rotationQuaternion) {
  12467. this.rotationQuaternion = source.rotationQuaternion.clone();
  12468. }
  12469. this.infiniteDistance = source.infiniteDistance;
  12470. this.setPivotMatrix(source.getPivotMatrix());
  12471. this.refreshBoundingInfo();
  12472. this._syncSubMeshes();
  12473. }
  12474. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12475. // Methods
  12476. get: function () {
  12477. return this._sourceMesh.receiveShadows;
  12478. },
  12479. enumerable: true,
  12480. configurable: true
  12481. });
  12482. Object.defineProperty(InstancedMesh.prototype, "material", {
  12483. get: function () {
  12484. return this._sourceMesh.material;
  12485. },
  12486. enumerable: true,
  12487. configurable: true
  12488. });
  12489. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12490. get: function () {
  12491. return this._sourceMesh.visibility;
  12492. },
  12493. enumerable: true,
  12494. configurable: true
  12495. });
  12496. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12497. get: function () {
  12498. return this._sourceMesh.skeleton;
  12499. },
  12500. enumerable: true,
  12501. configurable: true
  12502. });
  12503. InstancedMesh.prototype.getTotalVertices = function () {
  12504. return this._sourceMesh.getTotalVertices();
  12505. };
  12506. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12507. get: function () {
  12508. return this._sourceMesh;
  12509. },
  12510. enumerable: true,
  12511. configurable: true
  12512. });
  12513. InstancedMesh.prototype.getVerticesData = function (kind) {
  12514. return this._sourceMesh.getVerticesData(kind);
  12515. };
  12516. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12517. return this._sourceMesh.isVerticesDataPresent(kind);
  12518. };
  12519. InstancedMesh.prototype.getIndices = function () {
  12520. return this._sourceMesh.getIndices();
  12521. };
  12522. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12523. get: function () {
  12524. return this._sourceMesh._positions;
  12525. },
  12526. enumerable: true,
  12527. configurable: true
  12528. });
  12529. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12530. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12531. if (data) {
  12532. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12533. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12534. }
  12535. this._updateBoundingInfo();
  12536. };
  12537. InstancedMesh.prototype._preActivate = function () {
  12538. if (this._currentLOD) {
  12539. this._currentLOD._preActivate();
  12540. }
  12541. };
  12542. InstancedMesh.prototype._activate = function (renderId) {
  12543. if (this._currentLOD) {
  12544. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12545. }
  12546. };
  12547. InstancedMesh.prototype.getLOD = function (camera) {
  12548. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12549. if (this._currentLOD === this.sourceMesh) {
  12550. return this;
  12551. }
  12552. return this._currentLOD;
  12553. };
  12554. InstancedMesh.prototype._syncSubMeshes = function () {
  12555. this.releaseSubMeshes();
  12556. if (this._sourceMesh.subMeshes) {
  12557. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12558. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12559. }
  12560. }
  12561. };
  12562. InstancedMesh.prototype._generatePointsArray = function () {
  12563. return this._sourceMesh._generatePointsArray();
  12564. };
  12565. // Clone
  12566. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12567. var result = this._sourceMesh.createInstance(name);
  12568. // Deep copy
  12569. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12570. // Bounding info
  12571. this.refreshBoundingInfo();
  12572. // Parent
  12573. if (newParent) {
  12574. result.parent = newParent;
  12575. }
  12576. if (!doNotCloneChildren) {
  12577. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12578. var mesh = this.getScene().meshes[index];
  12579. if (mesh.parent === this) {
  12580. mesh.clone(mesh.name, result);
  12581. }
  12582. }
  12583. }
  12584. result.computeWorldMatrix(true);
  12585. return result;
  12586. };
  12587. // Dispoe
  12588. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12589. // Remove from mesh
  12590. var index = this._sourceMesh.instances.indexOf(this);
  12591. this._sourceMesh.instances.splice(index, 1);
  12592. _super.prototype.dispose.call(this, doNotRecurse);
  12593. };
  12594. return InstancedMesh;
  12595. })(BABYLON.AbstractMesh);
  12596. BABYLON.InstancedMesh = InstancedMesh;
  12597. })(BABYLON || (BABYLON = {}));
  12598. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12599. (function (BABYLON) {
  12600. var SubMesh = (function () {
  12601. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12602. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12603. this.materialIndex = materialIndex;
  12604. this.verticesStart = verticesStart;
  12605. this.verticesCount = verticesCount;
  12606. this.indexStart = indexStart;
  12607. this.indexCount = indexCount;
  12608. this._renderId = 0;
  12609. this._mesh = mesh;
  12610. this._renderingMesh = renderingMesh || mesh;
  12611. mesh.subMeshes.push(this);
  12612. this._id = mesh.subMeshes.length - 1;
  12613. if (createBoundingBox) {
  12614. this.refreshBoundingInfo();
  12615. mesh.computeWorldMatrix(true);
  12616. }
  12617. }
  12618. SubMesh.prototype.getBoundingInfo = function () {
  12619. return this._boundingInfo;
  12620. };
  12621. SubMesh.prototype.getMesh = function () {
  12622. return this._mesh;
  12623. };
  12624. SubMesh.prototype.getRenderingMesh = function () {
  12625. return this._renderingMesh;
  12626. };
  12627. SubMesh.prototype.getMaterial = function () {
  12628. var rootMaterial = this._renderingMesh.material;
  12629. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12630. var multiMaterial = rootMaterial;
  12631. return multiMaterial.getSubMaterial(this.materialIndex);
  12632. }
  12633. if (!rootMaterial) {
  12634. return this._mesh.getScene().defaultMaterial;
  12635. }
  12636. return rootMaterial;
  12637. };
  12638. // Methods
  12639. SubMesh.prototype.refreshBoundingInfo = function () {
  12640. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12641. if (!data) {
  12642. this._boundingInfo = this._mesh._boundingInfo;
  12643. return;
  12644. }
  12645. var indices = this._renderingMesh.getIndices();
  12646. var extend;
  12647. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12648. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12649. }
  12650. else {
  12651. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12652. }
  12653. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12654. };
  12655. SubMesh.prototype._checkCollision = function (collider) {
  12656. return this._boundingInfo._checkCollision(collider);
  12657. };
  12658. SubMesh.prototype.updateBoundingInfo = function (world) {
  12659. if (!this._boundingInfo) {
  12660. this.refreshBoundingInfo();
  12661. }
  12662. this._boundingInfo._update(world);
  12663. };
  12664. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12665. return this._boundingInfo.isInFrustum(frustumPlanes);
  12666. };
  12667. SubMesh.prototype.render = function () {
  12668. this._renderingMesh.render(this);
  12669. };
  12670. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12671. if (!this._linesIndexBuffer) {
  12672. var linesIndices = [];
  12673. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12674. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12675. }
  12676. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12677. this.linesIndexCount = linesIndices.length;
  12678. }
  12679. return this._linesIndexBuffer;
  12680. };
  12681. SubMesh.prototype.canIntersects = function (ray) {
  12682. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12683. };
  12684. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12685. var intersectInfo = null;
  12686. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12687. var p0 = positions[indices[index]];
  12688. var p1 = positions[indices[index + 1]];
  12689. var p2 = positions[indices[index + 2]];
  12690. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12691. if (currentIntersectInfo) {
  12692. if (currentIntersectInfo.distance < 0) {
  12693. continue;
  12694. }
  12695. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12696. intersectInfo = currentIntersectInfo;
  12697. intersectInfo.faceId = index / 3;
  12698. if (fastCheck) {
  12699. break;
  12700. }
  12701. }
  12702. }
  12703. }
  12704. return intersectInfo;
  12705. };
  12706. // Clone
  12707. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12708. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12709. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12710. return result;
  12711. };
  12712. // Dispose
  12713. SubMesh.prototype.dispose = function () {
  12714. if (this._linesIndexBuffer) {
  12715. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12716. this._linesIndexBuffer = null;
  12717. }
  12718. // Remove from mesh
  12719. var index = this._mesh.subMeshes.indexOf(this);
  12720. this._mesh.subMeshes.splice(index, 1);
  12721. };
  12722. // Statics
  12723. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12724. var minVertexIndex = Number.MAX_VALUE;
  12725. var maxVertexIndex = -Number.MAX_VALUE;
  12726. renderingMesh = renderingMesh || mesh;
  12727. var indices = renderingMesh.getIndices();
  12728. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12729. var vertexIndex = indices[index];
  12730. if (vertexIndex < minVertexIndex)
  12731. minVertexIndex = vertexIndex;
  12732. if (vertexIndex > maxVertexIndex)
  12733. maxVertexIndex = vertexIndex;
  12734. }
  12735. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12736. };
  12737. return SubMesh;
  12738. })();
  12739. BABYLON.SubMesh = SubMesh;
  12740. })(BABYLON || (BABYLON = {}));
  12741. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12742. (function (BABYLON) {
  12743. var BaseTexture = (function () {
  12744. function BaseTexture(scene) {
  12745. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12746. this.hasAlpha = false;
  12747. this.getAlphaFromRGB = false;
  12748. this.level = 1;
  12749. this.isCube = false;
  12750. this.isRenderTarget = false;
  12751. this.animations = new Array();
  12752. this.coordinatesIndex = 0;
  12753. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12754. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12755. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12756. this.anisotropicFilteringLevel = 4;
  12757. this._scene = scene;
  12758. this._scene.textures.push(this);
  12759. }
  12760. BaseTexture.prototype.getScene = function () {
  12761. return this._scene;
  12762. };
  12763. BaseTexture.prototype.getTextureMatrix = function () {
  12764. return null;
  12765. };
  12766. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12767. return null;
  12768. };
  12769. BaseTexture.prototype.getInternalTexture = function () {
  12770. return this._texture;
  12771. };
  12772. BaseTexture.prototype.isReady = function () {
  12773. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12774. return true;
  12775. }
  12776. if (this._texture) {
  12777. return this._texture.isReady;
  12778. }
  12779. return false;
  12780. };
  12781. BaseTexture.prototype.getSize = function () {
  12782. if (this._texture._width) {
  12783. return { width: this._texture._width, height: this._texture._height };
  12784. }
  12785. if (this._texture._size) {
  12786. return { width: this._texture._size, height: this._texture._size };
  12787. }
  12788. return { width: 0, height: 0 };
  12789. };
  12790. BaseTexture.prototype.getBaseSize = function () {
  12791. if (!this.isReady())
  12792. return { width: 0, height: 0 };
  12793. if (this._texture._size) {
  12794. return { width: this._texture._size, height: this._texture._size };
  12795. }
  12796. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12797. };
  12798. BaseTexture.prototype.scale = function (ratio) {
  12799. };
  12800. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12801. get: function () {
  12802. return false;
  12803. },
  12804. enumerable: true,
  12805. configurable: true
  12806. });
  12807. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12808. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12809. for (var index = 0; index < texturesCache.length; index++) {
  12810. var texturesCacheEntry = texturesCache[index];
  12811. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12812. texturesCache.splice(index, 1);
  12813. return;
  12814. }
  12815. }
  12816. };
  12817. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12818. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12819. for (var index = 0; index < texturesCache.length; index++) {
  12820. var texturesCacheEntry = texturesCache[index];
  12821. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12822. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12823. texturesCacheEntry.references++;
  12824. return texturesCacheEntry;
  12825. }
  12826. }
  12827. }
  12828. return null;
  12829. };
  12830. BaseTexture.prototype.delayLoad = function () {
  12831. };
  12832. BaseTexture.prototype.releaseInternalTexture = function () {
  12833. if (!this._texture) {
  12834. return;
  12835. }
  12836. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12837. this._texture.references--;
  12838. // Final reference ?
  12839. if (this._texture.references === 0) {
  12840. var index = texturesCache.indexOf(this._texture);
  12841. texturesCache.splice(index, 1);
  12842. this._scene.getEngine()._releaseTexture(this._texture);
  12843. delete this._texture;
  12844. }
  12845. };
  12846. BaseTexture.prototype.clone = function () {
  12847. return null;
  12848. };
  12849. BaseTexture.prototype.dispose = function () {
  12850. // Remove from scene
  12851. var index = this._scene.textures.indexOf(this);
  12852. if (index >= 0) {
  12853. this._scene.textures.splice(index, 1);
  12854. }
  12855. if (this._texture === undefined) {
  12856. return;
  12857. }
  12858. this.releaseInternalTexture();
  12859. // Callback
  12860. if (this.onDispose) {
  12861. this.onDispose();
  12862. }
  12863. };
  12864. return BaseTexture;
  12865. })();
  12866. BABYLON.BaseTexture = BaseTexture;
  12867. })(BABYLON || (BABYLON = {}));
  12868. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12869. (function (BABYLON) {
  12870. var RenderingGroup = (function () {
  12871. function RenderingGroup(index, scene) {
  12872. this.index = index;
  12873. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12874. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12875. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12876. this._scene = scene;
  12877. }
  12878. RenderingGroup.prototype.render = function (customRenderFunction) {
  12879. if (customRenderFunction) {
  12880. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12881. return true;
  12882. }
  12883. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12884. return false;
  12885. }
  12886. var engine = this._scene.getEngine();
  12887. // Opaque
  12888. var subIndex;
  12889. var submesh;
  12890. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12891. submesh = this._opaqueSubMeshes.data[subIndex];
  12892. submesh.render();
  12893. }
  12894. // Alpha test
  12895. engine.setAlphaTesting(true);
  12896. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12897. submesh = this._alphaTestSubMeshes.data[subIndex];
  12898. submesh.render();
  12899. }
  12900. engine.setAlphaTesting(false);
  12901. // Transparent
  12902. if (this._transparentSubMeshes.length) {
  12903. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12904. submesh = this._transparentSubMeshes.data[subIndex];
  12905. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12906. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12907. }
  12908. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12909. sortedArray.sort(function (a, b) {
  12910. // Alpha index first
  12911. if (a._alphaIndex > b._alphaIndex) {
  12912. return 1;
  12913. }
  12914. if (a._alphaIndex < b._alphaIndex) {
  12915. return -1;
  12916. }
  12917. // Then distance to camera
  12918. if (a._distanceToCamera < b._distanceToCamera) {
  12919. return 1;
  12920. }
  12921. if (a._distanceToCamera > b._distanceToCamera) {
  12922. return -1;
  12923. }
  12924. return 0;
  12925. });
  12926. // Rendering
  12927. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12928. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12929. submesh = sortedArray[subIndex];
  12930. submesh.render();
  12931. }
  12932. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12933. }
  12934. return true;
  12935. };
  12936. RenderingGroup.prototype.prepare = function () {
  12937. this._opaqueSubMeshes.reset();
  12938. this._transparentSubMeshes.reset();
  12939. this._alphaTestSubMeshes.reset();
  12940. };
  12941. RenderingGroup.prototype.dispatch = function (subMesh) {
  12942. var material = subMesh.getMaterial();
  12943. var mesh = subMesh.getMesh();
  12944. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12945. this._transparentSubMeshes.push(subMesh);
  12946. }
  12947. else if (material.needAlphaTesting()) {
  12948. this._alphaTestSubMeshes.push(subMesh);
  12949. }
  12950. else {
  12951. this._opaqueSubMeshes.push(subMesh); // Opaque
  12952. }
  12953. };
  12954. return RenderingGroup;
  12955. })();
  12956. BABYLON.RenderingGroup = RenderingGroup;
  12957. })(BABYLON || (BABYLON = {}));
  12958. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12959. (function (BABYLON) {
  12960. var RenderingManager = (function () {
  12961. function RenderingManager(scene) {
  12962. this._renderingGroups = new Array();
  12963. this._scene = scene;
  12964. }
  12965. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12966. if (this._scene._activeParticleSystems.length === 0) {
  12967. return;
  12968. }
  12969. // Particles
  12970. var beforeParticlesDate = BABYLON.Tools.Now;
  12971. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12972. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12973. if (particleSystem.renderingGroupId !== index) {
  12974. continue;
  12975. }
  12976. this._clearDepthBuffer();
  12977. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12978. this._scene._activeParticles += particleSystem.render();
  12979. }
  12980. }
  12981. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12982. };
  12983. RenderingManager.prototype._renderSprites = function (index) {
  12984. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12985. return;
  12986. }
  12987. // Sprites
  12988. var beforeSpritessDate = BABYLON.Tools.Now;
  12989. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12990. var spriteManager = this._scene.spriteManagers[id];
  12991. if (spriteManager.renderingGroupId === index) {
  12992. this._clearDepthBuffer();
  12993. spriteManager.render();
  12994. }
  12995. }
  12996. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12997. };
  12998. RenderingManager.prototype._clearDepthBuffer = function () {
  12999. if (this._depthBufferAlreadyCleaned) {
  13000. return;
  13001. }
  13002. this._scene.getEngine().clear(0, false, true);
  13003. this._depthBufferAlreadyCleaned = true;
  13004. };
  13005. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13006. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13007. this._depthBufferAlreadyCleaned = false;
  13008. var renderingGroup = this._renderingGroups[index];
  13009. var needToStepBack = false;
  13010. if (renderingGroup) {
  13011. this._clearDepthBuffer();
  13012. if (!renderingGroup.render(customRenderFunction)) {
  13013. this._renderingGroups.splice(index, 1);
  13014. needToStepBack = true;
  13015. }
  13016. }
  13017. if (renderSprites) {
  13018. this._renderSprites(index);
  13019. }
  13020. if (renderParticles) {
  13021. this._renderParticles(index, activeMeshes);
  13022. }
  13023. if (needToStepBack) {
  13024. index--;
  13025. }
  13026. }
  13027. };
  13028. RenderingManager.prototype.reset = function () {
  13029. for (var index in this._renderingGroups) {
  13030. var renderingGroup = this._renderingGroups[index];
  13031. renderingGroup.prepare();
  13032. }
  13033. };
  13034. RenderingManager.prototype.dispatch = function (subMesh) {
  13035. var mesh = subMesh.getMesh();
  13036. var renderingGroupId = mesh.renderingGroupId || 0;
  13037. if (!this._renderingGroups[renderingGroupId]) {
  13038. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13039. }
  13040. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13041. };
  13042. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13043. return RenderingManager;
  13044. })();
  13045. BABYLON.RenderingManager = RenderingManager;
  13046. })(BABYLON || (BABYLON = {}));
  13047. //# sourceMappingURL=babylon.renderingManager.js.map
  13048. var BABYLON;
  13049. (function (BABYLON) {
  13050. var Texture = (function (_super) {
  13051. __extends(Texture, _super);
  13052. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  13053. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13054. if (onLoad === void 0) { onLoad = null; }
  13055. if (onError === void 0) { onError = null; }
  13056. if (buffer === void 0) { buffer = null; }
  13057. if (deleteBuffer === void 0) { deleteBuffer = false; }
  13058. _super.call(this, scene);
  13059. this.uOffset = 0;
  13060. this.vOffset = 0;
  13061. this.uScale = 1.0;
  13062. this.vScale = 1.0;
  13063. this.uAng = 0;
  13064. this.vAng = 0;
  13065. this.wAng = 0;
  13066. this.name = url;
  13067. this.url = url;
  13068. this._noMipmap = noMipmap;
  13069. this._invertY = invertY;
  13070. this._samplingMode = samplingMode;
  13071. this._buffer = buffer;
  13072. this._deleteBuffer = deleteBuffer;
  13073. if (!url) {
  13074. return;
  13075. }
  13076. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  13077. if (!this._texture) {
  13078. if (!scene.useDelayedTextureLoading) {
  13079. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  13080. if (deleteBuffer) {
  13081. delete this._buffer;
  13082. }
  13083. }
  13084. else {
  13085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13086. }
  13087. }
  13088. }
  13089. Texture.prototype.delayLoad = function () {
  13090. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13091. return;
  13092. }
  13093. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13094. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  13095. if (!this._texture) {
  13096. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  13097. if (this._deleteBuffer) {
  13098. delete this._buffer;
  13099. }
  13100. }
  13101. };
  13102. Texture.prototype.updateSamplingMode = function (samplingMode) {
  13103. if (!this._texture) {
  13104. return;
  13105. }
  13106. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  13107. };
  13108. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  13109. x -= this.uOffset + 0.5;
  13110. y -= this.vOffset + 0.5;
  13111. z -= 0.5;
  13112. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  13113. t.x *= this.uScale;
  13114. t.y *= this.vScale;
  13115. t.x += 0.5;
  13116. t.y += 0.5;
  13117. t.z += 0.5;
  13118. };
  13119. Texture.prototype.getTextureMatrix = function () {
  13120. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  13121. return this._cachedTextureMatrix;
  13122. }
  13123. this._cachedUOffset = this.uOffset;
  13124. this._cachedVOffset = this.vOffset;
  13125. this._cachedUScale = this.uScale;
  13126. this._cachedVScale = this.vScale;
  13127. this._cachedUAng = this.uAng;
  13128. this._cachedVAng = this.vAng;
  13129. this._cachedWAng = this.wAng;
  13130. if (!this._cachedTextureMatrix) {
  13131. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13132. this._rowGenerationMatrix = new BABYLON.Matrix();
  13133. this._t0 = BABYLON.Vector3.Zero();
  13134. this._t1 = BABYLON.Vector3.Zero();
  13135. this._t2 = BABYLON.Vector3.Zero();
  13136. }
  13137. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  13138. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  13139. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  13140. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  13141. this._t1.subtractInPlace(this._t0);
  13142. this._t2.subtractInPlace(this._t0);
  13143. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13144. this._cachedTextureMatrix.m[0] = this._t1.x;
  13145. this._cachedTextureMatrix.m[1] = this._t1.y;
  13146. this._cachedTextureMatrix.m[2] = this._t1.z;
  13147. this._cachedTextureMatrix.m[4] = this._t2.x;
  13148. this._cachedTextureMatrix.m[5] = this._t2.y;
  13149. this._cachedTextureMatrix.m[6] = this._t2.z;
  13150. this._cachedTextureMatrix.m[8] = this._t0.x;
  13151. this._cachedTextureMatrix.m[9] = this._t0.y;
  13152. this._cachedTextureMatrix.m[10] = this._t0.z;
  13153. return this._cachedTextureMatrix;
  13154. };
  13155. Texture.prototype.getReflectionTextureMatrix = function () {
  13156. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  13157. return this._cachedTextureMatrix;
  13158. }
  13159. if (!this._cachedTextureMatrix) {
  13160. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13161. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  13162. }
  13163. this._cachedCoordinatesMode = this.coordinatesMode;
  13164. switch (this.coordinatesMode) {
  13165. case Texture.SPHERICAL_MODE:
  13166. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13167. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  13168. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  13169. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  13170. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  13171. break;
  13172. case Texture.PLANAR_MODE:
  13173. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13174. this._cachedTextureMatrix[0] = this.uScale;
  13175. this._cachedTextureMatrix[5] = this.vScale;
  13176. this._cachedTextureMatrix[12] = this.uOffset;
  13177. this._cachedTextureMatrix[13] = this.vOffset;
  13178. break;
  13179. case Texture.PROJECTION_MODE:
  13180. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  13181. this._projectionModeMatrix.m[0] = 0.5;
  13182. this._projectionModeMatrix.m[5] = -0.5;
  13183. this._projectionModeMatrix.m[10] = 0.0;
  13184. this._projectionModeMatrix.m[12] = 0.5;
  13185. this._projectionModeMatrix.m[13] = 0.5;
  13186. this._projectionModeMatrix.m[14] = 1.0;
  13187. this._projectionModeMatrix.m[15] = 1.0;
  13188. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  13189. break;
  13190. default:
  13191. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13192. break;
  13193. }
  13194. return this._cachedTextureMatrix;
  13195. };
  13196. Texture.prototype.clone = function () {
  13197. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  13198. // Base texture
  13199. newTexture.hasAlpha = this.hasAlpha;
  13200. newTexture.level = this.level;
  13201. newTexture.wrapU = this.wrapU;
  13202. newTexture.wrapV = this.wrapV;
  13203. newTexture.coordinatesIndex = this.coordinatesIndex;
  13204. newTexture.coordinatesMode = this.coordinatesMode;
  13205. // Texture
  13206. newTexture.uOffset = this.uOffset;
  13207. newTexture.vOffset = this.vOffset;
  13208. newTexture.uScale = this.uScale;
  13209. newTexture.vScale = this.vScale;
  13210. newTexture.uAng = this.uAng;
  13211. newTexture.vAng = this.vAng;
  13212. newTexture.wAng = this.wAng;
  13213. return newTexture;
  13214. };
  13215. // Statics
  13216. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  13217. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13218. if (onLoad === void 0) { onLoad = null; }
  13219. if (onError === void 0) { onError = null; }
  13220. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  13221. };
  13222. // Constants
  13223. Texture.NEAREST_SAMPLINGMODE = 1;
  13224. Texture.BILINEAR_SAMPLINGMODE = 2;
  13225. Texture.TRILINEAR_SAMPLINGMODE = 3;
  13226. Texture.EXPLICIT_MODE = 0;
  13227. Texture.SPHERICAL_MODE = 1;
  13228. Texture.PLANAR_MODE = 2;
  13229. Texture.CUBIC_MODE = 3;
  13230. Texture.PROJECTION_MODE = 4;
  13231. Texture.SKYBOX_MODE = 5;
  13232. Texture.CLAMP_ADDRESSMODE = 0;
  13233. Texture.WRAP_ADDRESSMODE = 1;
  13234. Texture.MIRROR_ADDRESSMODE = 2;
  13235. return Texture;
  13236. })(BABYLON.BaseTexture);
  13237. BABYLON.Texture = Texture;
  13238. })(BABYLON || (BABYLON = {}));
  13239. //# sourceMappingURL=babylon.texture.js.map
  13240. var BABYLON;
  13241. (function (BABYLON) {
  13242. var CubeTexture = (function (_super) {
  13243. __extends(CubeTexture, _super);
  13244. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  13245. _super.call(this, scene);
  13246. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  13247. this.name = rootUrl;
  13248. this.url = rootUrl;
  13249. this._noMipmap = noMipmap;
  13250. this.hasAlpha = false;
  13251. this._texture = this._getFromCache(rootUrl, noMipmap);
  13252. if (!extensions) {
  13253. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  13254. }
  13255. this._extensions = extensions;
  13256. if (!this._texture) {
  13257. if (!scene.useDelayedTextureLoading) {
  13258. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  13259. }
  13260. else {
  13261. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13262. }
  13263. }
  13264. this.isCube = true;
  13265. this._textureMatrix = BABYLON.Matrix.Identity();
  13266. }
  13267. CubeTexture.prototype.clone = function () {
  13268. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  13269. // Base texture
  13270. newTexture.level = this.level;
  13271. newTexture.wrapU = this.wrapU;
  13272. newTexture.wrapV = this.wrapV;
  13273. newTexture.coordinatesIndex = this.coordinatesIndex;
  13274. newTexture.coordinatesMode = this.coordinatesMode;
  13275. return newTexture;
  13276. };
  13277. // Methods
  13278. CubeTexture.prototype.delayLoad = function () {
  13279. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13280. return;
  13281. }
  13282. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13283. this._texture = this._getFromCache(this.url, this._noMipmap);
  13284. if (!this._texture) {
  13285. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13286. }
  13287. };
  13288. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13289. return this._textureMatrix;
  13290. };
  13291. return CubeTexture;
  13292. })(BABYLON.BaseTexture);
  13293. BABYLON.CubeTexture = CubeTexture;
  13294. })(BABYLON || (BABYLON = {}));
  13295. //# sourceMappingURL=babylon.cubeTexture.js.map
  13296. var BABYLON;
  13297. (function (BABYLON) {
  13298. var RenderTargetTexture = (function (_super) {
  13299. __extends(RenderTargetTexture, _super);
  13300. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13301. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13302. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13303. _super.call(this, null, scene, !generateMipMaps);
  13304. this.renderList = new Array();
  13305. this.renderParticles = true;
  13306. this.renderSprites = false;
  13307. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13308. this._currentRefreshId = -1;
  13309. this._refreshRate = 1;
  13310. this.name = name;
  13311. this.isRenderTarget = true;
  13312. this._size = size;
  13313. this._generateMipMaps = generateMipMaps;
  13314. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13315. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13316. // Rendering groups
  13317. this._renderingManager = new BABYLON.RenderingManager(scene);
  13318. }
  13319. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13320. this._currentRefreshId = -1;
  13321. };
  13322. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13323. get: function () {
  13324. return this._refreshRate;
  13325. },
  13326. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13327. set: function (value) {
  13328. this._refreshRate = value;
  13329. this.resetRefreshCounter();
  13330. },
  13331. enumerable: true,
  13332. configurable: true
  13333. });
  13334. RenderTargetTexture.prototype._shouldRender = function () {
  13335. if (this._currentRefreshId === -1) {
  13336. this._currentRefreshId = 1;
  13337. return true;
  13338. }
  13339. if (this.refreshRate === this._currentRefreshId) {
  13340. this._currentRefreshId = 1;
  13341. return true;
  13342. }
  13343. this._currentRefreshId++;
  13344. return false;
  13345. };
  13346. RenderTargetTexture.prototype.isReady = function () {
  13347. if (!this.getScene().renderTargetsEnabled) {
  13348. return false;
  13349. }
  13350. return _super.prototype.isReady.call(this);
  13351. };
  13352. RenderTargetTexture.prototype.getRenderSize = function () {
  13353. return this._size;
  13354. };
  13355. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13356. get: function () {
  13357. return true;
  13358. },
  13359. enumerable: true,
  13360. configurable: true
  13361. });
  13362. RenderTargetTexture.prototype.scale = function (ratio) {
  13363. var newSize = this._size * ratio;
  13364. this.resize(newSize, this._generateMipMaps);
  13365. };
  13366. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13367. this.releaseInternalTexture();
  13368. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13369. };
  13370. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13371. var scene = this.getScene();
  13372. var engine = scene.getEngine();
  13373. if (this._waitingRenderList) {
  13374. this.renderList = [];
  13375. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13376. var id = this._waitingRenderList[index];
  13377. this.renderList.push(scene.getMeshByID(id));
  13378. }
  13379. delete this._waitingRenderList;
  13380. }
  13381. if (this.renderList && this.renderList.length === 0) {
  13382. return;
  13383. }
  13384. // Bind
  13385. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13386. engine.bindFramebuffer(this._texture);
  13387. }
  13388. this._renderingManager.reset();
  13389. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13390. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13391. var mesh = currentRenderList[meshIndex];
  13392. if (mesh) {
  13393. if (!mesh.isReady()) {
  13394. // Reset _currentRefreshId
  13395. this.resetRefreshCounter();
  13396. continue;
  13397. }
  13398. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13399. mesh._activate(scene.getRenderId());
  13400. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13401. var subMesh = mesh.subMeshes[subIndex];
  13402. scene._activeIndices += subMesh.indexCount;
  13403. this._renderingManager.dispatch(subMesh);
  13404. }
  13405. }
  13406. }
  13407. }
  13408. if (this.onBeforeRender) {
  13409. this.onBeforeRender();
  13410. }
  13411. // Clear
  13412. if (this.onClear) {
  13413. this.onClear(engine);
  13414. }
  13415. else {
  13416. engine.clear(scene.clearColor, true, true);
  13417. }
  13418. if (!this._doNotChangeAspectRatio) {
  13419. scene.updateTransformMatrix(true);
  13420. }
  13421. // Render
  13422. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13423. if (useCameraPostProcess) {
  13424. scene.postProcessManager._finalizeFrame(false, this._texture);
  13425. }
  13426. if (!this._doNotChangeAspectRatio) {
  13427. scene.updateTransformMatrix(true);
  13428. }
  13429. if (this.onAfterRender) {
  13430. this.onAfterRender();
  13431. }
  13432. // Dump ?
  13433. if (dumpForDebug) {
  13434. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13435. }
  13436. // Unbind
  13437. engine.unBindFramebuffer(this._texture);
  13438. if (this.onAfterUnbind) {
  13439. this.onAfterUnbind();
  13440. }
  13441. };
  13442. RenderTargetTexture.prototype.clone = function () {
  13443. var textureSize = this.getSize();
  13444. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13445. // Base texture
  13446. newTexture.hasAlpha = this.hasAlpha;
  13447. newTexture.level = this.level;
  13448. // RenderTarget Texture
  13449. newTexture.coordinatesMode = this.coordinatesMode;
  13450. newTexture.renderList = this.renderList.slice(0);
  13451. return newTexture;
  13452. };
  13453. return RenderTargetTexture;
  13454. })(BABYLON.Texture);
  13455. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13456. })(BABYLON || (BABYLON = {}));
  13457. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13458. var BABYLON;
  13459. (function (BABYLON) {
  13460. var ProceduralTexture = (function (_super) {
  13461. __extends(ProceduralTexture, _super);
  13462. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13463. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13464. _super.call(this, null, scene, !generateMipMaps);
  13465. this._currentRefreshId = -1;
  13466. this._refreshRate = 1;
  13467. this._vertexDeclaration = [2];
  13468. this._vertexStrideSize = 2 * 4;
  13469. this._uniforms = new Array();
  13470. this._samplers = new Array();
  13471. this._textures = new Array();
  13472. this._floats = new Array();
  13473. this._floatsArrays = {};
  13474. this._colors3 = new Array();
  13475. this._colors4 = new Array();
  13476. this._vectors2 = new Array();
  13477. this._vectors3 = new Array();
  13478. this._matrices = new Array();
  13479. this._fallbackTextureUsed = false;
  13480. scene._proceduralTextures.push(this);
  13481. this.name = name;
  13482. this.isRenderTarget = true;
  13483. this._size = size;
  13484. this._generateMipMaps = generateMipMaps;
  13485. this.setFragment(fragment);
  13486. this._fallbackTexture = fallbackTexture;
  13487. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13488. // VBO
  13489. var vertices = [];
  13490. vertices.push(1, 1);
  13491. vertices.push(-1, 1);
  13492. vertices.push(-1, -1);
  13493. vertices.push(1, -1);
  13494. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13495. // Indices
  13496. var indices = [];
  13497. indices.push(0);
  13498. indices.push(1);
  13499. indices.push(2);
  13500. indices.push(0);
  13501. indices.push(2);
  13502. indices.push(3);
  13503. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13504. }
  13505. ProceduralTexture.prototype.reset = function () {
  13506. if (this._effect === undefined) {
  13507. return;
  13508. }
  13509. var engine = this.getScene().getEngine();
  13510. engine._releaseEffect(this._effect);
  13511. };
  13512. ProceduralTexture.prototype.isReady = function () {
  13513. var _this = this;
  13514. var engine = this.getScene().getEngine();
  13515. var shaders;
  13516. if (!this._fragment) {
  13517. return false;
  13518. }
  13519. if (this._fallbackTextureUsed) {
  13520. return true;
  13521. }
  13522. if (this._fragment.fragmentElement !== undefined) {
  13523. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13524. }
  13525. else {
  13526. shaders = { vertex: "procedural", fragment: this._fragment };
  13527. }
  13528. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13529. _this.releaseInternalTexture();
  13530. if (_this._fallbackTexture) {
  13531. _this._texture = _this._fallbackTexture._texture;
  13532. _this._texture.references++;
  13533. }
  13534. _this._fallbackTextureUsed = true;
  13535. });
  13536. return this._effect.isReady();
  13537. };
  13538. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13539. this._currentRefreshId = -1;
  13540. };
  13541. ProceduralTexture.prototype.setFragment = function (fragment) {
  13542. this._fragment = fragment;
  13543. };
  13544. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13545. get: function () {
  13546. return this._refreshRate;
  13547. },
  13548. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13549. set: function (value) {
  13550. this._refreshRate = value;
  13551. this.resetRefreshCounter();
  13552. },
  13553. enumerable: true,
  13554. configurable: true
  13555. });
  13556. ProceduralTexture.prototype._shouldRender = function () {
  13557. if (!this.isReady() || !this._texture) {
  13558. return false;
  13559. }
  13560. if (this._fallbackTextureUsed) {
  13561. return false;
  13562. }
  13563. if (this._currentRefreshId === -1) {
  13564. this._currentRefreshId = 1;
  13565. return true;
  13566. }
  13567. if (this.refreshRate === this._currentRefreshId) {
  13568. this._currentRefreshId = 1;
  13569. return true;
  13570. }
  13571. this._currentRefreshId++;
  13572. return false;
  13573. };
  13574. ProceduralTexture.prototype.getRenderSize = function () {
  13575. return this._size;
  13576. };
  13577. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13578. if (this._fallbackTextureUsed) {
  13579. return;
  13580. }
  13581. this.releaseInternalTexture();
  13582. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13583. };
  13584. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13585. if (this._uniforms.indexOf(uniformName) === -1) {
  13586. this._uniforms.push(uniformName);
  13587. }
  13588. };
  13589. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13590. if (this._samplers.indexOf(name) === -1) {
  13591. this._samplers.push(name);
  13592. }
  13593. this._textures[name] = texture;
  13594. return this;
  13595. };
  13596. ProceduralTexture.prototype.setFloat = function (name, value) {
  13597. this._checkUniform(name);
  13598. this._floats[name] = value;
  13599. return this;
  13600. };
  13601. ProceduralTexture.prototype.setFloats = function (name, value) {
  13602. this._checkUniform(name);
  13603. this._floatsArrays[name] = value;
  13604. return this;
  13605. };
  13606. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13607. this._checkUniform(name);
  13608. this._colors3[name] = value;
  13609. return this;
  13610. };
  13611. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13612. this._checkUniform(name);
  13613. this._colors4[name] = value;
  13614. return this;
  13615. };
  13616. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13617. this._checkUniform(name);
  13618. this._vectors2[name] = value;
  13619. return this;
  13620. };
  13621. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13622. this._checkUniform(name);
  13623. this._vectors3[name] = value;
  13624. return this;
  13625. };
  13626. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13627. this._checkUniform(name);
  13628. this._matrices[name] = value;
  13629. return this;
  13630. };
  13631. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13632. var scene = this.getScene();
  13633. var engine = scene.getEngine();
  13634. engine.bindFramebuffer(this._texture);
  13635. // Clear
  13636. engine.clear(scene.clearColor, true, true);
  13637. // Render
  13638. engine.enableEffect(this._effect);
  13639. engine.setState(false);
  13640. for (var name in this._textures) {
  13641. this._effect.setTexture(name, this._textures[name]);
  13642. }
  13643. for (name in this._floats) {
  13644. this._effect.setFloat(name, this._floats[name]);
  13645. }
  13646. for (name in this._floatsArrays) {
  13647. this._effect.setArray(name, this._floatsArrays[name]);
  13648. }
  13649. for (name in this._colors3) {
  13650. this._effect.setColor3(name, this._colors3[name]);
  13651. }
  13652. for (name in this._colors4) {
  13653. var color = this._colors4[name];
  13654. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13655. }
  13656. for (name in this._vectors2) {
  13657. this._effect.setVector2(name, this._vectors2[name]);
  13658. }
  13659. for (name in this._vectors3) {
  13660. this._effect.setVector3(name, this._vectors3[name]);
  13661. }
  13662. for (name in this._matrices) {
  13663. this._effect.setMatrix(name, this._matrices[name]);
  13664. }
  13665. // VBOs
  13666. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13667. // Draw order
  13668. engine.draw(true, 0, 6);
  13669. // Unbind
  13670. engine.unBindFramebuffer(this._texture);
  13671. };
  13672. ProceduralTexture.prototype.clone = function () {
  13673. var textureSize = this.getSize();
  13674. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13675. // Base texture
  13676. newTexture.hasAlpha = this.hasAlpha;
  13677. newTexture.level = this.level;
  13678. // RenderTarget Texture
  13679. newTexture.coordinatesMode = this.coordinatesMode;
  13680. return newTexture;
  13681. };
  13682. ProceduralTexture.prototype.dispose = function () {
  13683. var index = this.getScene()._proceduralTextures.indexOf(this);
  13684. if (index >= 0) {
  13685. this.getScene()._proceduralTextures.splice(index, 1);
  13686. }
  13687. _super.prototype.dispose.call(this);
  13688. };
  13689. return ProceduralTexture;
  13690. })(BABYLON.Texture);
  13691. BABYLON.ProceduralTexture = ProceduralTexture;
  13692. })(BABYLON || (BABYLON = {}));
  13693. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13694. var BABYLON;
  13695. (function (BABYLON) {
  13696. var WoodProceduralTexture = (function (_super) {
  13697. __extends(WoodProceduralTexture, _super);
  13698. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13699. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13700. this._ampScale = 100.0;
  13701. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13702. this.updateShaderUniforms();
  13703. this.refreshRate = 0;
  13704. }
  13705. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13706. this.setFloat("ampScale", this._ampScale);
  13707. this.setColor3("woodColor", this._woodColor);
  13708. };
  13709. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13710. get: function () {
  13711. return this._ampScale;
  13712. },
  13713. set: function (value) {
  13714. this._ampScale = value;
  13715. this.updateShaderUniforms();
  13716. },
  13717. enumerable: true,
  13718. configurable: true
  13719. });
  13720. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13721. get: function () {
  13722. return this._woodColor;
  13723. },
  13724. set: function (value) {
  13725. this._woodColor = value;
  13726. this.updateShaderUniforms();
  13727. },
  13728. enumerable: true,
  13729. configurable: true
  13730. });
  13731. return WoodProceduralTexture;
  13732. })(BABYLON.ProceduralTexture);
  13733. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13734. var FireProceduralTexture = (function (_super) {
  13735. __extends(FireProceduralTexture, _super);
  13736. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13737. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13738. this._time = 0.0;
  13739. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13740. this._autoGenerateTime = true;
  13741. this._alphaThreshold = 0.5;
  13742. this._fireColors = FireProceduralTexture.RedFireColors;
  13743. this.updateShaderUniforms();
  13744. this.refreshRate = 1;
  13745. }
  13746. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13747. this.setFloat("time", this._time);
  13748. this.setVector2("speed", this._speed);
  13749. this.setColor3("c1", this._fireColors[0]);
  13750. this.setColor3("c2", this._fireColors[1]);
  13751. this.setColor3("c3", this._fireColors[2]);
  13752. this.setColor3("c4", this._fireColors[3]);
  13753. this.setColor3("c5", this._fireColors[4]);
  13754. this.setColor3("c6", this._fireColors[5]);
  13755. this.setFloat("alphaThreshold", this._alphaThreshold);
  13756. };
  13757. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13758. if (this._autoGenerateTime) {
  13759. this._time += this.getScene().getAnimationRatio() * 0.03;
  13760. this.updateShaderUniforms();
  13761. }
  13762. _super.prototype.render.call(this, useCameraPostProcess);
  13763. };
  13764. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13765. get: function () {
  13766. return [
  13767. new BABYLON.Color3(0.5, 0.0, 1.0),
  13768. new BABYLON.Color3(0.9, 0.0, 1.0),
  13769. new BABYLON.Color3(0.2, 0.0, 1.0),
  13770. new BABYLON.Color3(1.0, 0.9, 1.0),
  13771. new BABYLON.Color3(0.1, 0.1, 1.0),
  13772. new BABYLON.Color3(0.9, 0.9, 1.0)
  13773. ];
  13774. },
  13775. enumerable: true,
  13776. configurable: true
  13777. });
  13778. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13779. get: function () {
  13780. return [
  13781. new BABYLON.Color3(0.5, 1.0, 0.0),
  13782. new BABYLON.Color3(0.5, 1.0, 0.0),
  13783. new BABYLON.Color3(0.3, 0.4, 0.0),
  13784. new BABYLON.Color3(0.5, 1.0, 0.0),
  13785. new BABYLON.Color3(0.2, 0.0, 0.0),
  13786. new BABYLON.Color3(0.5, 1.0, 0.0)
  13787. ];
  13788. },
  13789. enumerable: true,
  13790. configurable: true
  13791. });
  13792. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13793. get: function () {
  13794. return [
  13795. new BABYLON.Color3(0.5, 0.0, 0.1),
  13796. new BABYLON.Color3(0.9, 0.0, 0.0),
  13797. new BABYLON.Color3(0.2, 0.0, 0.0),
  13798. new BABYLON.Color3(1.0, 0.9, 0.0),
  13799. new BABYLON.Color3(0.1, 0.1, 0.1),
  13800. new BABYLON.Color3(0.9, 0.9, 0.9)
  13801. ];
  13802. },
  13803. enumerable: true,
  13804. configurable: true
  13805. });
  13806. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13807. get: function () {
  13808. return [
  13809. new BABYLON.Color3(0.1, 0.0, 0.5),
  13810. new BABYLON.Color3(0.0, 0.0, 0.5),
  13811. new BABYLON.Color3(0.1, 0.0, 0.2),
  13812. new BABYLON.Color3(0.0, 0.0, 1.0),
  13813. new BABYLON.Color3(0.1, 0.2, 0.3),
  13814. new BABYLON.Color3(0.0, 0.2, 0.9)
  13815. ];
  13816. },
  13817. enumerable: true,
  13818. configurable: true
  13819. });
  13820. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13821. get: function () {
  13822. return this._fireColors;
  13823. },
  13824. set: function (value) {
  13825. this._fireColors = value;
  13826. this.updateShaderUniforms();
  13827. },
  13828. enumerable: true,
  13829. configurable: true
  13830. });
  13831. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13832. get: function () {
  13833. return this._time;
  13834. },
  13835. set: function (value) {
  13836. this._time = value;
  13837. this.updateShaderUniforms();
  13838. },
  13839. enumerable: true,
  13840. configurable: true
  13841. });
  13842. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13843. get: function () {
  13844. return this._speed;
  13845. },
  13846. set: function (value) {
  13847. this._speed = value;
  13848. this.updateShaderUniforms();
  13849. },
  13850. enumerable: true,
  13851. configurable: true
  13852. });
  13853. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13854. get: function () {
  13855. return this._alphaThreshold;
  13856. },
  13857. set: function (value) {
  13858. this._alphaThreshold = value;
  13859. this.updateShaderUniforms();
  13860. },
  13861. enumerable: true,
  13862. configurable: true
  13863. });
  13864. return FireProceduralTexture;
  13865. })(BABYLON.ProceduralTexture);
  13866. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13867. var CloudProceduralTexture = (function (_super) {
  13868. __extends(CloudProceduralTexture, _super);
  13869. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13870. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13871. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13872. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13873. this.updateShaderUniforms();
  13874. this.refreshRate = 0;
  13875. }
  13876. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13877. this.setColor3("skyColor", this._skyColor);
  13878. this.setColor3("cloudColor", this._cloudColor);
  13879. };
  13880. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13881. get: function () {
  13882. return this._skyColor;
  13883. },
  13884. set: function (value) {
  13885. this._skyColor = value;
  13886. this.updateShaderUniforms();
  13887. },
  13888. enumerable: true,
  13889. configurable: true
  13890. });
  13891. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13892. get: function () {
  13893. return this._cloudColor;
  13894. },
  13895. set: function (value) {
  13896. this._cloudColor = value;
  13897. this.updateShaderUniforms();
  13898. },
  13899. enumerable: true,
  13900. configurable: true
  13901. });
  13902. return CloudProceduralTexture;
  13903. })(BABYLON.ProceduralTexture);
  13904. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13905. var GrassProceduralTexture = (function (_super) {
  13906. __extends(GrassProceduralTexture, _super);
  13907. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13908. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13909. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13910. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13911. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13912. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13913. this._grassColors = [
  13914. new BABYLON.Color3(0.29, 0.38, 0.02),
  13915. new BABYLON.Color3(0.36, 0.49, 0.09),
  13916. new BABYLON.Color3(0.51, 0.6, 0.28)
  13917. ];
  13918. this.updateShaderUniforms();
  13919. this.refreshRate = 0;
  13920. }
  13921. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13922. this.setColor3("herb1Color", this._grassColors[0]);
  13923. this.setColor3("herb2Color", this._grassColors[1]);
  13924. this.setColor3("herb3Color", this._grassColors[2]);
  13925. this.setColor3("groundColor", this._groundColor);
  13926. };
  13927. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13928. get: function () {
  13929. return this._grassColors;
  13930. },
  13931. set: function (value) {
  13932. this._grassColors = value;
  13933. this.updateShaderUniforms();
  13934. },
  13935. enumerable: true,
  13936. configurable: true
  13937. });
  13938. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13939. get: function () {
  13940. return this._groundColor;
  13941. },
  13942. set: function (value) {
  13943. this.groundColor = value;
  13944. this.updateShaderUniforms();
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. return GrassProceduralTexture;
  13950. })(BABYLON.ProceduralTexture);
  13951. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13952. var RoadProceduralTexture = (function (_super) {
  13953. __extends(RoadProceduralTexture, _super);
  13954. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13955. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13956. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13957. this.updateShaderUniforms();
  13958. this.refreshRate = 0;
  13959. }
  13960. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13961. this.setColor3("roadColor", this._roadColor);
  13962. };
  13963. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13964. get: function () {
  13965. return this._roadColor;
  13966. },
  13967. set: function (value) {
  13968. this._roadColor = value;
  13969. this.updateShaderUniforms();
  13970. },
  13971. enumerable: true,
  13972. configurable: true
  13973. });
  13974. return RoadProceduralTexture;
  13975. })(BABYLON.ProceduralTexture);
  13976. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13977. var BrickProceduralTexture = (function (_super) {
  13978. __extends(BrickProceduralTexture, _super);
  13979. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13980. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13981. this._numberOfBricksHeight = 15;
  13982. this._numberOfBricksWidth = 5;
  13983. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13984. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13985. this.updateShaderUniforms();
  13986. this.refreshRate = 0;
  13987. }
  13988. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13989. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13990. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13991. this.setColor3("brickColor", this._brickColor);
  13992. this.setColor3("jointColor", this._jointColor);
  13993. };
  13994. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13995. get: function () {
  13996. return this._numberOfBricksHeight;
  13997. },
  13998. set: function (value) {
  13999. this._numberOfBricksHeight = value;
  14000. this.updateShaderUniforms();
  14001. },
  14002. enumerable: true,
  14003. configurable: true
  14004. });
  14005. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  14006. get: function () {
  14007. return this._numberOfBricksWidth;
  14008. },
  14009. set: function (value) {
  14010. this._numberOfBricksHeight = value;
  14011. this.updateShaderUniforms();
  14012. },
  14013. enumerable: true,
  14014. configurable: true
  14015. });
  14016. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  14017. get: function () {
  14018. return this._jointColor;
  14019. },
  14020. set: function (value) {
  14021. this._jointColor = value;
  14022. this.updateShaderUniforms();
  14023. },
  14024. enumerable: true,
  14025. configurable: true
  14026. });
  14027. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  14028. get: function () {
  14029. return this._brickColor;
  14030. },
  14031. set: function (value) {
  14032. this._brickColor = value;
  14033. this.updateShaderUniforms();
  14034. },
  14035. enumerable: true,
  14036. configurable: true
  14037. });
  14038. return BrickProceduralTexture;
  14039. })(BABYLON.ProceduralTexture);
  14040. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  14041. var MarbleProceduralTexture = (function (_super) {
  14042. __extends(MarbleProceduralTexture, _super);
  14043. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  14044. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  14045. this._numberOfTilesHeight = 3;
  14046. this._numberOfTilesWidth = 3;
  14047. this._amplitude = 9.0;
  14048. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  14049. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  14050. this.updateShaderUniforms();
  14051. this.refreshRate = 0;
  14052. }
  14053. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  14054. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  14055. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  14056. this.setFloat("amplitude", this._amplitude);
  14057. this.setColor3("marbleColor", this._marbleColor);
  14058. this.setColor3("jointColor", this._jointColor);
  14059. };
  14060. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  14061. get: function () {
  14062. return this._numberOfTilesHeight;
  14063. },
  14064. set: function (value) {
  14065. this._numberOfTilesHeight = value;
  14066. this.updateShaderUniforms();
  14067. },
  14068. enumerable: true,
  14069. configurable: true
  14070. });
  14071. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  14072. get: function () {
  14073. return this._numberOfTilesWidth;
  14074. },
  14075. set: function (value) {
  14076. this._numberOfTilesWidth = value;
  14077. this.updateShaderUniforms();
  14078. },
  14079. enumerable: true,
  14080. configurable: true
  14081. });
  14082. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  14083. get: function () {
  14084. return this._jointColor;
  14085. },
  14086. set: function (value) {
  14087. this._jointColor = value;
  14088. this.updateShaderUniforms();
  14089. },
  14090. enumerable: true,
  14091. configurable: true
  14092. });
  14093. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  14094. get: function () {
  14095. return this._marbleColor;
  14096. },
  14097. set: function (value) {
  14098. this._marbleColor = value;
  14099. this.updateShaderUniforms();
  14100. },
  14101. enumerable: true,
  14102. configurable: true
  14103. });
  14104. return MarbleProceduralTexture;
  14105. })(BABYLON.ProceduralTexture);
  14106. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  14107. })(BABYLON || (BABYLON = {}));
  14108. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  14109. var BABYLON;
  14110. (function (BABYLON) {
  14111. var CustomProceduralTexture = (function (_super) {
  14112. __extends(CustomProceduralTexture, _super);
  14113. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  14114. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  14115. this._animate = true;
  14116. this._time = 0;
  14117. this._texturePath = texturePath;
  14118. //Try to load json
  14119. this.loadJson(texturePath);
  14120. this.refreshRate = 1;
  14121. }
  14122. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  14123. var _this = this;
  14124. var that = this;
  14125. function noConfigFile() {
  14126. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  14127. try {
  14128. that.setFragment(that._texturePath);
  14129. }
  14130. catch (ex) {
  14131. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  14132. }
  14133. }
  14134. var configFileUrl = jsonUrl + "/config.json";
  14135. var xhr = new XMLHttpRequest();
  14136. xhr.open("GET", configFileUrl, true);
  14137. xhr.addEventListener("load", function () {
  14138. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14139. try {
  14140. _this._config = JSON.parse(xhr.response);
  14141. _this.updateShaderUniforms();
  14142. _this.updateTextures();
  14143. _this.setFragment(_this._texturePath + "/custom");
  14144. _this._animate = _this._config.animate;
  14145. _this.refreshRate = _this._config.refreshrate;
  14146. }
  14147. catch (ex) {
  14148. noConfigFile();
  14149. }
  14150. }
  14151. else {
  14152. noConfigFile();
  14153. }
  14154. }, false);
  14155. xhr.addEventListener("error", function () {
  14156. noConfigFile();
  14157. }, false);
  14158. try {
  14159. xhr.send();
  14160. }
  14161. catch (ex) {
  14162. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  14163. }
  14164. };
  14165. CustomProceduralTexture.prototype.isReady = function () {
  14166. if (!_super.prototype.isReady.call(this)) {
  14167. return false;
  14168. }
  14169. for (var name in this._textures) {
  14170. var texture = this._textures[name];
  14171. if (!texture.isReady()) {
  14172. return false;
  14173. }
  14174. }
  14175. return true;
  14176. };
  14177. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  14178. if (this._animate) {
  14179. this._time += this.getScene().getAnimationRatio() * 0.03;
  14180. this.updateShaderUniforms();
  14181. }
  14182. _super.prototype.render.call(this, useCameraPostProcess);
  14183. };
  14184. CustomProceduralTexture.prototype.updateTextures = function () {
  14185. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  14186. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  14187. }
  14188. };
  14189. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  14190. if (this._config) {
  14191. for (var j = 0; j < this._config.uniforms.length; j++) {
  14192. var uniform = this._config.uniforms[j];
  14193. switch (uniform.type) {
  14194. case "float":
  14195. this.setFloat(uniform.name, uniform.value);
  14196. break;
  14197. case "color3":
  14198. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  14199. break;
  14200. case "color4":
  14201. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  14202. break;
  14203. case "vector2":
  14204. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  14205. break;
  14206. case "vector3":
  14207. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  14208. break;
  14209. }
  14210. }
  14211. }
  14212. this.setFloat("time", this._time);
  14213. };
  14214. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  14215. get: function () {
  14216. return this._animate;
  14217. },
  14218. set: function (value) {
  14219. this._animate = value;
  14220. },
  14221. enumerable: true,
  14222. configurable: true
  14223. });
  14224. return CustomProceduralTexture;
  14225. })(BABYLON.ProceduralTexture);
  14226. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  14227. })(BABYLON || (BABYLON = {}));
  14228. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  14229. var BABYLON;
  14230. (function (BABYLON) {
  14231. var MirrorTexture = (function (_super) {
  14232. __extends(MirrorTexture, _super);
  14233. function MirrorTexture(name, size, scene, generateMipMaps) {
  14234. var _this = this;
  14235. _super.call(this, name, size, scene, generateMipMaps, true);
  14236. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  14237. this._transformMatrix = BABYLON.Matrix.Zero();
  14238. this._mirrorMatrix = BABYLON.Matrix.Zero();
  14239. this.onBeforeRender = function () {
  14240. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  14241. _this._savedViewMatrix = scene.getViewMatrix();
  14242. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  14243. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  14244. scene.clipPlane = _this.mirrorPlane;
  14245. scene.getEngine().cullBackFaces = false;
  14246. };
  14247. this.onAfterRender = function () {
  14248. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  14249. scene.getEngine().cullBackFaces = true;
  14250. delete scene.clipPlane;
  14251. };
  14252. }
  14253. MirrorTexture.prototype.clone = function () {
  14254. var textureSize = this.getSize();
  14255. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14256. // Base texture
  14257. newTexture.hasAlpha = this.hasAlpha;
  14258. newTexture.level = this.level;
  14259. // Mirror Texture
  14260. newTexture.mirrorPlane = this.mirrorPlane.clone();
  14261. newTexture.renderList = this.renderList.slice(0);
  14262. return newTexture;
  14263. };
  14264. return MirrorTexture;
  14265. })(BABYLON.RenderTargetTexture);
  14266. BABYLON.MirrorTexture = MirrorTexture;
  14267. })(BABYLON || (BABYLON = {}));
  14268. //# sourceMappingURL=babylon.mirrorTexture.js.map
  14269. var BABYLON;
  14270. (function (BABYLON) {
  14271. var DynamicTexture = (function (_super) {
  14272. __extends(DynamicTexture, _super);
  14273. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  14274. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14275. _super.call(this, null, scene, !generateMipMaps);
  14276. this.name = name;
  14277. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14278. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14279. this._generateMipMaps = generateMipMaps;
  14280. if (options.getContext) {
  14281. this._canvas = options;
  14282. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14283. }
  14284. else {
  14285. this._canvas = document.createElement("canvas");
  14286. if (options.width) {
  14287. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14288. }
  14289. else {
  14290. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14291. }
  14292. }
  14293. var textureSize = this.getSize();
  14294. this._canvas.width = textureSize.width;
  14295. this._canvas.height = textureSize.height;
  14296. this._context = this._canvas.getContext("2d");
  14297. }
  14298. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14299. get: function () {
  14300. return true;
  14301. },
  14302. enumerable: true,
  14303. configurable: true
  14304. });
  14305. DynamicTexture.prototype.scale = function (ratio) {
  14306. var textureSize = this.getSize();
  14307. textureSize.width *= ratio;
  14308. textureSize.height *= ratio;
  14309. this._canvas.width = textureSize.width;
  14310. this._canvas.height = textureSize.height;
  14311. this.releaseInternalTexture();
  14312. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14313. };
  14314. DynamicTexture.prototype.getContext = function () {
  14315. return this._context;
  14316. };
  14317. DynamicTexture.prototype.clear = function () {
  14318. var size = this.getSize();
  14319. this._context.fillRect(0, 0, size.width, size.height);
  14320. };
  14321. DynamicTexture.prototype.update = function (invertY) {
  14322. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14323. };
  14324. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14325. if (update === void 0) { update = true; }
  14326. var size = this.getSize();
  14327. if (clearColor) {
  14328. this._context.fillStyle = clearColor;
  14329. this._context.fillRect(0, 0, size.width, size.height);
  14330. }
  14331. this._context.font = font;
  14332. if (x === null) {
  14333. var textSize = this._context.measureText(text);
  14334. x = (size.width - textSize.width) / 2;
  14335. }
  14336. this._context.fillStyle = color;
  14337. this._context.fillText(text, x, y);
  14338. if (update) {
  14339. this.update(invertY);
  14340. }
  14341. };
  14342. DynamicTexture.prototype.clone = function () {
  14343. var textureSize = this.getSize();
  14344. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14345. // Base texture
  14346. newTexture.hasAlpha = this.hasAlpha;
  14347. newTexture.level = this.level;
  14348. // Dynamic Texture
  14349. newTexture.wrapU = this.wrapU;
  14350. newTexture.wrapV = this.wrapV;
  14351. return newTexture;
  14352. };
  14353. return DynamicTexture;
  14354. })(BABYLON.Texture);
  14355. BABYLON.DynamicTexture = DynamicTexture;
  14356. })(BABYLON || (BABYLON = {}));
  14357. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14358. var BABYLON;
  14359. (function (BABYLON) {
  14360. var VideoTexture = (function (_super) {
  14361. __extends(VideoTexture, _super);
  14362. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14363. var _this = this;
  14364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14365. _super.call(this, null, scene, !generateMipMaps, invertY);
  14366. this._autoLaunch = true;
  14367. this.name = name;
  14368. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14369. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14370. var requiredWidth = size.width || size;
  14371. var requiredHeight = size.height || size;
  14372. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14373. var textureSize = this.getSize();
  14374. this.video = document.createElement("video");
  14375. this.video.width = textureSize.width;
  14376. this.video.height = textureSize.height;
  14377. this.video.autoplay = false;
  14378. this.video.loop = true;
  14379. this.video.addEventListener("canplaythrough", function () {
  14380. if (_this._texture) {
  14381. _this._texture.isReady = true;
  14382. }
  14383. });
  14384. urls.forEach(function (url) {
  14385. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14386. var source = document.createElement("source");
  14387. source.src = url;
  14388. _this.video.appendChild(source);
  14389. });
  14390. this._lastUpdate = BABYLON.Tools.Now;
  14391. }
  14392. VideoTexture.prototype.update = function () {
  14393. if (this._autoLaunch) {
  14394. this._autoLaunch = false;
  14395. this.video.play();
  14396. }
  14397. var now = BABYLON.Tools.Now;
  14398. if (now - this._lastUpdate < 15) {
  14399. return false;
  14400. }
  14401. this._lastUpdate = now;
  14402. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14403. return true;
  14404. };
  14405. return VideoTexture;
  14406. })(BABYLON.Texture);
  14407. BABYLON.VideoTexture = VideoTexture;
  14408. })(BABYLON || (BABYLON = {}));
  14409. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14410. (function (BABYLON) {
  14411. var EffectFallbacks = (function () {
  14412. function EffectFallbacks() {
  14413. this._defines = {};
  14414. this._currentRank = 32;
  14415. this._maxRank = -1;
  14416. }
  14417. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14418. if (!this._defines[rank]) {
  14419. if (rank < this._currentRank) {
  14420. this._currentRank = rank;
  14421. }
  14422. if (rank > this._maxRank) {
  14423. this._maxRank = rank;
  14424. }
  14425. this._defines[rank] = new Array();
  14426. }
  14427. this._defines[rank].push(define);
  14428. };
  14429. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14430. get: function () {
  14431. return this._currentRank <= this._maxRank;
  14432. },
  14433. enumerable: true,
  14434. configurable: true
  14435. });
  14436. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14437. var currentFallbacks = this._defines[this._currentRank];
  14438. for (var index = 0; index < currentFallbacks.length; index++) {
  14439. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14440. }
  14441. this._currentRank++;
  14442. return currentDefines;
  14443. };
  14444. return EffectFallbacks;
  14445. })();
  14446. BABYLON.EffectFallbacks = EffectFallbacks;
  14447. var Effect = (function () {
  14448. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14449. var _this = this;
  14450. this._isReady = false;
  14451. this._compilationError = "";
  14452. this._valueCache = [];
  14453. this._engine = engine;
  14454. this.name = baseName;
  14455. this.defines = defines;
  14456. this._uniformsNames = uniformsNames.concat(samplers);
  14457. this._samplers = samplers;
  14458. this._attributesNames = attributesNames;
  14459. this.onError = onError;
  14460. this.onCompiled = onCompiled;
  14461. var vertexSource;
  14462. var fragmentSource;
  14463. if (baseName.vertexElement) {
  14464. vertexSource = document.getElementById(baseName.vertexElement);
  14465. if (!vertexSource) {
  14466. vertexSource = baseName.vertexElement;
  14467. }
  14468. }
  14469. else {
  14470. vertexSource = baseName.vertex || baseName;
  14471. }
  14472. if (baseName.fragmentElement) {
  14473. fragmentSource = document.getElementById(baseName.fragmentElement);
  14474. if (!fragmentSource) {
  14475. fragmentSource = baseName.fragmentElement;
  14476. }
  14477. }
  14478. else {
  14479. fragmentSource = baseName.fragment || baseName;
  14480. }
  14481. this._loadVertexShader(vertexSource, function (vertexCode) {
  14482. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14483. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14484. });
  14485. });
  14486. }
  14487. // Properties
  14488. Effect.prototype.isReady = function () {
  14489. return this._isReady;
  14490. };
  14491. Effect.prototype.getProgram = function () {
  14492. return this._program;
  14493. };
  14494. Effect.prototype.getAttributesNames = function () {
  14495. return this._attributesNames;
  14496. };
  14497. Effect.prototype.getAttributeLocation = function (index) {
  14498. return this._attributes[index];
  14499. };
  14500. Effect.prototype.getAttributeLocationByName = function (name) {
  14501. var index = this._attributesNames.indexOf(name);
  14502. return this._attributes[index];
  14503. };
  14504. Effect.prototype.getAttributesCount = function () {
  14505. return this._attributes.length;
  14506. };
  14507. Effect.prototype.getUniformIndex = function (uniformName) {
  14508. return this._uniformsNames.indexOf(uniformName);
  14509. };
  14510. Effect.prototype.getUniform = function (uniformName) {
  14511. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14512. };
  14513. Effect.prototype.getSamplers = function () {
  14514. return this._samplers;
  14515. };
  14516. Effect.prototype.getCompilationError = function () {
  14517. return this._compilationError;
  14518. };
  14519. // Methods
  14520. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14521. // DOM element ?
  14522. if (vertex instanceof HTMLElement) {
  14523. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14524. callback(vertexCode);
  14525. return;
  14526. }
  14527. // Is in local store ?
  14528. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14529. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14530. return;
  14531. }
  14532. var vertexShaderUrl;
  14533. if (vertex[0] === ".") {
  14534. vertexShaderUrl = vertex;
  14535. }
  14536. else {
  14537. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14538. }
  14539. // Vertex shader
  14540. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14541. };
  14542. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14543. // DOM element ?
  14544. if (fragment instanceof HTMLElement) {
  14545. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14546. callback(fragmentCode);
  14547. return;
  14548. }
  14549. // Is in local store ?
  14550. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14551. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14552. return;
  14553. }
  14554. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14555. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14556. return;
  14557. }
  14558. var fragmentShaderUrl;
  14559. if (fragment[0] === ".") {
  14560. fragmentShaderUrl = fragment;
  14561. }
  14562. else {
  14563. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14564. }
  14565. // Fragment shader
  14566. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14567. };
  14568. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14569. try {
  14570. var engine = this._engine;
  14571. if (!engine.getCaps().highPrecisionShaderSupported) {
  14572. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14573. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14574. }
  14575. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14576. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14577. this._attributes = engine.getAttributes(this._program, attributesNames);
  14578. for (var index = 0; index < this._samplers.length; index++) {
  14579. var sampler = this.getUniform(this._samplers[index]);
  14580. if (sampler == null) {
  14581. this._samplers.splice(index, 1);
  14582. index--;
  14583. }
  14584. }
  14585. engine.bindSamplers(this);
  14586. this._isReady = true;
  14587. if (this.onCompiled) {
  14588. this.onCompiled(this);
  14589. }
  14590. }
  14591. catch (e) {
  14592. // Is it a problem with precision?
  14593. if (e.message.indexOf("highp") !== -1) {
  14594. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14595. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14596. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14597. return;
  14598. }
  14599. // Let's go through fallbacks then
  14600. if (fallbacks && fallbacks.isMoreFallbacks) {
  14601. defines = fallbacks.reduce(defines);
  14602. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14603. }
  14604. else {
  14605. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14606. BABYLON.Tools.Error("Defines: " + defines);
  14607. BABYLON.Tools.Error("Error: " + e.message);
  14608. this._compilationError = e.message;
  14609. if (this.onError) {
  14610. this.onError(this, this._compilationError);
  14611. }
  14612. }
  14613. }
  14614. };
  14615. Effect.prototype._bindTexture = function (channel, texture) {
  14616. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14617. };
  14618. Effect.prototype.setTexture = function (channel, texture) {
  14619. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14620. };
  14621. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14622. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14623. };
  14624. //public _cacheMatrix(uniformName, matrix) {
  14625. // if (!this._valueCache[uniformName]) {
  14626. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14627. // }
  14628. // for (var index = 0; index < 16; index++) {
  14629. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14630. // }
  14631. //};
  14632. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14633. if (!this._valueCache[uniformName]) {
  14634. this._valueCache[uniformName] = [x, y];
  14635. return;
  14636. }
  14637. this._valueCache[uniformName][0] = x;
  14638. this._valueCache[uniformName][1] = y;
  14639. };
  14640. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14641. if (!this._valueCache[uniformName]) {
  14642. this._valueCache[uniformName] = [x, y, z];
  14643. return;
  14644. }
  14645. this._valueCache[uniformName][0] = x;
  14646. this._valueCache[uniformName][1] = y;
  14647. this._valueCache[uniformName][2] = z;
  14648. };
  14649. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14650. if (!this._valueCache[uniformName]) {
  14651. this._valueCache[uniformName] = [x, y, z, w];
  14652. return;
  14653. }
  14654. this._valueCache[uniformName][0] = x;
  14655. this._valueCache[uniformName][1] = y;
  14656. this._valueCache[uniformName][2] = z;
  14657. this._valueCache[uniformName][3] = w;
  14658. };
  14659. Effect.prototype.setArray = function (uniformName, array) {
  14660. this._engine.setArray(this.getUniform(uniformName), array);
  14661. return this;
  14662. };
  14663. Effect.prototype.setArray2 = function (uniformName, array) {
  14664. this._engine.setArray2(this.getUniform(uniformName), array);
  14665. return this;
  14666. };
  14667. Effect.prototype.setArray3 = function (uniformName, array) {
  14668. this._engine.setArray3(this.getUniform(uniformName), array);
  14669. return this;
  14670. };
  14671. Effect.prototype.setArray4 = function (uniformName, array) {
  14672. this._engine.setArray4(this.getUniform(uniformName), array);
  14673. return this;
  14674. };
  14675. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14676. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14677. return this;
  14678. };
  14679. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14680. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14681. // return;
  14682. //this._cacheMatrix(uniformName, matrix);
  14683. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14684. return this;
  14685. };
  14686. Effect.prototype.setFloat = function (uniformName, value) {
  14687. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14688. return this;
  14689. this._valueCache[uniformName] = value;
  14690. this._engine.setFloat(this.getUniform(uniformName), value);
  14691. return this;
  14692. };
  14693. Effect.prototype.setBool = function (uniformName, bool) {
  14694. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14695. return this;
  14696. this._valueCache[uniformName] = bool;
  14697. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14698. return this;
  14699. };
  14700. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14701. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14702. return this;
  14703. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14704. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14705. return this;
  14706. };
  14707. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14708. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14709. return this;
  14710. this._cacheFloat2(uniformName, x, y);
  14711. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14712. return this;
  14713. };
  14714. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14715. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14716. return this;
  14717. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14718. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14719. return this;
  14720. };
  14721. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14722. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14723. return this;
  14724. this._cacheFloat3(uniformName, x, y, z);
  14725. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14726. return this;
  14727. };
  14728. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14729. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14730. return this;
  14731. this._cacheFloat4(uniformName, x, y, z, w);
  14732. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14733. return this;
  14734. };
  14735. Effect.prototype.setColor3 = function (uniformName, color3) {
  14736. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14737. return this;
  14738. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14739. this._engine.setColor3(this.getUniform(uniformName), color3);
  14740. return this;
  14741. };
  14742. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14743. 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)
  14744. return this;
  14745. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14746. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14747. return this;
  14748. };
  14749. // Statics
  14750. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\nvec4 leftFrag = texture2D(leftSampler, vUV);\nleftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\nvec4 rightFrag = texture2D(textureSampler, vUV);\nrightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\ngl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  14751. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\nfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\ngl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  14752. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\nfloat weights[7];\nweights[0] = 0.05;\nweights[1] = 0.1;\nweights[2] = 0.2;\nweights[3] = 0.3;\nweights[4] = 0.2;\nweights[5] = 0.1;\nweights[6] = 0.05;\n\nvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\nvec2 texelStep = texelSize * direction * blurWidth;\nvec2 start = vUV - 3.0 * texelStep;\n\nvec4 baseColor = vec4(0., 0., 0., 0.);\nvec2 texelOffset = vec2(0., 0.);\n\nfor (int i = 0; i < 7; i++)\n{\nbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\ntexelOffset += texelStep;\n}\n\ngl_FragColor = baseColor;\n}",
  14753. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\nfloat brickW = 1.0 / numberOfBricksWidth;\nfloat brickH = 1.0 / numberOfBricksHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.05;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\nif (brickColorSwitch == 0.0)\ncolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\nelse if (brickColorSwitch == 2.0)\ncolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n}\n\ngl_FragColor = vec4(color, 1.0);\n}",
  14754. chromaticAberrationPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvoid main(void)\n{\nvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;\nfloat radius = sqrt(radius2);\n\nvec4 original = texture2D(textureSampler, vUV);\n\nif (chromatic_aberration > 0.0) {\nvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\nfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\nfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\n\nvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\noriginal.r = texture2D(textureSampler, ref_coords_r).r;\noriginal.g = texture2D(textureSampler, ref_coords_g).g;\noriginal.b = texture2D(textureSampler, ref_coords_b).b;\n}\n\ngl_FragColor = original;\n}",
  14755. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\n\nvec2 p = vUV * 12.0;\nvec3 c = mix(skyColor, cloudColor, fbm(p));\ngl_FragColor = vec4(c, 1);\n\n}",
  14756. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14757. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14758. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\nfloat sliceSize = 1.0 / width; // space of 1 slice\nfloat slicePixelSize = sliceSize / width; // space of 1 pixel\nfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\nfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\nfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\nfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\nfloat s0 = xOffset + (zSlice0 * sliceSize);\nfloat s1 = xOffset + (zSlice1 * sliceSize);\nvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\nvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\nfloat zOffset = mod(uv.z * width, 1.0);\nvec4 result = mix(slice0Color, slice1Color, zOffset);\nreturn result;\n}\n\nvoid main(void)\n{\nvec4 screen_color = texture2D(textureSampler, vUV);\ngl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  14759. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\nvec2 onePixel = vec2(1.0, 1.0) / screenSize;\nvec4 colorSum =\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\n\nif (kernelWeight <= 0.0) {\nkernelWeight = 1.0;\n}\n\ngl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  14760. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform vec3 shadowsInfo0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform vec3 shadowsInfo1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform vec3 shadowsInfo2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn vPositionUVW;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\nreturn dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\nif (depth.z > shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat visibility = 1.;\n\nvec2 poissonDisk[4];\npoissonDisk[0] = vec2(-0.94201624, -0.39906216);\npoissonDisk[1] = vec2(0.94558609, -0.76890725);\npoissonDisk[2] = vec2(-0.094184101, -0.92938870);\npoissonDisk[3] = vec2(0.34495938, 0.29387760);\n\nfloat biasedDepth = depth.z - bias;\n\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\n\nreturn visibility;\n}\n\nfloat linstep(float low, float high, float v) {\nreturn clamp((v - low) / (high - low), 0.0, 1.0);\n}\n\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\n{\nfloat p = smoothstep(compare - bias, compare, moments.x);\nfloat variance = max(moments.y - moments.x * moments.x, 0.02);\nfloat d = compare - moments.x;\nfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n\nreturn clamp(max(p, p_max), 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\nvec3 dp1 = dFdx(p);\nvec3 dp2 = dFdy(p);\nvec2 duv1 = dFdx(uv);\nvec2 duv2 = dFdy(uv);\n\nvec3 dp2perp = cross(dp2, normal);\nvec3 dp1perp = cross(normal, dp1);\nvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\nvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\nfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\nreturn mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\nvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\nmap = map * 255. / 127. - 128. / 127.;\nmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\nreturn normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nstruct lightingInfo\n{\nvec3 diffuse;\nvec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 lightVectorW;\nfloat attenuation = 1.0;\nif (lightData.w == 0.)\n{\nvec3 direction = lightData.xyz - vPositionW;\n\nattenuation = max(0., 1.0 - length(direction) / range);\nlightVectorW = normalize(direction);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, max(1., vSpecularColor.a));\n\nresult.diffuse = ndl * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * attenuation;\n\nreturn result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 direction = lightData.xyz - vPositionW;\nvec3 lightVectorW = normalize(direction);\nfloat attenuation = max(0., 1.0 - length(direction) / range);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * spotAtten * attenuation;\n\nreturn result;\n}\n\nresult.diffuse = vec3(0.);\nresult.specular = vec3(0.);\n\nreturn result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\nlightingInfo result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = mix(groundColor, diffuseColor, ndl);\nresult.specular = specComp * specularColor;\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\nalpha *= baseColor.a;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n#ifdef NORMAL\nvec3 normalW = normalize(vNormalW);\n#else\nvec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\nnormalW = perturbNormal(viewDirectionW);\n#endif\n\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\nlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n#ifdef SHADOWPCF0\nshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n#ifdef SHADOWPCF1\nshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n#ifdef SHADOWPCF2\nshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n#ifdef SHADOWPCF3\nshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\nalpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14761. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\nmat4 finalWorld;\n\n#ifdef REFLECTION\nvPositionUVW = position;\n#endif\n\n#ifdef INSTANCES\nfinalWorld = mat4(world0, world1, world2, world3);\n#else\nfinalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = finalWorld * (m0 + m1 + m2);\n#endif\n\n#endif\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\n\n#ifdef NORMAL\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize = pointSize;\n#endif\n}",
  14762. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\nfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\ngl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  14763. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14764. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\n\nvoid main(void)\n{\nvec4 colorDepth = vec4(0.0);\n\nfor (int x = -OFFSET; x <= OFFSET; x++)\nfor (int y = -OFFSET; y <= OFFSET; y++)\ncolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\ngl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  14765. depthOfFieldPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform float maxZ;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform float focus_depth;\nuniform float aperture;\nuniform float edge_blur;\nuniform bool highlights;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\nvec2 getDistortedCoords(vec2 coords) {\n\nif (distortion == 0.0) { return coords; }\n\nvec2 direction = 1.0 * normalize(centered_screen_pos);\nvec2 dist_coords = vec2(0.5, 0.5);\ndist_coords.x = 0.5 + direction.x * radius2 * 1.0;\ndist_coords.y = 0.5 + direction.y * radius2 * 1.0;\nfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\ndist_coords = mix(coords, dist_coords, dist_amount);\n\nreturn dist_coords;\n}\n\nvec4 getBlurColor(vec2 coords, float size) {\n\nvec4 col = texture2D(textureSampler, coords);\nif (size == 0.0) { return col; }\n\nfloat blur_level = min(3.0, ceil(size / 1.0));\n\nfloat w = (size / screen_width);\nfloat h = (size / screen_height);\nfloat total_weight = 1.0;\n\ncol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\ncol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\ncol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\ncol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\ncol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\ncol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\ncol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\ncol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\ncol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\ncol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\ntotal_weight += 8.18;\n\nif (blur_level > 1.0) {\ncol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\ncol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\ncol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\ncol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\ncol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\ncol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\ncol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\ncol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\ncol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\ncol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\ntotal_weight += 5.96;\n}\n\nif (blur_level > 2.0) {\ncol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\ncol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\ncol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\ncol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\ncol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\ncol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\ncol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\ncol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\ncol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\ntotal_weight += 2.97;\n}\n\ncol /= total_weight; // scales color according to weights\ncol.a = 1.0;\n\n\nreturn col;\n}\n\nvec2 rand(vec2 co)\n{\nfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\nfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\nreturn clamp(vec2(noise1, noise2), 0.0, 1.0);\n}\n\nvoid main(void)\n{\n\ncentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\nradius = sqrt(radius2);\n\nvec4 final_color;\nvec2 distorted_coords = getDistortedCoords(vUV);\nvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\nfloat dof_blur_amount = 0.0;\nfloat depth_bias = 0.0; // positive if the pixel is further than focus depth; negative if closer\nif (focus_depth != -1.0) {\nvec4 depth_sample = texture2D(depthSampler, distorted_coords);\nfloat depth = depth_sample.r;\ndepth_bias = depth - focus_depth;\n\nif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\nelse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\n\nif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n}\n\nfloat edge_blur_amount = 0.0;\nif (edge_blur > 0.0) {\nedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\n}\n\nfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\n\nif (blur_amount == 0.0) {\ngl_FragColor = texture2D(textureSampler, distorted_coords);\n}\nelse {\n\ngl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\n\nif (depth_bias > 0.0 && highlights) {\ngl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\n}\n\nif (blur_noise) {\nvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\nvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\ngl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\n}\n}\n\nif (grain_amount > 0.0) {\nvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\ngl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\n}\n}",
  14766. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(passSampler, vUV);\n}",
  14767. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\nvec3 baseColor = texture2D(textureSampler, vUV).rgb;\nvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\ngl_FragColor = vec4(updatedColor, 1.0);\n}",
  14768. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\nvec2 p = vUV * 8.0;\nfloat q = fbm(p - time * 0.1);\nvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\nvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\nvec3 color = c * cos(shift * vUV.y);\nfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\ngl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  14769. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\nvec2 localTexelSize = texelSize;\nvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\nvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\nvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\nvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\nvec4 rgbM = texture2D(textureSampler, vUV);\nvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM = dot(rgbM, luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\nvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\nfloat dirReduce = max(\n(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\n\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\ndir * rcpDirMin)) * localTexelSize;\n\nvec4 rgbA = 0.5 * (\ntexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\ntexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\nvec4 rgbB = rgbA * 0.5 + 0.25 * (\ntexture2D(textureSampler, vUV + dir * -0.5) +\ntexture2D(textureSampler, vUV + dir * 0.5));\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\ngl_FragColor = rgbA;\n}\nelse {\ngl_FragColor = rgbB;\n}\n}",
  14770. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\ncolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\ncolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\ncolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\ngl_FragColor = vec4(color, 1.0);\n}",
  14771. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14772. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14773. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\nreturn dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv));\n\nif (depth.z > shadow)\n{\nreturn 0.;\n}\nreturn 1.;\n}\n\nfloat ChebychevInequality(vec2 moments, float t)\n{\nif (t <= moments.x)\n{\nreturn 1.0;\n}\n\nfloat variance = moments.y - (moments.x * moments.x);\nvariance = max(variance, 0.);\n\nfloat d = t - moments.x;\nreturn variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW;\nif (lightData.w == 0.)\n{\nlightVectorW = normalize(lightData.xyz - vPositionW);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\nresult[0] = ndl * diffuseColor.rgb;\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = ndl * spotAtten * diffuseColor.rgb;\nresult[1] = specComp * specularColor * spotAtten;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nresult[0] = vec3(0.);\nresult[1] = vec3(0.);\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\nmat3 result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\nvec3 normalW = normalize(vNormalW);\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\nmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14774. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn position;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\nmat4 finalWorld;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = world * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = world * (m0 + m1 + m2);\n#endif\n\n#else\nfinalWorld = world;\n#endif\n\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef REFLECTION\nvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n}",
  14775. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14776. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  14777. lensHighlightsPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float gain;\nuniform float threshold;\nuniform bool pentagon;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight = color;\nfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\nfloat lum_threshold;\nif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\nelse { lum_threshold = 0.5 + 0.44 * threshold; }\n\nluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\n\nhighlight *= luminance * gain;\nhighlight.a = 1.0;\n\nreturn highlight;\n}\n\nvoid main(void)\n{\nvec4 original = texture2D(textureSampler, vUV);\n\nif (gain == -1.0) {\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nreturn;\n}\n\nfloat w = 2.0 / screen_width;\nfloat h = 2.0 / screen_height;\n\nfloat weight = 1.0;\n\nvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\n\nif (pentagon) {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\n}\nelse {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\n}\n\nblurred /= 39.0;\n\ngl_FragColor = blurred;\n\n}",
  14778. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\nfloat val = 0.0;\nfloat freq = 1.0;\nfor (int i = 0; i < 4; i++)\n{\nval += abs(noise(P*freq) / freq);\nfreq *= 2.07;\n}\nreturn val;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\nvec3 col;\nx = 0.5*(x + 1.);\nx = sqrt(x);\nx = sqrt(x);\nx = sqrt(x);\ncol = vec3(.2 + .75*x);\ncol.b *= 0.95;\nreturn col;\n}\n\nvoid main()\n{\nfloat brickW = 1.0 / numberOfTilesWidth;\nfloat brickH = 1.0 / numberOfTilesHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.01;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\nt += amplitude * turbulence(brickvUV.xy);\nt = sin(t);\ncolor = marble_color(t);\n}\n\ngl_FragColor = vec4(color, 0.0);\n}",
  14779. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\nvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\nfloat rSq = theta.x * theta.x + theta.y * theta.y;\nvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\nreturn LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\nvec2 tc = HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nelse{\ngl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n}\n}",
  14780. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\ngl_FragColor = color;\n}",
  14781. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\nvec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14782. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\ngl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  14783. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\nvec3 viewPos = (view * vec4(position, 1.0)).xyz;\nvec3 cornerPos;\nfloat size = options.y;\nfloat angle = options.x;\nvec2 offset = options.zw;\n\ncornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\nvUV = offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos = invView * vec4(viewPos, 1.0);\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  14784. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(textureSampler, vUV);\n}",
  14785. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14786. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\nvPosition = position;\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14787. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\nfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\nvec2 uv = vUV - vec2(0.5);\nvec2 offset = uv * depth * ref;\nvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\ngl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  14788. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\nvec3 color = roadColor * ratioy;\ngl_FragColor = vec4(color, 1.0);\n}",
  14789. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\nconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\nconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\nvec4 res = fract(depth * bit_shift);\nres -= res.xxyz * bit_mask;\n\nreturn res;\n}\n\nvec2 packHalf(float depth)\n{\nconst vec2 bitOffset = vec2(1.0 / 255., 0.);\nvec2 color = vec2(depth, fract(depth * 255.));\n\nreturn color - (color.yy * bitOffset);\n}\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\nfloat depth = vPosition.z / vPosition.w;\ndepth = depth * 0.5 + 0.5;\n\n#ifdef VSM\nfloat moment1 = depth;\nfloat moment2 = moment1 * moment1;\n\ngl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\ngl_FragColor = pack(depth);\n#endif\n}",
  14790. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\nvPosition = viewProjection * finalWorld * vec4(position, 1.0);\ngl_Position = vPosition;\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14791. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\nif (alphaTest)\n{\nif (baseColor.a < 0.95)\ndiscard;\n}\n\nbaseColor *= vColor;\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\nbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = baseColor;\n}",
  14792. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) {\nvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz;\nvec2 cornerPos;\n\nfloat angle = position.w;\nvec2 size = vec2(options.x, options.y);\nvec2 offset = options.zw;\nvec2 uvScale = textureInfos.xy;\n\ncornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\n\nvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\nvUV = (uvOffset + cellInfo.zw) * uvScale;\n\n#ifdef FOG\nfFogDistance = viewPos.z;\n#endif\n}",
  14793. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.001);\nconst vec2 offset2 = vec2(0.001, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\nfloat depth1 = texture2D(textureSampler, coords + offset1).r;\nfloat depth2 = texture2D(textureSampler, coords + offset2).r;\n\nvec3 p1 = vec3(offset1, depth1 - depth);\nvec3 p2 = vec3(offset2, depth2 - depth);\n\nvec3 normal = cross(p1, p2);\nnormal.z = -normal.z;\n\nreturn normalize(normal);\n}\n\nvoid main(void)\n{\nconst float base = 0.2;\n\nvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\nfloat depth = texture2D(textureSampler, vUV).r;\nvec3 position = vec3(vUV, depth);\nvec3 normal = normalFromDepth(depth, vUV);\nfloat radiusDepth = radius / depth;\nfloat occlusion = 0.0;\n\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\n\nfor (int i = 0; i < SAMPLES; i++)\n{\nray = radiusDepth * reflect(sampleSphere[i], random);\nhemiRay = position + sign(dot(ray, normal)) * ray;\n\nocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\ndifference = depth - occlusionDepth;\n\nocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n}\n\nfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\nfloat result = clamp(ao + base, 0.0, 1.0);\ngl_FragColor.r = result;\ngl_FragColor.g = result;\ngl_FragColor.b = result;\ngl_FragColor.a = 1.0;\n}",
  14794. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\ngl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  14795. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\nvec2 tc = vUV;\nvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\ndeltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\nfloat illuminationDecay = 1.0;\n\nvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\nfor(int i=0; i < NUM_SAMPLES; i++) {\ntc -= deltaTexCoord;\nvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\nsample *= illuminationDecay * weight;\ncolor += sample;\nilluminationDecay *= decay;\n}\n\nvec4 realColor = texture2D(textureSampler, vUV);\ngl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  14796. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\nif (diffuseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef OPACITY\nvec4 opacityColor = texture2D(opacitySampler, vUV);\nfloat alpha = 1.0;\n\n#ifdef OPACITYRGB\nopacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n#else\nalpha *= opacityColor.a * opacityLevel;\n#endif\n\n#if defined(BASIC_RENDER)\ngl_FragColor = vec4(diffuseColor.rgb, alpha);\n#else\ngl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n#endif\n\ngl_FragColor.a = alpha;\n#else\n#ifndef BASIC_RENDER\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#else\ngl_FragColor = diffuseColor;\n#endif\n#endif\n\n}",
  14797. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\nvec3 wood = woodColor * ratioy;\ngl_FragColor = vec4(wood, 1.0);\n}",
  14798. };
  14799. return Effect;
  14800. })();
  14801. BABYLON.Effect = Effect;
  14802. })(BABYLON || (BABYLON = {}));
  14803. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14804. (function (BABYLON) {
  14805. var Material = (function () {
  14806. function Material(name, scene, doNotAdd) {
  14807. this.name = name;
  14808. this.checkReadyOnEveryCall = true;
  14809. this.checkReadyOnlyOnce = false;
  14810. this.state = "";
  14811. this.alpha = 1.0;
  14812. this.backFaceCulling = true;
  14813. this._wasPreviouslyReady = false;
  14814. this._fillMode = Material.TriangleFillMode;
  14815. this.pointSize = 1.0;
  14816. this.zOffset = 0;
  14817. this.id = name;
  14818. this._scene = scene;
  14819. if (!doNotAdd) {
  14820. scene.materials.push(this);
  14821. }
  14822. }
  14823. Object.defineProperty(Material, "TriangleFillMode", {
  14824. get: function () {
  14825. return Material._TriangleFillMode;
  14826. },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. Object.defineProperty(Material, "WireFrameFillMode", {
  14831. get: function () {
  14832. return Material._WireFrameFillMode;
  14833. },
  14834. enumerable: true,
  14835. configurable: true
  14836. });
  14837. Object.defineProperty(Material, "PointFillMode", {
  14838. get: function () {
  14839. return Material._PointFillMode;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. Object.defineProperty(Material.prototype, "wireframe", {
  14845. get: function () {
  14846. return this._fillMode === Material.WireFrameFillMode;
  14847. },
  14848. set: function (value) {
  14849. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14850. },
  14851. enumerable: true,
  14852. configurable: true
  14853. });
  14854. Object.defineProperty(Material.prototype, "pointsCloud", {
  14855. get: function () {
  14856. return this._fillMode === Material.PointFillMode;
  14857. },
  14858. set: function (value) {
  14859. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14860. },
  14861. enumerable: true,
  14862. configurable: true
  14863. });
  14864. Object.defineProperty(Material.prototype, "fillMode", {
  14865. get: function () {
  14866. return this._fillMode;
  14867. },
  14868. set: function (value) {
  14869. this._fillMode = value;
  14870. },
  14871. enumerable: true,
  14872. configurable: true
  14873. });
  14874. Material.prototype.isReady = function (mesh, useInstances) {
  14875. return true;
  14876. };
  14877. Material.prototype.getEffect = function () {
  14878. return this._effect;
  14879. };
  14880. Material.prototype.getScene = function () {
  14881. return this._scene;
  14882. };
  14883. Material.prototype.needAlphaBlending = function () {
  14884. return (this.alpha < 1.0);
  14885. };
  14886. Material.prototype.needAlphaTesting = function () {
  14887. return false;
  14888. };
  14889. Material.prototype.getAlphaTestTexture = function () {
  14890. return null;
  14891. };
  14892. Material.prototype.trackCreation = function (onCompiled, onError) {
  14893. };
  14894. Material.prototype._preBind = function () {
  14895. var engine = this._scene.getEngine();
  14896. engine.enableEffect(this._effect);
  14897. engine.setState(this.backFaceCulling, this.zOffset);
  14898. };
  14899. Material.prototype.bind = function (world, mesh) {
  14900. this._scene._cachedMaterial = this;
  14901. if (this.onBind) {
  14902. this.onBind(this, mesh);
  14903. }
  14904. };
  14905. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14906. };
  14907. Material.prototype.unbind = function () {
  14908. };
  14909. Material.prototype.dispose = function (forceDisposeEffect) {
  14910. // Remove from scene
  14911. var index = this._scene.materials.indexOf(this);
  14912. this._scene.materials.splice(index, 1);
  14913. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14914. if (forceDisposeEffect && this._effect) {
  14915. this._scene.getEngine()._releaseEffect(this._effect);
  14916. this._effect = null;
  14917. }
  14918. // Callback
  14919. if (this.onDispose) {
  14920. this.onDispose();
  14921. }
  14922. };
  14923. Material._TriangleFillMode = 0;
  14924. Material._WireFrameFillMode = 1;
  14925. Material._PointFillMode = 2;
  14926. return Material;
  14927. })();
  14928. BABYLON.Material = Material;
  14929. })(BABYLON || (BABYLON = {}));
  14930. //# sourceMappingURL=babylon.material.js.map
  14931. var BABYLON;
  14932. (function (BABYLON) {
  14933. var maxSimultaneousLights = 4;
  14934. var FresnelParameters = (function () {
  14935. function FresnelParameters() {
  14936. this.isEnabled = true;
  14937. this.leftColor = BABYLON.Color3.White();
  14938. this.rightColor = BABYLON.Color3.Black();
  14939. this.bias = 0;
  14940. this.power = 1;
  14941. }
  14942. return FresnelParameters;
  14943. })();
  14944. BABYLON.FresnelParameters = FresnelParameters;
  14945. var StandardMaterial = (function (_super) {
  14946. __extends(StandardMaterial, _super);
  14947. function StandardMaterial(name, scene) {
  14948. var _this = this;
  14949. _super.call(this, name, scene);
  14950. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14951. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14952. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14953. this.specularPower = 64;
  14954. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14955. this.useAlphaFromDiffuseTexture = false;
  14956. this.useSpecularOverAlpha = true;
  14957. this.fogEnabled = true;
  14958. this._cachedDefines = null;
  14959. this._renderTargets = new BABYLON.SmartArray(16);
  14960. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14961. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14962. this._scaledDiffuse = new BABYLON.Color3();
  14963. this._scaledSpecular = new BABYLON.Color3();
  14964. this.getRenderTargetTextures = function () {
  14965. _this._renderTargets.reset();
  14966. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14967. _this._renderTargets.push(_this.reflectionTexture);
  14968. }
  14969. return _this._renderTargets;
  14970. };
  14971. }
  14972. StandardMaterial.prototype.needAlphaBlending = function () {
  14973. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14974. };
  14975. StandardMaterial.prototype.needAlphaTesting = function () {
  14976. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  14977. };
  14978. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14979. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14980. };
  14981. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14982. return this.diffuseTexture;
  14983. };
  14984. // Methods
  14985. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14986. if (this.checkReadyOnlyOnce) {
  14987. if (this._wasPreviouslyReady) {
  14988. }
  14989. }
  14990. var scene = this.getScene();
  14991. if (!this.checkReadyOnEveryCall) {
  14992. if (this._renderId === scene.getRenderId()) {
  14993. }
  14994. }
  14995. var engine = scene.getEngine();
  14996. var defines = [];
  14997. var fallbacks = new BABYLON.EffectFallbacks();
  14998. var needNormals = false;
  14999. var needUVs = false;
  15000. // Textures
  15001. if (scene.texturesEnabled) {
  15002. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15003. if (!this.diffuseTexture.isReady()) {
  15004. return false;
  15005. }
  15006. else {
  15007. needUVs = true;
  15008. defines.push("#define DIFFUSE");
  15009. }
  15010. }
  15011. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15012. if (!this.ambientTexture.isReady()) {
  15013. return false;
  15014. }
  15015. else {
  15016. needUVs = true;
  15017. defines.push("#define AMBIENT");
  15018. }
  15019. }
  15020. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15021. if (!this.opacityTexture.isReady()) {
  15022. return false;
  15023. }
  15024. else {
  15025. needUVs = true;
  15026. defines.push("#define OPACITY");
  15027. if (this.opacityTexture.getAlphaFromRGB) {
  15028. defines.push("#define OPACITYRGB");
  15029. }
  15030. }
  15031. }
  15032. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15033. if (!this.reflectionTexture.isReady()) {
  15034. return false;
  15035. }
  15036. else {
  15037. needNormals = true;
  15038. needUVs = true;
  15039. defines.push("#define REFLECTION");
  15040. fallbacks.addFallback(0, "REFLECTION");
  15041. }
  15042. }
  15043. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15044. if (!this.emissiveTexture.isReady()) {
  15045. return false;
  15046. }
  15047. else {
  15048. needUVs = true;
  15049. defines.push("#define EMISSIVE");
  15050. }
  15051. }
  15052. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15053. if (!this.specularTexture.isReady()) {
  15054. return false;
  15055. }
  15056. else {
  15057. needUVs = true;
  15058. defines.push("#define SPECULAR");
  15059. fallbacks.addFallback(0, "SPECULAR");
  15060. }
  15061. }
  15062. }
  15063. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  15064. if (!this.bumpTexture.isReady()) {
  15065. return false;
  15066. }
  15067. else {
  15068. needUVs = true;
  15069. defines.push("#define BUMP");
  15070. fallbacks.addFallback(0, "BUMP");
  15071. }
  15072. }
  15073. // Effect
  15074. if (this.useSpecularOverAlpha) {
  15075. defines.push("#define SPECULAROVERALPHA");
  15076. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  15077. }
  15078. if (scene.clipPlane) {
  15079. defines.push("#define CLIPPLANE");
  15080. }
  15081. if (engine.getAlphaTesting()) {
  15082. defines.push("#define ALPHATEST");
  15083. }
  15084. if (this._shouldUseAlphaFromDiffuseTexture()) {
  15085. defines.push("#define ALPHAFROMDIFFUSE");
  15086. }
  15087. // Point size
  15088. if (this.pointsCloud || scene.forcePointsCloud) {
  15089. defines.push("#define POINTSIZE");
  15090. }
  15091. // Fog
  15092. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15093. defines.push("#define FOG");
  15094. fallbacks.addFallback(1, "FOG");
  15095. }
  15096. var shadowsActivated = false;
  15097. var lightIndex = 0;
  15098. if (scene.lightsEnabled) {
  15099. for (var index = 0; index < scene.lights.length; index++) {
  15100. var light = scene.lights[index];
  15101. if (!light.isEnabled()) {
  15102. continue;
  15103. }
  15104. // Excluded check
  15105. if (light._excludedMeshesIds.length > 0) {
  15106. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  15107. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  15108. if (excludedMesh) {
  15109. light.excludedMeshes.push(excludedMesh);
  15110. }
  15111. }
  15112. light._excludedMeshesIds = [];
  15113. }
  15114. // Included check
  15115. if (light._includedOnlyMeshesIds.length > 0) {
  15116. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  15117. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  15118. if (includedOnlyMesh) {
  15119. light.includedOnlyMeshes.push(includedOnlyMesh);
  15120. }
  15121. }
  15122. light._includedOnlyMeshesIds = [];
  15123. }
  15124. if (!light.canAffectMesh(mesh)) {
  15125. continue;
  15126. }
  15127. needNormals = true;
  15128. defines.push("#define LIGHT" + lightIndex);
  15129. if (lightIndex > 0) {
  15130. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  15131. }
  15132. var type;
  15133. if (light instanceof BABYLON.SpotLight) {
  15134. type = "#define SPOTLIGHT" + lightIndex;
  15135. }
  15136. else if (light instanceof BABYLON.HemisphericLight) {
  15137. type = "#define HEMILIGHT" + lightIndex;
  15138. }
  15139. else {
  15140. type = "#define POINTDIRLIGHT" + lightIndex;
  15141. }
  15142. defines.push(type);
  15143. if (lightIndex > 0) {
  15144. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  15145. }
  15146. // Shadows
  15147. if (scene.shadowsEnabled) {
  15148. var shadowGenerator = light.getShadowGenerator();
  15149. if (mesh && mesh.receiveShadows && shadowGenerator) {
  15150. defines.push("#define SHADOW" + lightIndex);
  15151. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  15152. if (!shadowsActivated) {
  15153. defines.push("#define SHADOWS");
  15154. shadowsActivated = true;
  15155. }
  15156. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  15157. defines.push("#define SHADOWVSM" + lightIndex);
  15158. if (lightIndex > 0) {
  15159. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  15160. }
  15161. }
  15162. if (shadowGenerator.usePoissonSampling) {
  15163. defines.push("#define SHADOWPCF" + lightIndex);
  15164. if (lightIndex > 0) {
  15165. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  15166. }
  15167. }
  15168. }
  15169. }
  15170. lightIndex++;
  15171. if (lightIndex === maxSimultaneousLights)
  15172. break;
  15173. }
  15174. }
  15175. if (StandardMaterial.FresnelEnabled) {
  15176. // Fresnel
  15177. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15178. var fresnelRank = 1;
  15179. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15180. defines.push("#define DIFFUSEFRESNEL");
  15181. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  15182. fresnelRank++;
  15183. }
  15184. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15185. defines.push("#define OPACITYFRESNEL");
  15186. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  15187. fresnelRank++;
  15188. }
  15189. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15190. defines.push("#define REFLECTIONFRESNEL");
  15191. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  15192. fresnelRank++;
  15193. }
  15194. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15195. defines.push("#define EMISSIVEFRESNEL");
  15196. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  15197. fresnelRank++;
  15198. }
  15199. needNormals = true;
  15200. defines.push("#define FRESNEL");
  15201. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  15202. }
  15203. }
  15204. // Attribs
  15205. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15206. if (mesh) {
  15207. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15208. attribs.push(BABYLON.VertexBuffer.NormalKind);
  15209. defines.push("#define NORMAL");
  15210. }
  15211. if (needUVs) {
  15212. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15213. attribs.push(BABYLON.VertexBuffer.UVKind);
  15214. defines.push("#define UV1");
  15215. }
  15216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15217. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15218. defines.push("#define UV2");
  15219. }
  15220. }
  15221. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15222. attribs.push(BABYLON.VertexBuffer.ColorKind);
  15223. defines.push("#define VERTEXCOLOR");
  15224. if (mesh.hasVertexAlpha) {
  15225. defines.push("#define VERTEXALPHA");
  15226. }
  15227. }
  15228. if (mesh.useBones) {
  15229. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15230. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15231. defines.push("#define BONES");
  15232. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15233. defines.push("#define BONES4");
  15234. fallbacks.addFallback(0, "BONES4");
  15235. }
  15236. // Instances
  15237. if (useInstances) {
  15238. defines.push("#define INSTANCES");
  15239. attribs.push("world0");
  15240. attribs.push("world1");
  15241. attribs.push("world2");
  15242. attribs.push("world3");
  15243. }
  15244. }
  15245. // Get correct effect
  15246. var join = defines.join("\n");
  15247. if (this._cachedDefines !== join) {
  15248. this._cachedDefines = join;
  15249. scene.resetCachedMaterial();
  15250. // Legacy browser patch
  15251. var shaderName = "default";
  15252. if (!scene.getEngine().getCaps().standardDerivatives) {
  15253. shaderName = "legacydefault";
  15254. }
  15255. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  15256. }
  15257. if (!this._effect.isReady()) {
  15258. return false;
  15259. }
  15260. this._renderId = scene.getRenderId();
  15261. this._wasPreviouslyReady = true;
  15262. return true;
  15263. };
  15264. StandardMaterial.prototype.unbind = function () {
  15265. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  15266. this._effect.setTexture("reflection2DSampler", null);
  15267. }
  15268. };
  15269. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  15270. this._effect.setMatrix("world", world);
  15271. };
  15272. StandardMaterial.prototype.bind = function (world, mesh) {
  15273. var scene = this.getScene();
  15274. // Matrices
  15275. this.bindOnlyWorldMatrix(world);
  15276. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  15277. // Bones
  15278. if (mesh && mesh.useBones) {
  15279. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15280. }
  15281. if (scene.getCachedMaterial() !== this) {
  15282. if (StandardMaterial.FresnelEnabled) {
  15283. // Fresnel
  15284. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15285. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15286. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15287. }
  15288. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15289. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15290. }
  15291. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15292. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15293. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15294. }
  15295. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15296. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15297. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15298. }
  15299. }
  15300. // Textures
  15301. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15302. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15303. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15304. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15305. }
  15306. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15307. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15308. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15309. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15310. }
  15311. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15312. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15313. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15314. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15315. }
  15316. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15317. if (this.reflectionTexture.isCube) {
  15318. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15319. }
  15320. else {
  15321. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15322. }
  15323. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15324. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15325. }
  15326. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15327. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15328. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15329. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15330. }
  15331. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15332. this._effect.setTexture("specularSampler", this.specularTexture);
  15333. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15334. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15335. }
  15336. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15337. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15338. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15339. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15340. }
  15341. // Clip plane
  15342. if (scene.clipPlane) {
  15343. var clipPlane = scene.clipPlane;
  15344. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15345. }
  15346. // Point size
  15347. if (this.pointsCloud) {
  15348. this._effect.setFloat("pointSize", this.pointSize);
  15349. }
  15350. // Colors
  15351. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15352. // Scaling down color according to emissive
  15353. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15354. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15355. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15356. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15357. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15358. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15359. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15360. }
  15361. // Scaling down color according to emissive
  15362. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15363. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15364. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15365. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15366. if (scene.lightsEnabled) {
  15367. var lightIndex = 0;
  15368. for (var index = 0; index < scene.lights.length; index++) {
  15369. var light = scene.lights[index];
  15370. if (!light.isEnabled()) {
  15371. continue;
  15372. }
  15373. if (!light.canAffectMesh(mesh)) {
  15374. continue;
  15375. }
  15376. if (light instanceof BABYLON.PointLight) {
  15377. // Point Light
  15378. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15379. }
  15380. else if (light instanceof BABYLON.DirectionalLight) {
  15381. // Directional Light
  15382. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15383. }
  15384. else if (light instanceof BABYLON.SpotLight) {
  15385. // Spot Light
  15386. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15387. }
  15388. else if (light instanceof BABYLON.HemisphericLight) {
  15389. // Hemispheric Light
  15390. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15391. }
  15392. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15393. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15394. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15395. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15396. // Shadows
  15397. if (scene.shadowsEnabled) {
  15398. var shadowGenerator = light.getShadowGenerator();
  15399. if (mesh.receiveShadows && shadowGenerator) {
  15400. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15401. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15402. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15403. }
  15404. }
  15405. lightIndex++;
  15406. if (lightIndex === maxSimultaneousLights)
  15407. break;
  15408. }
  15409. }
  15410. // View
  15411. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15412. this._effect.setMatrix("view", scene.getViewMatrix());
  15413. }
  15414. // Fog
  15415. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15416. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15417. this._effect.setColor3("vFogColor", scene.fogColor);
  15418. }
  15419. _super.prototype.bind.call(this, world, mesh);
  15420. };
  15421. StandardMaterial.prototype.getAnimatables = function () {
  15422. var results = [];
  15423. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15424. results.push(this.diffuseTexture);
  15425. }
  15426. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15427. results.push(this.ambientTexture);
  15428. }
  15429. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15430. results.push(this.opacityTexture);
  15431. }
  15432. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15433. results.push(this.reflectionTexture);
  15434. }
  15435. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15436. results.push(this.emissiveTexture);
  15437. }
  15438. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15439. results.push(this.specularTexture);
  15440. }
  15441. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15442. results.push(this.bumpTexture);
  15443. }
  15444. return results;
  15445. };
  15446. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15447. if (this.diffuseTexture) {
  15448. this.diffuseTexture.dispose();
  15449. }
  15450. if (this.ambientTexture) {
  15451. this.ambientTexture.dispose();
  15452. }
  15453. if (this.opacityTexture) {
  15454. this.opacityTexture.dispose();
  15455. }
  15456. if (this.reflectionTexture) {
  15457. this.reflectionTexture.dispose();
  15458. }
  15459. if (this.emissiveTexture) {
  15460. this.emissiveTexture.dispose();
  15461. }
  15462. if (this.specularTexture) {
  15463. this.specularTexture.dispose();
  15464. }
  15465. if (this.bumpTexture) {
  15466. this.bumpTexture.dispose();
  15467. }
  15468. _super.prototype.dispose.call(this, forceDisposeEffect);
  15469. };
  15470. StandardMaterial.prototype.clone = function (name) {
  15471. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15472. // Base material
  15473. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15474. newStandardMaterial.alpha = this.alpha;
  15475. newStandardMaterial.fillMode = this.fillMode;
  15476. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15477. // Standard material
  15478. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15479. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15480. }
  15481. if (this.ambientTexture && this.ambientTexture.clone) {
  15482. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15483. }
  15484. if (this.opacityTexture && this.opacityTexture.clone) {
  15485. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15486. }
  15487. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15488. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15489. }
  15490. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15491. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15492. }
  15493. if (this.specularTexture && this.specularTexture.clone) {
  15494. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15495. }
  15496. if (this.bumpTexture && this.bumpTexture.clone) {
  15497. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15498. }
  15499. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15500. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15501. newStandardMaterial.specularColor = this.specularColor.clone();
  15502. newStandardMaterial.specularPower = this.specularPower;
  15503. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15504. return newStandardMaterial;
  15505. };
  15506. // Statics
  15507. // Flags used to enable or disable a type of texture for all Standard Materials
  15508. StandardMaterial.DiffuseTextureEnabled = true;
  15509. StandardMaterial.AmbientTextureEnabled = true;
  15510. StandardMaterial.OpacityTextureEnabled = true;
  15511. StandardMaterial.ReflectionTextureEnabled = true;
  15512. StandardMaterial.EmissiveTextureEnabled = true;
  15513. StandardMaterial.SpecularTextureEnabled = true;
  15514. StandardMaterial.BumpTextureEnabled = true;
  15515. StandardMaterial.FresnelEnabled = true;
  15516. return StandardMaterial;
  15517. })(BABYLON.Material);
  15518. BABYLON.StandardMaterial = StandardMaterial;
  15519. })(BABYLON || (BABYLON = {}));
  15520. //# sourceMappingURL=babylon.standardMaterial.js.map
  15521. var BABYLON;
  15522. (function (BABYLON) {
  15523. var MultiMaterial = (function (_super) {
  15524. __extends(MultiMaterial, _super);
  15525. function MultiMaterial(name, scene) {
  15526. _super.call(this, name, scene, true);
  15527. this.subMaterials = new Array();
  15528. scene.multiMaterials.push(this);
  15529. }
  15530. // Properties
  15531. MultiMaterial.prototype.getSubMaterial = function (index) {
  15532. if (index < 0 || index >= this.subMaterials.length) {
  15533. return this.getScene().defaultMaterial;
  15534. }
  15535. return this.subMaterials[index];
  15536. };
  15537. // Methods
  15538. MultiMaterial.prototype.isReady = function (mesh) {
  15539. for (var index = 0; index < this.subMaterials.length; index++) {
  15540. var subMaterial = this.subMaterials[index];
  15541. if (subMaterial) {
  15542. if (!this.subMaterials[index].isReady(mesh)) {
  15543. return false;
  15544. }
  15545. }
  15546. }
  15547. return true;
  15548. };
  15549. return MultiMaterial;
  15550. })(BABYLON.Material);
  15551. BABYLON.MultiMaterial = MultiMaterial;
  15552. })(BABYLON || (BABYLON = {}));
  15553. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15554. (function (BABYLON) {
  15555. var Database = (function () {
  15556. function Database(urlToScene, callbackManifestChecked) {
  15557. // Handling various flavors of prefixed version of IndexedDB
  15558. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15559. this.callbackManifestChecked = callbackManifestChecked;
  15560. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15561. this.db = null;
  15562. this.enableSceneOffline = false;
  15563. this.enableTexturesOffline = false;
  15564. this.manifestVersionFound = 0;
  15565. this.mustUpdateRessources = false;
  15566. this.hasReachedQuota = false;
  15567. this.checkManifestFile();
  15568. }
  15569. Database.prototype.checkManifestFile = function () {
  15570. var _this = this;
  15571. function noManifestFile() {
  15572. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15573. that.enableSceneOffline = false;
  15574. that.enableTexturesOffline = false;
  15575. that.callbackManifestChecked(false);
  15576. }
  15577. var that = this;
  15578. var manifestURL = this.currentSceneUrl + ".manifest";
  15579. var xhr = new XMLHttpRequest();
  15580. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15581. xhr.open("GET", manifestURLTimeStamped, true);
  15582. xhr.addEventListener("load", function () {
  15583. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15584. try {
  15585. var manifestFile = JSON.parse(xhr.response);
  15586. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15587. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15588. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15589. _this.manifestVersionFound = manifestFile.version;
  15590. }
  15591. if (_this.callbackManifestChecked) {
  15592. _this.callbackManifestChecked(true);
  15593. }
  15594. }
  15595. catch (ex) {
  15596. noManifestFile();
  15597. }
  15598. }
  15599. else {
  15600. noManifestFile();
  15601. }
  15602. }, false);
  15603. xhr.addEventListener("error", function (event) {
  15604. noManifestFile();
  15605. }, false);
  15606. try {
  15607. xhr.send();
  15608. }
  15609. catch (ex) {
  15610. BABYLON.Tools.Error("Error on XHR send request.");
  15611. that.callbackManifestChecked(false);
  15612. }
  15613. };
  15614. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15615. var _this = this;
  15616. function handleError() {
  15617. that.isSupported = false;
  15618. if (errorCallback)
  15619. errorCallback();
  15620. }
  15621. var that = this;
  15622. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15623. // Your browser doesn't support IndexedDB
  15624. this.isSupported = false;
  15625. if (errorCallback)
  15626. errorCallback();
  15627. }
  15628. else {
  15629. // If the DB hasn't been opened or created yet
  15630. if (!this.db) {
  15631. this.hasReachedQuota = false;
  15632. this.isSupported = true;
  15633. var request = this.idbFactory.open("babylonjs", 1);
  15634. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15635. request.onerror = function (event) {
  15636. handleError();
  15637. };
  15638. // executes when a version change transaction cannot complete due to other active transactions
  15639. request.onblocked = function (event) {
  15640. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15641. handleError();
  15642. };
  15643. // DB has been opened successfully
  15644. request.onsuccess = function (event) {
  15645. _this.db = request.result;
  15646. successCallback();
  15647. };
  15648. // Initialization of the DB. Creating Scenes & Textures stores
  15649. request.onupgradeneeded = function (event) {
  15650. _this.db = (event.target).result;
  15651. try {
  15652. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15653. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15654. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15655. }
  15656. catch (ex) {
  15657. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15658. handleError();
  15659. }
  15660. };
  15661. }
  15662. else {
  15663. if (successCallback)
  15664. successCallback();
  15665. }
  15666. }
  15667. };
  15668. Database.prototype.loadImageFromDB = function (url, image) {
  15669. var _this = this;
  15670. var completeURL = Database.ReturnFullUrlLocation(url);
  15671. var saveAndLoadImage = function () {
  15672. if (!_this.hasReachedQuota && _this.db !== null) {
  15673. // the texture is not yet in the DB, let's try to save it
  15674. _this._saveImageIntoDBAsync(completeURL, image);
  15675. }
  15676. else {
  15677. image.src = url;
  15678. }
  15679. };
  15680. if (!this.mustUpdateRessources) {
  15681. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15682. }
  15683. else {
  15684. saveAndLoadImage();
  15685. }
  15686. };
  15687. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15688. if (this.isSupported && this.db !== null) {
  15689. var texture;
  15690. var transaction = this.db.transaction(["textures"]);
  15691. transaction.onabort = function (event) {
  15692. image.src = url;
  15693. };
  15694. transaction.oncomplete = function (event) {
  15695. var blobTextureURL;
  15696. if (texture) {
  15697. var URL = window.URL || window.webkitURL;
  15698. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15699. image.onerror = function () {
  15700. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15701. image.src = url;
  15702. };
  15703. image.src = blobTextureURL;
  15704. }
  15705. else {
  15706. notInDBCallback();
  15707. }
  15708. };
  15709. var getRequest = transaction.objectStore("textures").get(url);
  15710. getRequest.onsuccess = function (event) {
  15711. texture = (event.target).result;
  15712. };
  15713. getRequest.onerror = function (event) {
  15714. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15715. image.src = url;
  15716. };
  15717. }
  15718. else {
  15719. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15720. image.src = url;
  15721. }
  15722. };
  15723. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15724. var _this = this;
  15725. if (this.isSupported) {
  15726. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15727. var generateBlobUrl = function () {
  15728. var blobTextureURL;
  15729. if (blob) {
  15730. var URL = window.URL || window.webkitURL;
  15731. try {
  15732. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15733. }
  15734. catch (ex) {
  15735. blobTextureURL = URL.createObjectURL(blob);
  15736. }
  15737. }
  15738. image.src = blobTextureURL;
  15739. };
  15740. if (Database.isUASupportingBlobStorage) {
  15741. var xhr = new XMLHttpRequest(), blob;
  15742. xhr.open("GET", url, true);
  15743. xhr.responseType = "blob";
  15744. xhr.addEventListener("load", function () {
  15745. if (xhr.status === 200) {
  15746. // Blob as response (XHR2)
  15747. blob = xhr.response;
  15748. var transaction = _this.db.transaction(["textures"], "readwrite");
  15749. // the transaction could abort because of a QuotaExceededError error
  15750. transaction.onabort = function (event) {
  15751. try {
  15752. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15753. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15754. this.hasReachedQuota = true;
  15755. }
  15756. }
  15757. catch (ex) {
  15758. }
  15759. generateBlobUrl();
  15760. };
  15761. transaction.oncomplete = function (event) {
  15762. generateBlobUrl();
  15763. };
  15764. var newTexture = { textureUrl: url, data: blob };
  15765. try {
  15766. // Put the blob into the dabase
  15767. var addRequest = transaction.objectStore("textures").put(newTexture);
  15768. addRequest.onsuccess = function (event) {
  15769. };
  15770. addRequest.onerror = function (event) {
  15771. generateBlobUrl();
  15772. };
  15773. }
  15774. catch (ex) {
  15775. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15776. if (ex.code === 25) {
  15777. Database.isUASupportingBlobStorage = false;
  15778. }
  15779. image.src = url;
  15780. }
  15781. }
  15782. else {
  15783. image.src = url;
  15784. }
  15785. }, false);
  15786. xhr.addEventListener("error", function (event) {
  15787. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15788. image.src = url;
  15789. }, false);
  15790. xhr.send();
  15791. }
  15792. else {
  15793. image.src = url;
  15794. }
  15795. }
  15796. else {
  15797. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15798. image.src = url;
  15799. }
  15800. };
  15801. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15802. var _this = this;
  15803. var updateVersion = function (event) {
  15804. // the version is not yet in the DB or we need to update it
  15805. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15806. };
  15807. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15808. };
  15809. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15810. var _this = this;
  15811. if (this.isSupported) {
  15812. var version;
  15813. try {
  15814. var transaction = this.db.transaction(["versions"]);
  15815. transaction.oncomplete = function (event) {
  15816. if (version) {
  15817. // If the version in the JSON file is > than the version in DB
  15818. if (_this.manifestVersionFound > version.data) {
  15819. _this.mustUpdateRessources = true;
  15820. updateInDBCallback();
  15821. }
  15822. else {
  15823. callback(version.data);
  15824. }
  15825. }
  15826. else {
  15827. _this.mustUpdateRessources = true;
  15828. updateInDBCallback();
  15829. }
  15830. };
  15831. transaction.onabort = function (event) {
  15832. callback(-1);
  15833. };
  15834. var getRequest = transaction.objectStore("versions").get(url);
  15835. getRequest.onsuccess = function (event) {
  15836. version = (event.target).result;
  15837. };
  15838. getRequest.onerror = function (event) {
  15839. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15840. callback(-1);
  15841. };
  15842. }
  15843. catch (ex) {
  15844. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15845. callback(-1);
  15846. }
  15847. }
  15848. else {
  15849. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15850. callback(-1);
  15851. }
  15852. };
  15853. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15854. var _this = this;
  15855. if (this.isSupported && !this.hasReachedQuota) {
  15856. try {
  15857. // Open a transaction to the database
  15858. var transaction = this.db.transaction(["versions"], "readwrite");
  15859. // the transaction could abort because of a QuotaExceededError error
  15860. transaction.onabort = function (event) {
  15861. try {
  15862. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15863. _this.hasReachedQuota = true;
  15864. }
  15865. }
  15866. catch (ex) {
  15867. }
  15868. callback(-1);
  15869. };
  15870. transaction.oncomplete = function (event) {
  15871. callback(_this.manifestVersionFound);
  15872. };
  15873. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15874. // Put the scene into the database
  15875. var addRequest = transaction.objectStore("versions").put(newVersion);
  15876. addRequest.onsuccess = function (event) {
  15877. };
  15878. addRequest.onerror = function (event) {
  15879. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15880. };
  15881. }
  15882. catch (ex) {
  15883. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15884. callback(-1);
  15885. }
  15886. }
  15887. else {
  15888. callback(-1);
  15889. }
  15890. };
  15891. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15892. var _this = this;
  15893. var completeUrl = Database.ReturnFullUrlLocation(url);
  15894. var saveAndLoadFile = function (event) {
  15895. // the scene is not yet in the DB, let's try to save it
  15896. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15897. };
  15898. this._checkVersionFromDB(completeUrl, function (version) {
  15899. if (version !== -1) {
  15900. if (!_this.mustUpdateRessources) {
  15901. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15902. }
  15903. else {
  15904. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15905. }
  15906. }
  15907. else {
  15908. errorCallback();
  15909. }
  15910. });
  15911. };
  15912. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15913. if (this.isSupported) {
  15914. var targetStore;
  15915. if (url.indexOf(".babylon") !== -1) {
  15916. targetStore = "scenes";
  15917. }
  15918. else {
  15919. targetStore = "textures";
  15920. }
  15921. var file;
  15922. var transaction = this.db.transaction([targetStore]);
  15923. transaction.oncomplete = function (event) {
  15924. if (file) {
  15925. callback(file.data);
  15926. }
  15927. else {
  15928. notInDBCallback();
  15929. }
  15930. };
  15931. transaction.onabort = function (event) {
  15932. notInDBCallback();
  15933. };
  15934. var getRequest = transaction.objectStore(targetStore).get(url);
  15935. getRequest.onsuccess = function (event) {
  15936. file = (event.target).result;
  15937. };
  15938. getRequest.onerror = function (event) {
  15939. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15940. notInDBCallback();
  15941. };
  15942. }
  15943. else {
  15944. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15945. callback();
  15946. }
  15947. };
  15948. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15949. var _this = this;
  15950. if (this.isSupported) {
  15951. var targetStore;
  15952. if (url.indexOf(".babylon") !== -1) {
  15953. targetStore = "scenes";
  15954. }
  15955. else {
  15956. targetStore = "textures";
  15957. }
  15958. // Create XHR
  15959. var xhr = new XMLHttpRequest(), fileData;
  15960. xhr.open("GET", url, true);
  15961. if (useArrayBuffer) {
  15962. xhr.responseType = "arraybuffer";
  15963. }
  15964. xhr.onprogress = progressCallback;
  15965. xhr.addEventListener("load", function () {
  15966. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15967. // Blob as response (XHR2)
  15968. //fileData = xhr.responseText;
  15969. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15970. if (!_this.hasReachedQuota) {
  15971. // Open a transaction to the database
  15972. var transaction = _this.db.transaction([targetStore], "readwrite");
  15973. // the transaction could abort because of a QuotaExceededError error
  15974. transaction.onabort = function (event) {
  15975. try {
  15976. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15977. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15978. this.hasReachedQuota = true;
  15979. }
  15980. }
  15981. catch (ex) {
  15982. }
  15983. callback(fileData);
  15984. };
  15985. transaction.oncomplete = function (event) {
  15986. callback(fileData);
  15987. };
  15988. var newFile;
  15989. if (targetStore === "scenes") {
  15990. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15991. }
  15992. else {
  15993. newFile = { textureUrl: url, data: fileData };
  15994. }
  15995. try {
  15996. // Put the scene into the database
  15997. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15998. addRequest.onsuccess = function (event) {
  15999. };
  16000. addRequest.onerror = function (event) {
  16001. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  16002. };
  16003. }
  16004. catch (ex) {
  16005. callback(fileData);
  16006. }
  16007. }
  16008. else {
  16009. callback(fileData);
  16010. }
  16011. }
  16012. else {
  16013. callback();
  16014. }
  16015. }, false);
  16016. xhr.addEventListener("error", function (event) {
  16017. BABYLON.Tools.Error("error on XHR request.");
  16018. callback();
  16019. }, false);
  16020. xhr.send();
  16021. }
  16022. else {
  16023. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  16024. callback();
  16025. }
  16026. };
  16027. Database.isUASupportingBlobStorage = true;
  16028. Database.parseURL = function (url) {
  16029. var a = document.createElement('a');
  16030. a.href = url;
  16031. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  16032. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  16033. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  16034. return absLocation;
  16035. };
  16036. Database.ReturnFullUrlLocation = function (url) {
  16037. if (url.indexOf("http:/") === -1) {
  16038. return (BABYLON.Database.parseURL(window.location.href) + url);
  16039. }
  16040. else {
  16041. return url;
  16042. }
  16043. };
  16044. return Database;
  16045. })();
  16046. BABYLON.Database = Database;
  16047. })(BABYLON || (BABYLON = {}));
  16048. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  16049. (function (BABYLON) {
  16050. var SpriteManager = (function () {
  16051. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  16052. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16053. this.name = name;
  16054. this.cellSize = cellSize;
  16055. this.sprites = new Array();
  16056. this.renderingGroupId = 0;
  16057. this.fogEnabled = true;
  16058. this._vertexDeclaration = [4, 4, 4, 4];
  16059. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  16060. this._capacity = capacity;
  16061. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  16062. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16063. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16064. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  16065. this._scene = scene;
  16066. this._scene.spriteManagers.push(this);
  16067. // VBO
  16068. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16069. var indices = [];
  16070. var index = 0;
  16071. for (var count = 0; count < capacity; count++) {
  16072. indices.push(index);
  16073. indices.push(index + 1);
  16074. indices.push(index + 2);
  16075. indices.push(index);
  16076. indices.push(index + 2);
  16077. indices.push(index + 3);
  16078. index += 4;
  16079. }
  16080. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16081. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16082. // Effects
  16083. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  16084. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  16085. }
  16086. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  16087. var arrayOffset = index * 16;
  16088. if (offsetX === 0)
  16089. offsetX = this._epsilon;
  16090. else if (offsetX === 1)
  16091. offsetX = 1 - this._epsilon;
  16092. if (offsetY === 0)
  16093. offsetY = this._epsilon;
  16094. else if (offsetY === 1)
  16095. offsetY = 1 - this._epsilon;
  16096. this._vertices[arrayOffset] = sprite.position.x;
  16097. this._vertices[arrayOffset + 1] = sprite.position.y;
  16098. this._vertices[arrayOffset + 2] = sprite.position.z;
  16099. this._vertices[arrayOffset + 3] = sprite.angle;
  16100. this._vertices[arrayOffset + 4] = sprite.width;
  16101. this._vertices[arrayOffset + 5] = sprite.height;
  16102. this._vertices[arrayOffset + 6] = offsetX;
  16103. this._vertices[arrayOffset + 7] = offsetY;
  16104. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  16105. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  16106. var offset = (sprite.cellIndex / rowSize) >> 0;
  16107. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  16108. this._vertices[arrayOffset + 11] = offset;
  16109. // Color
  16110. this._vertices[arrayOffset + 12] = sprite.color.r;
  16111. this._vertices[arrayOffset + 13] = sprite.color.g;
  16112. this._vertices[arrayOffset + 14] = sprite.color.b;
  16113. this._vertices[arrayOffset + 15] = sprite.color.a;
  16114. };
  16115. SpriteManager.prototype.render = function () {
  16116. // Check
  16117. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  16118. return;
  16119. var engine = this._scene.getEngine();
  16120. var baseSize = this._spriteTexture.getBaseSize();
  16121. // Sprites
  16122. var deltaTime = engine.getDeltaTime();
  16123. var max = Math.min(this._capacity, this.sprites.length);
  16124. var rowSize = baseSize.width / this.cellSize;
  16125. var offset = 0;
  16126. for (var index = 0; index < max; index++) {
  16127. var sprite = this.sprites[index];
  16128. if (!sprite) {
  16129. continue;
  16130. }
  16131. sprite._animate(deltaTime);
  16132. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  16133. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  16134. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  16135. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  16136. }
  16137. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16138. // Render
  16139. var effect = this._effectBase;
  16140. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16141. effect = this._effectFog;
  16142. }
  16143. engine.enableEffect(effect);
  16144. var viewMatrix = this._scene.getViewMatrix();
  16145. effect.setTexture("diffuseSampler", this._spriteTexture);
  16146. effect.setMatrix("view", viewMatrix);
  16147. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16148. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  16149. // Fog
  16150. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16151. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  16152. effect.setColor3("vFogColor", this._scene.fogColor);
  16153. }
  16154. // VBOs
  16155. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16156. // Draw order
  16157. engine.setDepthFunctionToLessOrEqual();
  16158. effect.setBool("alphaTest", true);
  16159. engine.setColorWrite(false);
  16160. engine.draw(true, 0, max * 6);
  16161. engine.setColorWrite(true);
  16162. effect.setBool("alphaTest", false);
  16163. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16164. engine.draw(true, 0, max * 6);
  16165. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16166. };
  16167. SpriteManager.prototype.dispose = function () {
  16168. if (this._vertexBuffer) {
  16169. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16170. this._vertexBuffer = null;
  16171. }
  16172. if (this._indexBuffer) {
  16173. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16174. this._indexBuffer = null;
  16175. }
  16176. if (this._spriteTexture) {
  16177. this._spriteTexture.dispose();
  16178. this._spriteTexture = null;
  16179. }
  16180. // Remove from scene
  16181. var index = this._scene.spriteManagers.indexOf(this);
  16182. this._scene.spriteManagers.splice(index, 1);
  16183. // Callback
  16184. if (this.onDispose) {
  16185. this.onDispose();
  16186. }
  16187. };
  16188. return SpriteManager;
  16189. })();
  16190. BABYLON.SpriteManager = SpriteManager;
  16191. })(BABYLON || (BABYLON = {}));
  16192. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  16193. (function (BABYLON) {
  16194. var Sprite = (function () {
  16195. function Sprite(name, manager) {
  16196. this.name = name;
  16197. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16198. this.width = 1.0;
  16199. this.height = 1.0;
  16200. this.angle = 0;
  16201. this.cellIndex = 0;
  16202. this.invertU = 0;
  16203. this.invertV = 0;
  16204. this.animations = new Array();
  16205. this._animationStarted = false;
  16206. this._loopAnimation = false;
  16207. this._fromIndex = 0;
  16208. this._toIndex = 0;
  16209. this._delay = 0;
  16210. this._direction = 1;
  16211. this._frameCount = 0;
  16212. this._time = 0;
  16213. this._manager = manager;
  16214. this._manager.sprites.push(this);
  16215. this.position = BABYLON.Vector3.Zero();
  16216. }
  16217. Object.defineProperty(Sprite.prototype, "size", {
  16218. get: function () {
  16219. return this.width;
  16220. },
  16221. set: function (value) {
  16222. this.width = value;
  16223. this.height = value;
  16224. },
  16225. enumerable: true,
  16226. configurable: true
  16227. });
  16228. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  16229. this._fromIndex = from;
  16230. this._toIndex = to;
  16231. this._loopAnimation = loop;
  16232. this._delay = delay;
  16233. this._animationStarted = true;
  16234. this._direction = from < to ? 1 : -1;
  16235. this.cellIndex = from;
  16236. this._time = 0;
  16237. };
  16238. Sprite.prototype.stopAnimation = function () {
  16239. this._animationStarted = false;
  16240. };
  16241. Sprite.prototype._animate = function (deltaTime) {
  16242. if (!this._animationStarted)
  16243. return;
  16244. this._time += deltaTime;
  16245. if (this._time > this._delay) {
  16246. this._time = this._time % this._delay;
  16247. this.cellIndex += this._direction;
  16248. if (this.cellIndex == this._toIndex) {
  16249. if (this._loopAnimation) {
  16250. this.cellIndex = this._fromIndex;
  16251. }
  16252. else {
  16253. this._animationStarted = false;
  16254. if (this.disposeWhenFinishedAnimating) {
  16255. this.dispose();
  16256. }
  16257. }
  16258. }
  16259. }
  16260. };
  16261. Sprite.prototype.dispose = function () {
  16262. for (var i = 0; i < this._manager.sprites.length; i++) {
  16263. if (this._manager.sprites[i] == this) {
  16264. this._manager.sprites.splice(i, 1);
  16265. }
  16266. }
  16267. };
  16268. return Sprite;
  16269. })();
  16270. BABYLON.Sprite = Sprite;
  16271. })(BABYLON || (BABYLON = {}));
  16272. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  16273. (function (BABYLON) {
  16274. var Layer = (function () {
  16275. function Layer(name, imgUrl, scene, isBackground, color) {
  16276. this.name = name;
  16277. this._vertexDeclaration = [2];
  16278. this._vertexStrideSize = 2 * 4;
  16279. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16280. this.isBackground = isBackground === undefined ? true : isBackground;
  16281. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16282. this._scene = scene;
  16283. this._scene.layers.push(this);
  16284. // VBO
  16285. var vertices = [];
  16286. vertices.push(1, 1);
  16287. vertices.push(-1, 1);
  16288. vertices.push(-1, -1);
  16289. vertices.push(1, -1);
  16290. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16291. // Indices
  16292. var indices = [];
  16293. indices.push(0);
  16294. indices.push(1);
  16295. indices.push(2);
  16296. indices.push(0);
  16297. indices.push(2);
  16298. indices.push(3);
  16299. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16300. // Effects
  16301. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16302. }
  16303. Layer.prototype.render = function () {
  16304. // Check
  16305. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16306. return;
  16307. var engine = this._scene.getEngine();
  16308. // Render
  16309. engine.enableEffect(this._effect);
  16310. engine.setState(false);
  16311. // Texture
  16312. this._effect.setTexture("textureSampler", this.texture);
  16313. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16314. // Color
  16315. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16316. // VBOs
  16317. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16318. // Draw order
  16319. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16320. engine.draw(true, 0, 6);
  16321. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16322. };
  16323. Layer.prototype.dispose = function () {
  16324. if (this._vertexBuffer) {
  16325. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16326. this._vertexBuffer = null;
  16327. }
  16328. if (this._indexBuffer) {
  16329. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16330. this._indexBuffer = null;
  16331. }
  16332. if (this.texture) {
  16333. this.texture.dispose();
  16334. this.texture = null;
  16335. }
  16336. // Remove from scene
  16337. var index = this._scene.layers.indexOf(this);
  16338. this._scene.layers.splice(index, 1);
  16339. // Callback
  16340. if (this.onDispose) {
  16341. this.onDispose();
  16342. }
  16343. };
  16344. return Layer;
  16345. })();
  16346. BABYLON.Layer = Layer;
  16347. })(BABYLON || (BABYLON = {}));
  16348. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16349. (function (BABYLON) {
  16350. var Particle = (function () {
  16351. function Particle() {
  16352. this.position = BABYLON.Vector3.Zero();
  16353. this.direction = BABYLON.Vector3.Zero();
  16354. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16355. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16356. this.lifeTime = 1.0;
  16357. this.age = 0;
  16358. this.size = 0;
  16359. this.angle = 0;
  16360. this.angularSpeed = 0;
  16361. }
  16362. Particle.prototype.copyTo = function (other) {
  16363. other.position.copyFrom(this.position);
  16364. other.direction.copyFrom(this.direction);
  16365. other.color.copyFrom(this.color);
  16366. other.colorStep.copyFrom(this.colorStep);
  16367. other.lifeTime = this.lifeTime;
  16368. other.age = this.age;
  16369. other.size = this.size;
  16370. other.angle = this.angle;
  16371. other.angularSpeed = this.angularSpeed;
  16372. };
  16373. return Particle;
  16374. })();
  16375. BABYLON.Particle = Particle;
  16376. })(BABYLON || (BABYLON = {}));
  16377. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16378. (function (BABYLON) {
  16379. var randomNumber = function (min, max) {
  16380. if (min === max) {
  16381. return (min);
  16382. }
  16383. var random = Math.random();
  16384. return ((random * (max - min)) + min);
  16385. };
  16386. var ParticleSystem = (function () {
  16387. function ParticleSystem(name, capacity, scene, customEffect) {
  16388. var _this = this;
  16389. this.name = name;
  16390. this.renderingGroupId = 0;
  16391. this.emitter = null;
  16392. this.emitRate = 10;
  16393. this.manualEmitCount = -1;
  16394. this.updateSpeed = 0.01;
  16395. this.targetStopDuration = 0;
  16396. this.disposeOnStop = false;
  16397. this.minEmitPower = 1;
  16398. this.maxEmitPower = 1;
  16399. this.minLifeTime = 1;
  16400. this.maxLifeTime = 1;
  16401. this.minSize = 1;
  16402. this.maxSize = 1;
  16403. this.minAngularSpeed = 0;
  16404. this.maxAngularSpeed = 0;
  16405. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16406. this.forceDepthWrite = false;
  16407. this.gravity = BABYLON.Vector3.Zero();
  16408. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16409. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16410. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16411. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16412. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16413. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16414. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16415. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16416. this.particles = new Array();
  16417. this._vertexDeclaration = [3, 4, 4];
  16418. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16419. this._stockParticles = new Array();
  16420. this._newPartsExcess = 0;
  16421. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16422. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16423. this._scaledDirection = BABYLON.Vector3.Zero();
  16424. this._scaledGravity = BABYLON.Vector3.Zero();
  16425. this._currentRenderId = -1;
  16426. this._started = false;
  16427. this._stopped = false;
  16428. this._actualFrame = 0;
  16429. this.id = name;
  16430. this._capacity = capacity;
  16431. this._scene = scene;
  16432. this._customEffect = customEffect;
  16433. scene.particleSystems.push(this);
  16434. // VBO
  16435. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16436. var indices = [];
  16437. var index = 0;
  16438. for (var count = 0; count < capacity; count++) {
  16439. indices.push(index);
  16440. indices.push(index + 1);
  16441. indices.push(index + 2);
  16442. indices.push(index);
  16443. indices.push(index + 2);
  16444. indices.push(index + 3);
  16445. index += 4;
  16446. }
  16447. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16448. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16449. // Default behaviors
  16450. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16451. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16452. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16453. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16454. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16455. };
  16456. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16457. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16458. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16459. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16461. };
  16462. this.updateFunction = function (particles) {
  16463. for (var index = 0; index < particles.length; index++) {
  16464. var particle = particles[index];
  16465. particle.age += _this._scaledUpdateSpeed;
  16466. if (particle.age >= particle.lifeTime) {
  16467. _this.recycleParticle(particle);
  16468. index--;
  16469. continue;
  16470. }
  16471. else {
  16472. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16473. particle.color.addInPlace(_this._scaledColorStep);
  16474. if (particle.color.a < 0)
  16475. particle.color.a = 0;
  16476. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16477. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16478. particle.position.addInPlace(_this._scaledDirection);
  16479. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16480. particle.direction.addInPlace(_this._scaledGravity);
  16481. }
  16482. }
  16483. };
  16484. }
  16485. ParticleSystem.prototype.recycleParticle = function (particle) {
  16486. var lastParticle = this.particles.pop();
  16487. if (lastParticle !== particle) {
  16488. lastParticle.copyTo(particle);
  16489. this._stockParticles.push(lastParticle);
  16490. }
  16491. };
  16492. ParticleSystem.prototype.getCapacity = function () {
  16493. return this._capacity;
  16494. };
  16495. ParticleSystem.prototype.isAlive = function () {
  16496. return this._alive;
  16497. };
  16498. ParticleSystem.prototype.isStarted = function () {
  16499. return this._started;
  16500. };
  16501. ParticleSystem.prototype.start = function () {
  16502. this._started = true;
  16503. this._stopped = false;
  16504. this._actualFrame = 0;
  16505. };
  16506. ParticleSystem.prototype.stop = function () {
  16507. this._stopped = true;
  16508. };
  16509. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16510. var offset = index * 11;
  16511. this._vertices[offset] = particle.position.x;
  16512. this._vertices[offset + 1] = particle.position.y;
  16513. this._vertices[offset + 2] = particle.position.z;
  16514. this._vertices[offset + 3] = particle.color.r;
  16515. this._vertices[offset + 4] = particle.color.g;
  16516. this._vertices[offset + 5] = particle.color.b;
  16517. this._vertices[offset + 6] = particle.color.a;
  16518. this._vertices[offset + 7] = particle.angle;
  16519. this._vertices[offset + 8] = particle.size;
  16520. this._vertices[offset + 9] = offsetX;
  16521. this._vertices[offset + 10] = offsetY;
  16522. };
  16523. ParticleSystem.prototype._update = function (newParticles) {
  16524. // Update current
  16525. this._alive = this.particles.length > 0;
  16526. this.updateFunction(this.particles);
  16527. // Add new ones
  16528. var worldMatrix;
  16529. if (this.emitter.position) {
  16530. worldMatrix = this.emitter.getWorldMatrix();
  16531. }
  16532. else {
  16533. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16534. }
  16535. for (var index = 0; index < newParticles; index++) {
  16536. if (this.particles.length === this._capacity) {
  16537. break;
  16538. }
  16539. if (this._stockParticles.length !== 0) {
  16540. var particle = this._stockParticles.pop();
  16541. particle.age = 0;
  16542. }
  16543. else {
  16544. particle = new BABYLON.Particle();
  16545. }
  16546. this.particles.push(particle);
  16547. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16548. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16549. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16550. particle.size = randomNumber(this.minSize, this.maxSize);
  16551. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16552. this.startPositionFunction(worldMatrix, particle.position);
  16553. var step = randomNumber(0, 1.0);
  16554. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16555. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16556. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16557. }
  16558. };
  16559. ParticleSystem.prototype._getEffect = function () {
  16560. if (this._customEffect) {
  16561. return this._customEffect;
  16562. }
  16563. ;
  16564. var defines = [];
  16565. if (this._scene.clipPlane) {
  16566. defines.push("#define CLIPPLANE");
  16567. }
  16568. // Effect
  16569. var join = defines.join("\n");
  16570. if (this._cachedDefines !== join) {
  16571. this._cachedDefines = join;
  16572. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16573. }
  16574. return this._effect;
  16575. };
  16576. ParticleSystem.prototype.animate = function () {
  16577. if (!this._started)
  16578. return;
  16579. var effect = this._getEffect();
  16580. // Check
  16581. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16582. return;
  16583. if (this._currentRenderId === this._scene.getRenderId()) {
  16584. return;
  16585. }
  16586. this._currentRenderId = this._scene.getRenderId();
  16587. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16588. // determine the number of particles we need to create
  16589. var emitCout;
  16590. if (this.manualEmitCount > -1) {
  16591. emitCout = this.manualEmitCount;
  16592. this.manualEmitCount = 0;
  16593. }
  16594. else {
  16595. emitCout = this.emitRate;
  16596. }
  16597. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16598. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16599. if (this._newPartsExcess > 1.0) {
  16600. newParticles += this._newPartsExcess >> 0;
  16601. this._newPartsExcess -= this._newPartsExcess >> 0;
  16602. }
  16603. this._alive = false;
  16604. if (!this._stopped) {
  16605. this._actualFrame += this._scaledUpdateSpeed;
  16606. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16607. this.stop();
  16608. }
  16609. else {
  16610. newParticles = 0;
  16611. }
  16612. this._update(newParticles);
  16613. // Stopped?
  16614. if (this._stopped) {
  16615. if (!this._alive) {
  16616. this._started = false;
  16617. if (this.disposeOnStop) {
  16618. this._scene._toBeDisposed.push(this);
  16619. }
  16620. }
  16621. }
  16622. // Update VBO
  16623. var offset = 0;
  16624. for (var index = 0; index < this.particles.length; index++) {
  16625. var particle = this.particles[index];
  16626. this._appendParticleVertex(offset++, particle, 0, 0);
  16627. this._appendParticleVertex(offset++, particle, 1, 0);
  16628. this._appendParticleVertex(offset++, particle, 1, 1);
  16629. this._appendParticleVertex(offset++, particle, 0, 1);
  16630. }
  16631. var engine = this._scene.getEngine();
  16632. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16633. };
  16634. ParticleSystem.prototype.render = function () {
  16635. var effect = this._getEffect();
  16636. // Check
  16637. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16638. return 0;
  16639. var engine = this._scene.getEngine();
  16640. // Render
  16641. engine.enableEffect(effect);
  16642. engine.setState(false);
  16643. var viewMatrix = this._scene.getViewMatrix();
  16644. effect.setTexture("diffuseSampler", this.particleTexture);
  16645. effect.setMatrix("view", viewMatrix);
  16646. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16647. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16648. if (this._scene.clipPlane) {
  16649. var clipPlane = this._scene.clipPlane;
  16650. var invView = viewMatrix.clone();
  16651. invView.invert();
  16652. effect.setMatrix("invView", invView);
  16653. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16654. }
  16655. // VBOs
  16656. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16657. // Draw order
  16658. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16659. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16660. }
  16661. else {
  16662. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16663. }
  16664. if (this.forceDepthWrite) {
  16665. engine.setDepthWrite(true);
  16666. }
  16667. engine.draw(true, 0, this.particles.length * 6);
  16668. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16669. return this.particles.length;
  16670. };
  16671. ParticleSystem.prototype.dispose = function () {
  16672. if (this._vertexBuffer) {
  16673. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16674. this._vertexBuffer = null;
  16675. }
  16676. if (this._indexBuffer) {
  16677. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16678. this._indexBuffer = null;
  16679. }
  16680. if (this.particleTexture) {
  16681. this.particleTexture.dispose();
  16682. this.particleTexture = null;
  16683. }
  16684. // Remove from scene
  16685. var index = this._scene.particleSystems.indexOf(this);
  16686. this._scene.particleSystems.splice(index, 1);
  16687. // Callback
  16688. if (this.onDispose) {
  16689. this.onDispose();
  16690. }
  16691. };
  16692. // Clone
  16693. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16694. var result = new ParticleSystem(name, this._capacity, this._scene);
  16695. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16696. if (newEmitter === undefined) {
  16697. newEmitter = this.emitter;
  16698. }
  16699. result.emitter = newEmitter;
  16700. if (this.particleTexture) {
  16701. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16702. }
  16703. result.start();
  16704. return result;
  16705. };
  16706. // Statics
  16707. ParticleSystem.BLENDMODE_ONEONE = 0;
  16708. ParticleSystem.BLENDMODE_STANDARD = 1;
  16709. return ParticleSystem;
  16710. })();
  16711. BABYLON.ParticleSystem = ParticleSystem;
  16712. })(BABYLON || (BABYLON = {}));
  16713. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16714. (function (BABYLON) {
  16715. var Animation = (function () {
  16716. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16717. this.name = name;
  16718. this.targetProperty = targetProperty;
  16719. this.framePerSecond = framePerSecond;
  16720. this.dataType = dataType;
  16721. this.loopMode = loopMode;
  16722. this._offsetsCache = {};
  16723. this._highLimitsCache = {};
  16724. this._stopped = false;
  16725. this.targetPropertyPath = targetProperty.split(".");
  16726. this.dataType = dataType;
  16727. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16728. }
  16729. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16730. var dataType = undefined;
  16731. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16732. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16733. }
  16734. else if (from instanceof BABYLON.Quaternion) {
  16735. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16736. }
  16737. else if (from instanceof BABYLON.Vector3) {
  16738. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16739. }
  16740. else if (from instanceof BABYLON.Vector2) {
  16741. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16742. }
  16743. else if (from instanceof BABYLON.Color3) {
  16744. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16745. }
  16746. if (dataType == undefined) {
  16747. return null;
  16748. }
  16749. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16750. var keys = [];
  16751. keys.push({ frame: 0, value: from });
  16752. keys.push({ frame: totalFrame, value: to });
  16753. animation.setKeys(keys);
  16754. mesh.animations.push(animation);
  16755. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16756. };
  16757. // Methods
  16758. Animation.prototype.isStopped = function () {
  16759. return this._stopped;
  16760. };
  16761. Animation.prototype.getKeys = function () {
  16762. return this._keys;
  16763. };
  16764. Animation.prototype.getEasingFunction = function () {
  16765. return this._easingFunction;
  16766. };
  16767. Animation.prototype.setEasingFunction = function (easingFunction) {
  16768. this._easingFunction = easingFunction;
  16769. };
  16770. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16771. return startValue + (endValue - startValue) * gradient;
  16772. };
  16773. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16774. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16775. };
  16776. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16777. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16778. };
  16779. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16780. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16781. };
  16782. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16783. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16784. };
  16785. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16786. var startScale = new BABYLON.Vector3(0, 0, 0);
  16787. var startRotation = new BABYLON.Quaternion();
  16788. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16789. startValue.decompose(startScale, startRotation, startTranslation);
  16790. var endScale = new BABYLON.Vector3(0, 0, 0);
  16791. var endRotation = new BABYLON.Quaternion();
  16792. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16793. endValue.decompose(endScale, endRotation, endTranslation);
  16794. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16795. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16796. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16797. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16798. return result;
  16799. };
  16800. Animation.prototype.clone = function () {
  16801. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16802. clone.setKeys(this._keys);
  16803. return clone;
  16804. };
  16805. Animation.prototype.setKeys = function (values) {
  16806. this._keys = values.slice(0);
  16807. this._offsetsCache = {};
  16808. this._highLimitsCache = {};
  16809. };
  16810. Animation.prototype._getKeyValue = function (value) {
  16811. if (typeof value === "function") {
  16812. return value();
  16813. }
  16814. return value;
  16815. };
  16816. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16817. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16818. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16819. }
  16820. this.currentFrame = currentFrame;
  16821. // Try to get a hash to find the right key
  16822. 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));
  16823. if (this._keys[startKey].frame >= currentFrame) {
  16824. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16825. startKey--;
  16826. }
  16827. }
  16828. for (var key = startKey; key < this._keys.length; key++) {
  16829. if (this._keys[key + 1].frame >= currentFrame) {
  16830. var startValue = this._getKeyValue(this._keys[key].value);
  16831. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16832. // gradient : percent of currentFrame between the frame inf and the frame sup
  16833. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16834. // check for easingFunction and correction of gradient
  16835. if (this._easingFunction != null) {
  16836. gradient = this._easingFunction.ease(gradient);
  16837. }
  16838. switch (this.dataType) {
  16839. case Animation.ANIMATIONTYPE_FLOAT:
  16840. switch (loopMode) {
  16841. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16842. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16843. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16844. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16845. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16846. }
  16847. break;
  16848. case Animation.ANIMATIONTYPE_QUATERNION:
  16849. var quaternion = null;
  16850. switch (loopMode) {
  16851. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16852. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16853. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16854. break;
  16855. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16856. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16857. break;
  16858. }
  16859. return quaternion;
  16860. case Animation.ANIMATIONTYPE_VECTOR3:
  16861. switch (loopMode) {
  16862. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16863. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16864. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16865. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16866. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16867. }
  16868. case Animation.ANIMATIONTYPE_VECTOR2:
  16869. switch (loopMode) {
  16870. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16871. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16872. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16873. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16874. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16875. }
  16876. case Animation.ANIMATIONTYPE_COLOR3:
  16877. switch (loopMode) {
  16878. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16879. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16880. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16881. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16882. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16883. }
  16884. case Animation.ANIMATIONTYPE_MATRIX:
  16885. switch (loopMode) {
  16886. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16887. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16888. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16889. return startValue;
  16890. }
  16891. default:
  16892. break;
  16893. }
  16894. break;
  16895. }
  16896. }
  16897. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16898. };
  16899. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16900. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16901. this._stopped = true;
  16902. return false;
  16903. }
  16904. var returnValue = true;
  16905. // Adding a start key at frame 0 if missing
  16906. if (this._keys[0].frame !== 0) {
  16907. var newKey = { frame: 0, value: this._keys[0].value };
  16908. this._keys.splice(0, 0, newKey);
  16909. }
  16910. // Check limits
  16911. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16912. from = this._keys[0].frame;
  16913. }
  16914. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16915. to = this._keys[this._keys.length - 1].frame;
  16916. }
  16917. // Compute ratio
  16918. var range = to - from;
  16919. var offsetValue;
  16920. // ratio represents the frame delta between from and to
  16921. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16922. var highLimitValue = 0;
  16923. if (ratio > range && !loop) {
  16924. returnValue = false;
  16925. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16926. }
  16927. else {
  16928. // Get max value if required
  16929. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16930. var keyOffset = to.toString() + from.toString();
  16931. if (!this._offsetsCache[keyOffset]) {
  16932. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16933. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16934. switch (this.dataType) {
  16935. case Animation.ANIMATIONTYPE_FLOAT:
  16936. this._offsetsCache[keyOffset] = toValue - fromValue;
  16937. break;
  16938. case Animation.ANIMATIONTYPE_QUATERNION:
  16939. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16940. break;
  16941. case Animation.ANIMATIONTYPE_VECTOR3:
  16942. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16943. case Animation.ANIMATIONTYPE_VECTOR2:
  16944. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16945. case Animation.ANIMATIONTYPE_COLOR3:
  16946. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16947. default:
  16948. break;
  16949. }
  16950. this._highLimitsCache[keyOffset] = toValue;
  16951. }
  16952. highLimitValue = this._highLimitsCache[keyOffset];
  16953. offsetValue = this._offsetsCache[keyOffset];
  16954. }
  16955. }
  16956. if (offsetValue === undefined) {
  16957. switch (this.dataType) {
  16958. case Animation.ANIMATIONTYPE_FLOAT:
  16959. offsetValue = 0;
  16960. break;
  16961. case Animation.ANIMATIONTYPE_QUATERNION:
  16962. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16963. break;
  16964. case Animation.ANIMATIONTYPE_VECTOR3:
  16965. offsetValue = BABYLON.Vector3.Zero();
  16966. break;
  16967. case Animation.ANIMATIONTYPE_VECTOR2:
  16968. offsetValue = BABYLON.Vector2.Zero();
  16969. break;
  16970. case Animation.ANIMATIONTYPE_COLOR3:
  16971. offsetValue = BABYLON.Color3.Black();
  16972. }
  16973. }
  16974. // Compute value
  16975. var repeatCount = (ratio / range) >> 0;
  16976. var currentFrame = returnValue ? from + ratio % range : to;
  16977. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16978. // Set value
  16979. if (this.targetPropertyPath.length > 1) {
  16980. var property = this._target[this.targetPropertyPath[0]];
  16981. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16982. property = property[this.targetPropertyPath[index]];
  16983. }
  16984. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16985. }
  16986. else {
  16987. this._target[this.targetPropertyPath[0]] = currentValue;
  16988. }
  16989. if (this._target.markAsDirty) {
  16990. this._target.markAsDirty(this.targetProperty);
  16991. }
  16992. if (!returnValue) {
  16993. this._stopped = true;
  16994. }
  16995. return returnValue;
  16996. };
  16997. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16998. get: function () {
  16999. return Animation._ANIMATIONTYPE_FLOAT;
  17000. },
  17001. enumerable: true,
  17002. configurable: true
  17003. });
  17004. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  17005. get: function () {
  17006. return Animation._ANIMATIONTYPE_VECTOR3;
  17007. },
  17008. enumerable: true,
  17009. configurable: true
  17010. });
  17011. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  17012. get: function () {
  17013. return Animation._ANIMATIONTYPE_VECTOR2;
  17014. },
  17015. enumerable: true,
  17016. configurable: true
  17017. });
  17018. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  17019. get: function () {
  17020. return Animation._ANIMATIONTYPE_QUATERNION;
  17021. },
  17022. enumerable: true,
  17023. configurable: true
  17024. });
  17025. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  17026. get: function () {
  17027. return Animation._ANIMATIONTYPE_MATRIX;
  17028. },
  17029. enumerable: true,
  17030. configurable: true
  17031. });
  17032. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  17033. get: function () {
  17034. return Animation._ANIMATIONTYPE_COLOR3;
  17035. },
  17036. enumerable: true,
  17037. configurable: true
  17038. });
  17039. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  17040. get: function () {
  17041. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  17042. },
  17043. enumerable: true,
  17044. configurable: true
  17045. });
  17046. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  17047. get: function () {
  17048. return Animation._ANIMATIONLOOPMODE_CYCLE;
  17049. },
  17050. enumerable: true,
  17051. configurable: true
  17052. });
  17053. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  17054. get: function () {
  17055. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  17056. },
  17057. enumerable: true,
  17058. configurable: true
  17059. });
  17060. // Statics
  17061. Animation._ANIMATIONTYPE_FLOAT = 0;
  17062. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  17063. Animation._ANIMATIONTYPE_QUATERNION = 2;
  17064. Animation._ANIMATIONTYPE_MATRIX = 3;
  17065. Animation._ANIMATIONTYPE_COLOR3 = 4;
  17066. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  17067. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  17068. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  17069. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  17070. return Animation;
  17071. })();
  17072. BABYLON.Animation = Animation;
  17073. })(BABYLON || (BABYLON = {}));
  17074. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  17075. (function (BABYLON) {
  17076. var Animatable = (function () {
  17077. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  17078. if (fromFrame === void 0) { fromFrame = 0; }
  17079. if (toFrame === void 0) { toFrame = 100; }
  17080. if (loopAnimation === void 0) { loopAnimation = false; }
  17081. if (speedRatio === void 0) { speedRatio = 1.0; }
  17082. this.target = target;
  17083. this.fromFrame = fromFrame;
  17084. this.toFrame = toFrame;
  17085. this.loopAnimation = loopAnimation;
  17086. this.speedRatio = speedRatio;
  17087. this.onAnimationEnd = onAnimationEnd;
  17088. this._animations = new Array();
  17089. this._paused = false;
  17090. this.animationStarted = false;
  17091. if (animations) {
  17092. this.appendAnimations(target, animations);
  17093. }
  17094. this._scene = scene;
  17095. scene._activeAnimatables.push(this);
  17096. }
  17097. // Methods
  17098. Animatable.prototype.appendAnimations = function (target, animations) {
  17099. for (var index = 0; index < animations.length; index++) {
  17100. var animation = animations[index];
  17101. animation._target = target;
  17102. this._animations.push(animation);
  17103. }
  17104. };
  17105. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  17106. var animations = this._animations;
  17107. for (var index = 0; index < animations.length; index++) {
  17108. if (animations[index].targetProperty === property) {
  17109. return animations[index];
  17110. }
  17111. }
  17112. return null;
  17113. };
  17114. Animatable.prototype.pause = function () {
  17115. if (this._paused) {
  17116. return;
  17117. }
  17118. this._paused = true;
  17119. };
  17120. Animatable.prototype.restart = function () {
  17121. this._paused = false;
  17122. };
  17123. Animatable.prototype.stop = function () {
  17124. var index = this._scene._activeAnimatables.indexOf(this);
  17125. if (index > -1) {
  17126. this._scene._activeAnimatables.splice(index, 1);
  17127. }
  17128. if (this.onAnimationEnd) {
  17129. this.onAnimationEnd();
  17130. }
  17131. };
  17132. Animatable.prototype._animate = function (delay) {
  17133. if (this._paused) {
  17134. if (!this._pausedDelay) {
  17135. this._pausedDelay = delay;
  17136. }
  17137. return true;
  17138. }
  17139. if (!this._localDelayOffset) {
  17140. this._localDelayOffset = delay;
  17141. }
  17142. else if (this._pausedDelay) {
  17143. this._localDelayOffset += delay - this._pausedDelay;
  17144. this._pausedDelay = null;
  17145. }
  17146. // Animating
  17147. var running = false;
  17148. var animations = this._animations;
  17149. for (var index = 0; index < animations.length; index++) {
  17150. var animation = animations[index];
  17151. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  17152. running = running || isRunning;
  17153. }
  17154. if (!running) {
  17155. // Remove from active animatables
  17156. index = this._scene._activeAnimatables.indexOf(this);
  17157. this._scene._activeAnimatables.splice(index, 1);
  17158. }
  17159. if (!running && this.onAnimationEnd) {
  17160. this.onAnimationEnd();
  17161. }
  17162. return running;
  17163. };
  17164. return Animatable;
  17165. })();
  17166. BABYLON.Animatable = Animatable;
  17167. })(BABYLON || (BABYLON = {}));
  17168. //# sourceMappingURL=babylon.animatable.js.map
  17169. var BABYLON;
  17170. (function (BABYLON) {
  17171. var EasingFunction = (function () {
  17172. function EasingFunction() {
  17173. // Properties
  17174. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  17175. }
  17176. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  17177. get: function () {
  17178. return EasingFunction._EASINGMODE_EASEIN;
  17179. },
  17180. enumerable: true,
  17181. configurable: true
  17182. });
  17183. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  17184. get: function () {
  17185. return EasingFunction._EASINGMODE_EASEOUT;
  17186. },
  17187. enumerable: true,
  17188. configurable: true
  17189. });
  17190. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  17191. get: function () {
  17192. return EasingFunction._EASINGMODE_EASEINOUT;
  17193. },
  17194. enumerable: true,
  17195. configurable: true
  17196. });
  17197. EasingFunction.prototype.setEasingMode = function (easingMode) {
  17198. var n = Math.min(Math.max(easingMode, 0), 2);
  17199. this._easingMode = n;
  17200. };
  17201. EasingFunction.prototype.getEasingMode = function () {
  17202. return this._easingMode;
  17203. };
  17204. EasingFunction.prototype.easeInCore = function (gradient) {
  17205. throw new Error('You must implement this method');
  17206. };
  17207. EasingFunction.prototype.ease = function (gradient) {
  17208. switch (this._easingMode) {
  17209. case EasingFunction.EASINGMODE_EASEIN:
  17210. return this.easeInCore(gradient);
  17211. case EasingFunction.EASINGMODE_EASEOUT:
  17212. return (1 - this.easeInCore(1 - gradient));
  17213. }
  17214. if (gradient >= 0.5) {
  17215. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  17216. }
  17217. return (this.easeInCore(gradient * 2) * 0.5);
  17218. };
  17219. //Statics
  17220. EasingFunction._EASINGMODE_EASEIN = 0;
  17221. EasingFunction._EASINGMODE_EASEOUT = 1;
  17222. EasingFunction._EASINGMODE_EASEINOUT = 2;
  17223. return EasingFunction;
  17224. })();
  17225. BABYLON.EasingFunction = EasingFunction;
  17226. var CircleEase = (function (_super) {
  17227. __extends(CircleEase, _super);
  17228. function CircleEase() {
  17229. _super.apply(this, arguments);
  17230. }
  17231. CircleEase.prototype.easeInCore = function (gradient) {
  17232. gradient = Math.max(0, Math.min(1, gradient));
  17233. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  17234. };
  17235. return CircleEase;
  17236. })(EasingFunction);
  17237. BABYLON.CircleEase = CircleEase;
  17238. var BackEase = (function (_super) {
  17239. __extends(BackEase, _super);
  17240. function BackEase(amplitude) {
  17241. if (amplitude === void 0) { amplitude = 1; }
  17242. _super.call(this);
  17243. this.amplitude = amplitude;
  17244. }
  17245. BackEase.prototype.easeInCore = function (gradient) {
  17246. var num = Math.max(0, this.amplitude);
  17247. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  17248. };
  17249. return BackEase;
  17250. })(EasingFunction);
  17251. BABYLON.BackEase = BackEase;
  17252. var BounceEase = (function (_super) {
  17253. __extends(BounceEase, _super);
  17254. function BounceEase(bounces, bounciness) {
  17255. if (bounces === void 0) { bounces = 3; }
  17256. if (bounciness === void 0) { bounciness = 2; }
  17257. _super.call(this);
  17258. this.bounces = bounces;
  17259. this.bounciness = bounciness;
  17260. }
  17261. BounceEase.prototype.easeInCore = function (gradient) {
  17262. var y = Math.max(0.0, this.bounces);
  17263. var bounciness = this.bounciness;
  17264. if (bounciness <= 1.0) {
  17265. bounciness = 1.001;
  17266. }
  17267. var num9 = Math.pow(bounciness, y);
  17268. var num5 = 1.0 - bounciness;
  17269. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  17270. var num15 = gradient * num4;
  17271. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  17272. var num3 = Math.floor(num65);
  17273. var num13 = num3 + 1.0;
  17274. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  17275. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  17276. var num7 = (num8 + num12) * 0.5;
  17277. var num6 = gradient - num7;
  17278. var num2 = num7 - num8;
  17279. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17280. };
  17281. return BounceEase;
  17282. })(EasingFunction);
  17283. BABYLON.BounceEase = BounceEase;
  17284. var CubicEase = (function (_super) {
  17285. __extends(CubicEase, _super);
  17286. function CubicEase() {
  17287. _super.apply(this, arguments);
  17288. }
  17289. CubicEase.prototype.easeInCore = function (gradient) {
  17290. return (gradient * gradient * gradient);
  17291. };
  17292. return CubicEase;
  17293. })(EasingFunction);
  17294. BABYLON.CubicEase = CubicEase;
  17295. var ElasticEase = (function (_super) {
  17296. __extends(ElasticEase, _super);
  17297. function ElasticEase(oscillations, springiness) {
  17298. if (oscillations === void 0) { oscillations = 3; }
  17299. if (springiness === void 0) { springiness = 3; }
  17300. _super.call(this);
  17301. this.oscillations = oscillations;
  17302. this.springiness = springiness;
  17303. }
  17304. ElasticEase.prototype.easeInCore = function (gradient) {
  17305. var num2;
  17306. var num3 = Math.max(0.0, this.oscillations);
  17307. var num = Math.max(0.0, this.springiness);
  17308. if (num == 0) {
  17309. num2 = gradient;
  17310. }
  17311. else {
  17312. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17313. }
  17314. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17315. };
  17316. return ElasticEase;
  17317. })(EasingFunction);
  17318. BABYLON.ElasticEase = ElasticEase;
  17319. var ExponentialEase = (function (_super) {
  17320. __extends(ExponentialEase, _super);
  17321. function ExponentialEase(exponent) {
  17322. if (exponent === void 0) { exponent = 2; }
  17323. _super.call(this);
  17324. this.exponent = exponent;
  17325. }
  17326. ExponentialEase.prototype.easeInCore = function (gradient) {
  17327. if (this.exponent <= 0) {
  17328. return gradient;
  17329. }
  17330. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17331. };
  17332. return ExponentialEase;
  17333. })(EasingFunction);
  17334. BABYLON.ExponentialEase = ExponentialEase;
  17335. var PowerEase = (function (_super) {
  17336. __extends(PowerEase, _super);
  17337. function PowerEase(power) {
  17338. if (power === void 0) { power = 2; }
  17339. _super.call(this);
  17340. this.power = power;
  17341. }
  17342. PowerEase.prototype.easeInCore = function (gradient) {
  17343. var y = Math.max(0.0, this.power);
  17344. return Math.pow(gradient, y);
  17345. };
  17346. return PowerEase;
  17347. })(EasingFunction);
  17348. BABYLON.PowerEase = PowerEase;
  17349. var QuadraticEase = (function (_super) {
  17350. __extends(QuadraticEase, _super);
  17351. function QuadraticEase() {
  17352. _super.apply(this, arguments);
  17353. }
  17354. QuadraticEase.prototype.easeInCore = function (gradient) {
  17355. return (gradient * gradient);
  17356. };
  17357. return QuadraticEase;
  17358. })(EasingFunction);
  17359. BABYLON.QuadraticEase = QuadraticEase;
  17360. var QuarticEase = (function (_super) {
  17361. __extends(QuarticEase, _super);
  17362. function QuarticEase() {
  17363. _super.apply(this, arguments);
  17364. }
  17365. QuarticEase.prototype.easeInCore = function (gradient) {
  17366. return (gradient * gradient * gradient * gradient);
  17367. };
  17368. return QuarticEase;
  17369. })(EasingFunction);
  17370. BABYLON.QuarticEase = QuarticEase;
  17371. var QuinticEase = (function (_super) {
  17372. __extends(QuinticEase, _super);
  17373. function QuinticEase() {
  17374. _super.apply(this, arguments);
  17375. }
  17376. QuinticEase.prototype.easeInCore = function (gradient) {
  17377. return (gradient * gradient * gradient * gradient * gradient);
  17378. };
  17379. return QuinticEase;
  17380. })(EasingFunction);
  17381. BABYLON.QuinticEase = QuinticEase;
  17382. var SineEase = (function (_super) {
  17383. __extends(SineEase, _super);
  17384. function SineEase() {
  17385. _super.apply(this, arguments);
  17386. }
  17387. SineEase.prototype.easeInCore = function (gradient) {
  17388. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17389. };
  17390. return SineEase;
  17391. })(EasingFunction);
  17392. BABYLON.SineEase = SineEase;
  17393. var BezierCurveEase = (function (_super) {
  17394. __extends(BezierCurveEase, _super);
  17395. function BezierCurveEase(x1, y1, x2, y2) {
  17396. if (x1 === void 0) { x1 = 0; }
  17397. if (y1 === void 0) { y1 = 0; }
  17398. if (x2 === void 0) { x2 = 1; }
  17399. if (y2 === void 0) { y2 = 1; }
  17400. _super.call(this);
  17401. this.x1 = x1;
  17402. this.y1 = y1;
  17403. this.x2 = x2;
  17404. this.y2 = y2;
  17405. }
  17406. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17407. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17408. };
  17409. return BezierCurveEase;
  17410. })(EasingFunction);
  17411. BABYLON.BezierCurveEase = BezierCurveEase;
  17412. })(BABYLON || (BABYLON = {}));
  17413. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17414. (function (BABYLON) {
  17415. var Octree = (function () {
  17416. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17417. if (maxDepth === void 0) { maxDepth = 2; }
  17418. this.maxDepth = maxDepth;
  17419. this.dynamicContent = new Array();
  17420. this._maxBlockCapacity = maxBlockCapacity || 64;
  17421. this._selectionContent = new BABYLON.SmartArray(1024);
  17422. this._creationFunc = creationFunc;
  17423. }
  17424. // Methods
  17425. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17426. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17427. };
  17428. Octree.prototype.addMesh = function (entry) {
  17429. for (var index = 0; index < this.blocks.length; index++) {
  17430. var block = this.blocks[index];
  17431. block.addEntry(entry);
  17432. }
  17433. };
  17434. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17435. this._selectionContent.reset();
  17436. for (var index = 0; index < this.blocks.length; index++) {
  17437. var block = this.blocks[index];
  17438. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17439. }
  17440. if (allowDuplicate) {
  17441. this._selectionContent.concat(this.dynamicContent);
  17442. }
  17443. else {
  17444. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17445. }
  17446. return this._selectionContent;
  17447. };
  17448. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17449. this._selectionContent.reset();
  17450. for (var index = 0; index < this.blocks.length; index++) {
  17451. var block = this.blocks[index];
  17452. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17453. }
  17454. if (allowDuplicate) {
  17455. this._selectionContent.concat(this.dynamicContent);
  17456. }
  17457. else {
  17458. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17459. }
  17460. return this._selectionContent;
  17461. };
  17462. Octree.prototype.intersectsRay = function (ray) {
  17463. this._selectionContent.reset();
  17464. for (var index = 0; index < this.blocks.length; index++) {
  17465. var block = this.blocks[index];
  17466. block.intersectsRay(ray, this._selectionContent);
  17467. }
  17468. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17469. return this._selectionContent;
  17470. };
  17471. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17472. target.blocks = new Array();
  17473. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17474. for (var x = 0; x < 2; x++) {
  17475. for (var y = 0; y < 2; y++) {
  17476. for (var z = 0; z < 2; z++) {
  17477. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17478. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17479. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17480. block.addEntries(entries);
  17481. target.blocks.push(block);
  17482. }
  17483. }
  17484. }
  17485. };
  17486. Octree.CreationFuncForMeshes = function (entry, block) {
  17487. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17488. block.entries.push(entry);
  17489. }
  17490. };
  17491. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17492. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17493. block.entries.push(entry);
  17494. }
  17495. };
  17496. return Octree;
  17497. })();
  17498. BABYLON.Octree = Octree;
  17499. })(BABYLON || (BABYLON = {}));
  17500. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17501. (function (BABYLON) {
  17502. var OctreeBlock = (function () {
  17503. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17504. this.entries = new Array();
  17505. this._boundingVectors = new Array();
  17506. this._capacity = capacity;
  17507. this._depth = depth;
  17508. this._maxDepth = maxDepth;
  17509. this._creationFunc = creationFunc;
  17510. this._minPoint = minPoint;
  17511. this._maxPoint = maxPoint;
  17512. this._boundingVectors.push(minPoint.clone());
  17513. this._boundingVectors.push(maxPoint.clone());
  17514. this._boundingVectors.push(minPoint.clone());
  17515. this._boundingVectors[2].x = maxPoint.x;
  17516. this._boundingVectors.push(minPoint.clone());
  17517. this._boundingVectors[3].y = maxPoint.y;
  17518. this._boundingVectors.push(minPoint.clone());
  17519. this._boundingVectors[4].z = maxPoint.z;
  17520. this._boundingVectors.push(maxPoint.clone());
  17521. this._boundingVectors[5].z = minPoint.z;
  17522. this._boundingVectors.push(maxPoint.clone());
  17523. this._boundingVectors[6].x = minPoint.x;
  17524. this._boundingVectors.push(maxPoint.clone());
  17525. this._boundingVectors[7].y = minPoint.y;
  17526. }
  17527. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17528. // Property
  17529. get: function () {
  17530. return this._capacity;
  17531. },
  17532. enumerable: true,
  17533. configurable: true
  17534. });
  17535. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17536. get: function () {
  17537. return this._minPoint;
  17538. },
  17539. enumerable: true,
  17540. configurable: true
  17541. });
  17542. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17543. get: function () {
  17544. return this._maxPoint;
  17545. },
  17546. enumerable: true,
  17547. configurable: true
  17548. });
  17549. // Methods
  17550. OctreeBlock.prototype.addEntry = function (entry) {
  17551. if (this.blocks) {
  17552. for (var index = 0; index < this.blocks.length; index++) {
  17553. var block = this.blocks[index];
  17554. block.addEntry(entry);
  17555. }
  17556. return;
  17557. }
  17558. this._creationFunc(entry, this);
  17559. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17560. this.createInnerBlocks();
  17561. }
  17562. };
  17563. OctreeBlock.prototype.addEntries = function (entries) {
  17564. for (var index = 0; index < entries.length; index++) {
  17565. var mesh = entries[index];
  17566. this.addEntry(mesh);
  17567. }
  17568. };
  17569. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17570. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17571. if (this.blocks) {
  17572. for (var index = 0; index < this.blocks.length; index++) {
  17573. var block = this.blocks[index];
  17574. block.select(frustumPlanes, selection, allowDuplicate);
  17575. }
  17576. return;
  17577. }
  17578. if (allowDuplicate) {
  17579. selection.concat(this.entries);
  17580. }
  17581. else {
  17582. selection.concatWithNoDuplicate(this.entries);
  17583. }
  17584. }
  17585. };
  17586. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17587. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17588. if (this.blocks) {
  17589. for (var index = 0; index < this.blocks.length; index++) {
  17590. var block = this.blocks[index];
  17591. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17592. }
  17593. return;
  17594. }
  17595. if (allowDuplicate) {
  17596. selection.concat(this.entries);
  17597. }
  17598. else {
  17599. selection.concatWithNoDuplicate(this.entries);
  17600. }
  17601. }
  17602. };
  17603. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17604. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17605. if (this.blocks) {
  17606. for (var index = 0; index < this.blocks.length; index++) {
  17607. var block = this.blocks[index];
  17608. block.intersectsRay(ray, selection);
  17609. }
  17610. return;
  17611. }
  17612. selection.concatWithNoDuplicate(this.entries);
  17613. }
  17614. };
  17615. OctreeBlock.prototype.createInnerBlocks = function () {
  17616. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17617. };
  17618. return OctreeBlock;
  17619. })();
  17620. BABYLON.OctreeBlock = OctreeBlock;
  17621. })(BABYLON || (BABYLON = {}));
  17622. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17623. (function (BABYLON) {
  17624. var Bone = (function () {
  17625. function Bone(name, skeleton, parentBone, matrix) {
  17626. this.name = name;
  17627. this.children = new Array();
  17628. this.animations = new Array();
  17629. this._worldTransform = new BABYLON.Matrix();
  17630. this._absoluteTransform = new BABYLON.Matrix();
  17631. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17632. this._skeleton = skeleton;
  17633. this._matrix = matrix;
  17634. this._baseMatrix = matrix;
  17635. skeleton.bones.push(this);
  17636. if (parentBone) {
  17637. this._parent = parentBone;
  17638. parentBone.children.push(this);
  17639. }
  17640. else {
  17641. this._parent = null;
  17642. }
  17643. this._updateDifferenceMatrix();
  17644. }
  17645. // Members
  17646. Bone.prototype.getParent = function () {
  17647. return this._parent;
  17648. };
  17649. Bone.prototype.getLocalMatrix = function () {
  17650. return this._matrix;
  17651. };
  17652. Bone.prototype.getBaseMatrix = function () {
  17653. return this._baseMatrix;
  17654. };
  17655. Bone.prototype.getWorldMatrix = function () {
  17656. return this._worldTransform;
  17657. };
  17658. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17659. return this._invertedAbsoluteTransform;
  17660. };
  17661. Bone.prototype.getAbsoluteMatrix = function () {
  17662. var matrix = this._matrix.clone();
  17663. var parent = this._parent;
  17664. while (parent) {
  17665. matrix = matrix.multiply(parent.getLocalMatrix());
  17666. parent = parent.getParent();
  17667. }
  17668. return matrix;
  17669. };
  17670. // Methods
  17671. Bone.prototype.updateMatrix = function (matrix) {
  17672. this._matrix = matrix;
  17673. this._skeleton._markAsDirty();
  17674. this._updateDifferenceMatrix();
  17675. };
  17676. Bone.prototype._updateDifferenceMatrix = function () {
  17677. if (this._parent) {
  17678. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17679. }
  17680. else {
  17681. this._absoluteTransform.copyFrom(this._matrix);
  17682. }
  17683. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17684. for (var index = 0; index < this.children.length; index++) {
  17685. this.children[index]._updateDifferenceMatrix();
  17686. }
  17687. };
  17688. Bone.prototype.markAsDirty = function () {
  17689. this._skeleton._markAsDirty();
  17690. };
  17691. return Bone;
  17692. })();
  17693. BABYLON.Bone = Bone;
  17694. })(BABYLON || (BABYLON = {}));
  17695. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17696. (function (BABYLON) {
  17697. var Skeleton = (function () {
  17698. function Skeleton(name, id, scene) {
  17699. this.name = name;
  17700. this.id = id;
  17701. this.bones = new Array();
  17702. this._isDirty = true;
  17703. this._identity = BABYLON.Matrix.Identity();
  17704. this.bones = [];
  17705. this._scene = scene;
  17706. scene.skeletons.push(this);
  17707. this.prepare();
  17708. //make sure it will recalculate the matrix next time prepare is called.
  17709. this._isDirty = true;
  17710. }
  17711. // Members
  17712. Skeleton.prototype.getTransformMatrices = function () {
  17713. return this._transformMatrices;
  17714. };
  17715. // Methods
  17716. Skeleton.prototype._markAsDirty = function () {
  17717. this._isDirty = true;
  17718. };
  17719. Skeleton.prototype.prepare = function () {
  17720. if (!this._isDirty) {
  17721. return;
  17722. }
  17723. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17724. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17725. }
  17726. for (var index = 0; index < this.bones.length; index++) {
  17727. var bone = this.bones[index];
  17728. var parentBone = bone.getParent();
  17729. if (parentBone) {
  17730. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17731. }
  17732. else {
  17733. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17734. }
  17735. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17736. }
  17737. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17738. this._isDirty = false;
  17739. this._scene._activeBones += this.bones.length;
  17740. };
  17741. Skeleton.prototype.getAnimatables = function () {
  17742. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17743. this._animatables = [];
  17744. for (var index = 0; index < this.bones.length; index++) {
  17745. this._animatables.push(this.bones[index]);
  17746. }
  17747. }
  17748. return this._animatables;
  17749. };
  17750. Skeleton.prototype.clone = function (name, id) {
  17751. var result = new Skeleton(name, id || name, this._scene);
  17752. for (var index = 0; index < this.bones.length; index++) {
  17753. var source = this.bones[index];
  17754. var parentBone = null;
  17755. if (source.getParent()) {
  17756. var parentIndex = this.bones.indexOf(source.getParent());
  17757. parentBone = result.bones[parentIndex];
  17758. }
  17759. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17760. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17761. }
  17762. return result;
  17763. };
  17764. return Skeleton;
  17765. })();
  17766. BABYLON.Skeleton = Skeleton;
  17767. })(BABYLON || (BABYLON = {}));
  17768. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17769. (function (BABYLON) {
  17770. var PostProcess = (function () {
  17771. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17772. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17773. this.name = name;
  17774. this.width = -1;
  17775. this.height = -1;
  17776. this._reusable = false;
  17777. this._textures = new BABYLON.SmartArray(2);
  17778. this._currentRenderTextureInd = 0;
  17779. if (camera != null) {
  17780. this._camera = camera;
  17781. this._scene = camera.getScene();
  17782. camera.attachPostProcess(this);
  17783. this._engine = this._scene.getEngine();
  17784. }
  17785. else {
  17786. this._engine = engine;
  17787. }
  17788. this._renderRatio = ratio;
  17789. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17790. this._reusable = reusable || false;
  17791. samplers = samplers || [];
  17792. samplers.push("textureSampler");
  17793. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17794. }
  17795. PostProcess.prototype.isReusable = function () {
  17796. return this._reusable;
  17797. };
  17798. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17799. camera = camera || this._camera;
  17800. var scene = camera.getScene();
  17801. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17802. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17803. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17804. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17805. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17806. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17807. if (this._textures.length > 0) {
  17808. for (var i = 0; i < this._textures.length; i++) {
  17809. this._engine._releaseTexture(this._textures.data[i]);
  17810. }
  17811. this._textures.reset();
  17812. }
  17813. this.width = desiredWidth;
  17814. this.height = desiredHeight;
  17815. 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 }));
  17816. if (this._reusable) {
  17817. 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 }));
  17818. }
  17819. if (this.onSizeChanged) {
  17820. this.onSizeChanged();
  17821. }
  17822. }
  17823. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17824. if (this.onActivate) {
  17825. this.onActivate(camera);
  17826. }
  17827. // Clear
  17828. if (this.clearColor) {
  17829. this._engine.clear(this.clearColor, true, true);
  17830. }
  17831. else {
  17832. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17833. }
  17834. if (this._reusable) {
  17835. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17836. }
  17837. };
  17838. PostProcess.prototype.apply = function () {
  17839. // Check
  17840. if (!this._effect.isReady())
  17841. return null;
  17842. // States
  17843. this._engine.enableEffect(this._effect);
  17844. this._engine.setState(false);
  17845. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17846. this._engine.setDepthBuffer(false);
  17847. this._engine.setDepthWrite(false);
  17848. // Texture
  17849. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17850. // Parameters
  17851. if (this.onApply) {
  17852. this.onApply(this._effect);
  17853. }
  17854. return this._effect;
  17855. };
  17856. PostProcess.prototype.dispose = function (camera) {
  17857. camera = camera || this._camera;
  17858. if (this._textures.length > 0) {
  17859. for (var i = 0; i < this._textures.length; i++) {
  17860. this._engine._releaseTexture(this._textures.data[i]);
  17861. }
  17862. this._textures.reset();
  17863. }
  17864. if (!camera) {
  17865. return;
  17866. }
  17867. camera.detachPostProcess(this);
  17868. var index = camera._postProcesses.indexOf(this);
  17869. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17870. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17871. }
  17872. };
  17873. return PostProcess;
  17874. })();
  17875. BABYLON.PostProcess = PostProcess;
  17876. })(BABYLON || (BABYLON = {}));
  17877. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17878. (function (BABYLON) {
  17879. var PostProcessManager = (function () {
  17880. function PostProcessManager(scene) {
  17881. this._vertexDeclaration = [2];
  17882. this._vertexStrideSize = 2 * 4;
  17883. this._scene = scene;
  17884. }
  17885. PostProcessManager.prototype._prepareBuffers = function () {
  17886. if (this._vertexBuffer) {
  17887. return;
  17888. }
  17889. // VBO
  17890. var vertices = [];
  17891. vertices.push(1, 1);
  17892. vertices.push(-1, 1);
  17893. vertices.push(-1, -1);
  17894. vertices.push(1, -1);
  17895. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17896. // Indices
  17897. var indices = [];
  17898. indices.push(0);
  17899. indices.push(1);
  17900. indices.push(2);
  17901. indices.push(0);
  17902. indices.push(2);
  17903. indices.push(3);
  17904. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17905. };
  17906. // Methods
  17907. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17908. var postProcesses = this._scene.activeCamera._postProcesses;
  17909. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17910. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17911. return false;
  17912. }
  17913. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17914. return true;
  17915. };
  17916. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17917. var engine = this._scene.getEngine();
  17918. for (var index = 0; index < postProcesses.length; index++) {
  17919. if (index < postProcesses.length - 1) {
  17920. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17921. }
  17922. else {
  17923. if (targetTexture) {
  17924. engine.bindFramebuffer(targetTexture);
  17925. }
  17926. else {
  17927. engine.restoreDefaultFramebuffer();
  17928. }
  17929. }
  17930. var pp = postProcesses[index];
  17931. var effect = pp.apply();
  17932. if (effect) {
  17933. if (pp.onBeforeRender) {
  17934. pp.onBeforeRender(effect);
  17935. }
  17936. // VBOs
  17937. this._prepareBuffers();
  17938. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17939. // Draw order
  17940. engine.draw(true, 0, 6);
  17941. }
  17942. }
  17943. // Restore depth buffer
  17944. engine.setDepthBuffer(true);
  17945. engine.setDepthWrite(true);
  17946. };
  17947. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17948. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17949. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17950. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17951. return;
  17952. }
  17953. var engine = this._scene.getEngine();
  17954. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17955. if (index < postProcessesTakenIndices.length - 1) {
  17956. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17957. }
  17958. else {
  17959. if (targetTexture) {
  17960. engine.bindFramebuffer(targetTexture);
  17961. }
  17962. else {
  17963. engine.restoreDefaultFramebuffer();
  17964. }
  17965. }
  17966. if (doNotPresent) {
  17967. break;
  17968. }
  17969. var pp = postProcesses[postProcessesTakenIndices[index]];
  17970. var effect = pp.apply();
  17971. if (effect) {
  17972. if (pp.onBeforeRender) {
  17973. pp.onBeforeRender(effect);
  17974. }
  17975. // VBOs
  17976. this._prepareBuffers();
  17977. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17978. // Draw order
  17979. engine.draw(true, 0, 6);
  17980. }
  17981. }
  17982. // Restore depth buffer
  17983. engine.setDepthBuffer(true);
  17984. engine.setDepthWrite(true);
  17985. };
  17986. PostProcessManager.prototype.dispose = function () {
  17987. if (this._vertexBuffer) {
  17988. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17989. this._vertexBuffer = null;
  17990. }
  17991. if (this._indexBuffer) {
  17992. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17993. this._indexBuffer = null;
  17994. }
  17995. };
  17996. return PostProcessManager;
  17997. })();
  17998. BABYLON.PostProcessManager = PostProcessManager;
  17999. })(BABYLON || (BABYLON = {}));
  18000. //# sourceMappingURL=babylon.postProcessManager.js.map
  18001. var BABYLON;
  18002. (function (BABYLON) {
  18003. var PassPostProcess = (function (_super) {
  18004. __extends(PassPostProcess, _super);
  18005. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18006. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  18007. }
  18008. return PassPostProcess;
  18009. })(BABYLON.PostProcess);
  18010. BABYLON.PassPostProcess = PassPostProcess;
  18011. })(BABYLON || (BABYLON = {}));
  18012. //# sourceMappingURL=babylon.passPostProcess.js.map
  18013. var BABYLON;
  18014. (function (BABYLON) {
  18015. var BlurPostProcess = (function (_super) {
  18016. __extends(BlurPostProcess, _super);
  18017. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  18018. var _this = this;
  18019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  18020. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  18021. this.direction = direction;
  18022. this.blurWidth = blurWidth;
  18023. this.onApply = function (effect) {
  18024. effect.setFloat2("screenSize", _this.width, _this.height);
  18025. effect.setVector2("direction", _this.direction);
  18026. effect.setFloat("blurWidth", _this.blurWidth);
  18027. };
  18028. }
  18029. return BlurPostProcess;
  18030. })(BABYLON.PostProcess);
  18031. BABYLON.BlurPostProcess = BlurPostProcess;
  18032. })(BABYLON || (BABYLON = {}));
  18033. //# sourceMappingURL=babylon.blurPostProcess.js.map
  18034. var BABYLON;
  18035. (function (BABYLON) {
  18036. var FilterPostProcess = (function (_super) {
  18037. __extends(FilterPostProcess, _super);
  18038. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  18039. var _this = this;
  18040. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  18041. this.kernelMatrix = kernelMatrix;
  18042. this.onApply = function (effect) {
  18043. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  18044. };
  18045. }
  18046. return FilterPostProcess;
  18047. })(BABYLON.PostProcess);
  18048. BABYLON.FilterPostProcess = FilterPostProcess;
  18049. })(BABYLON || (BABYLON = {}));
  18050. //# sourceMappingURL=babylon.filterPostProcess.js.map
  18051. var BABYLON;
  18052. (function (BABYLON) {
  18053. var RefractionPostProcess = (function (_super) {
  18054. __extends(RefractionPostProcess, _super);
  18055. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  18056. var _this = this;
  18057. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  18058. this.color = color;
  18059. this.depth = depth;
  18060. this.colorLevel = colorLevel;
  18061. this.onActivate = function (cam) {
  18062. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  18063. };
  18064. this.onApply = function (effect) {
  18065. effect.setColor3("baseColor", _this.color);
  18066. effect.setFloat("depth", _this.depth);
  18067. effect.setFloat("colorLevel", _this.colorLevel);
  18068. effect.setTexture("refractionSampler", _this._refRexture);
  18069. };
  18070. }
  18071. // Methods
  18072. RefractionPostProcess.prototype.dispose = function (camera) {
  18073. if (this._refRexture) {
  18074. this._refRexture.dispose();
  18075. }
  18076. _super.prototype.dispose.call(this, camera);
  18077. };
  18078. return RefractionPostProcess;
  18079. })(BABYLON.PostProcess);
  18080. BABYLON.RefractionPostProcess = RefractionPostProcess;
  18081. })(BABYLON || (BABYLON = {}));
  18082. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  18083. var BABYLON;
  18084. (function (BABYLON) {
  18085. var BlackAndWhitePostProcess = (function (_super) {
  18086. __extends(BlackAndWhitePostProcess, _super);
  18087. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18088. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  18089. }
  18090. return BlackAndWhitePostProcess;
  18091. })(BABYLON.PostProcess);
  18092. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  18093. })(BABYLON || (BABYLON = {}));
  18094. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  18095. var BABYLON;
  18096. (function (BABYLON) {
  18097. var ConvolutionPostProcess = (function (_super) {
  18098. __extends(ConvolutionPostProcess, _super);
  18099. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  18100. var _this = this;
  18101. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  18102. this.kernel = kernel;
  18103. this.onApply = function (effect) {
  18104. effect.setFloat2("screenSize", _this.width, _this.height);
  18105. effect.setArray("kernel", _this.kernel);
  18106. };
  18107. }
  18108. // Statics
  18109. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  18110. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  18111. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  18112. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  18113. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  18114. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  18115. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  18116. return ConvolutionPostProcess;
  18117. })(BABYLON.PostProcess);
  18118. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  18119. })(BABYLON || (BABYLON = {}));
  18120. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  18121. var BABYLON;
  18122. (function (BABYLON) {
  18123. var FxaaPostProcess = (function (_super) {
  18124. __extends(FxaaPostProcess, _super);
  18125. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18126. var _this = this;
  18127. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  18128. this.onSizeChanged = function () {
  18129. _this.texelWidth = 1.0 / _this.width;
  18130. _this.texelHeight = 1.0 / _this.height;
  18131. };
  18132. this.onApply = function (effect) {
  18133. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  18134. };
  18135. }
  18136. return FxaaPostProcess;
  18137. })(BABYLON.PostProcess);
  18138. BABYLON.FxaaPostProcess = FxaaPostProcess;
  18139. })(BABYLON || (BABYLON = {}));
  18140. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  18141. (function (BABYLON) {
  18142. var LensFlare = (function () {
  18143. function LensFlare(size, position, color, imgUrl, system) {
  18144. this.size = size;
  18145. this.position = position;
  18146. this.dispose = function () {
  18147. if (this.texture) {
  18148. this.texture.dispose();
  18149. }
  18150. // Remove from scene
  18151. var index = this._system.lensFlares.indexOf(this);
  18152. this._system.lensFlares.splice(index, 1);
  18153. };
  18154. this.color = color || new BABYLON.Color3(1, 1, 1);
  18155. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  18156. this._system = system;
  18157. system.lensFlares.push(this);
  18158. }
  18159. return LensFlare;
  18160. })();
  18161. BABYLON.LensFlare = LensFlare;
  18162. })(BABYLON || (BABYLON = {}));
  18163. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  18164. (function (BABYLON) {
  18165. var LensFlareSystem = (function () {
  18166. function LensFlareSystem(name, emitter, scene) {
  18167. this.name = name;
  18168. this.lensFlares = new Array();
  18169. this.borderLimit = 300;
  18170. this._vertexDeclaration = [2];
  18171. this._vertexStrideSize = 2 * 4;
  18172. this._isEnabled = true;
  18173. this._scene = scene;
  18174. this._emitter = emitter;
  18175. scene.lensFlareSystems.push(this);
  18176. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  18177. // VBO
  18178. var vertices = [];
  18179. vertices.push(1, 1);
  18180. vertices.push(-1, 1);
  18181. vertices.push(-1, -1);
  18182. vertices.push(1, -1);
  18183. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18184. // Indices
  18185. var indices = [];
  18186. indices.push(0);
  18187. indices.push(1);
  18188. indices.push(2);
  18189. indices.push(0);
  18190. indices.push(2);
  18191. indices.push(3);
  18192. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18193. // Effects
  18194. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  18195. }
  18196. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  18197. get: function () {
  18198. return this._isEnabled;
  18199. },
  18200. set: function (value) {
  18201. this._isEnabled = value;
  18202. },
  18203. enumerable: true,
  18204. configurable: true
  18205. });
  18206. LensFlareSystem.prototype.getScene = function () {
  18207. return this._scene;
  18208. };
  18209. LensFlareSystem.prototype.getEmitter = function () {
  18210. return this._emitter;
  18211. };
  18212. LensFlareSystem.prototype.getEmitterPosition = function () {
  18213. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  18214. };
  18215. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  18216. var position = this.getEmitterPosition();
  18217. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  18218. this._positionX = position.x;
  18219. this._positionY = position.y;
  18220. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  18221. if (position.z > 0) {
  18222. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  18223. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  18224. return true;
  18225. }
  18226. }
  18227. return false;
  18228. };
  18229. LensFlareSystem.prototype._isVisible = function () {
  18230. if (!this._isEnabled) {
  18231. return false;
  18232. }
  18233. var emitterPosition = this.getEmitterPosition();
  18234. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  18235. var distance = direction.length();
  18236. direction.normalize();
  18237. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  18238. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  18239. return !pickInfo.hit || pickInfo.distance > distance;
  18240. };
  18241. LensFlareSystem.prototype.render = function () {
  18242. if (!this._effect.isReady())
  18243. return false;
  18244. var engine = this._scene.getEngine();
  18245. var viewport = this._scene.activeCamera.viewport;
  18246. var globalViewport = viewport.toGlobal(engine);
  18247. // Position
  18248. if (!this.computeEffectivePosition(globalViewport)) {
  18249. return false;
  18250. }
  18251. // Visibility
  18252. if (!this._isVisible()) {
  18253. return false;
  18254. }
  18255. // Intensity
  18256. var awayX;
  18257. var awayY;
  18258. if (this._positionX < this.borderLimit + globalViewport.x) {
  18259. awayX = this.borderLimit + globalViewport.x - this._positionX;
  18260. }
  18261. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  18262. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  18263. }
  18264. else {
  18265. awayX = 0;
  18266. }
  18267. if (this._positionY < this.borderLimit + globalViewport.y) {
  18268. awayY = this.borderLimit + globalViewport.y - this._positionY;
  18269. }
  18270. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  18271. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  18272. }
  18273. else {
  18274. awayY = 0;
  18275. }
  18276. var away = (awayX > awayY) ? awayX : awayY;
  18277. if (away > this.borderLimit) {
  18278. away = this.borderLimit;
  18279. }
  18280. var intensity = 1.0 - (away / this.borderLimit);
  18281. if (intensity < 0) {
  18282. return false;
  18283. }
  18284. if (intensity > 1.0) {
  18285. intensity = 1.0;
  18286. }
  18287. // Position
  18288. var centerX = globalViewport.x + globalViewport.width / 2;
  18289. var centerY = globalViewport.y + globalViewport.height / 2;
  18290. var distX = centerX - this._positionX;
  18291. var distY = centerY - this._positionY;
  18292. // Effects
  18293. engine.enableEffect(this._effect);
  18294. engine.setState(false);
  18295. engine.setDepthBuffer(false);
  18296. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18297. // VBOs
  18298. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18299. for (var index = 0; index < this.lensFlares.length; index++) {
  18300. var flare = this.lensFlares[index];
  18301. var x = centerX - (distX * flare.position);
  18302. var y = centerY - (distY * flare.position);
  18303. var cw = flare.size;
  18304. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18305. var cx = 2 * (x / globalViewport.width) - 1.0;
  18306. var cy = 1.0 - 2 * (y / globalViewport.height);
  18307. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18308. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18309. // Texture
  18310. this._effect.setTexture("textureSampler", flare.texture);
  18311. // Color
  18312. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18313. // Draw order
  18314. engine.draw(true, 0, 6);
  18315. }
  18316. engine.setDepthBuffer(true);
  18317. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18318. return true;
  18319. };
  18320. LensFlareSystem.prototype.dispose = function () {
  18321. if (this._vertexBuffer) {
  18322. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18323. this._vertexBuffer = null;
  18324. }
  18325. if (this._indexBuffer) {
  18326. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18327. this._indexBuffer = null;
  18328. }
  18329. while (this.lensFlares.length) {
  18330. this.lensFlares[0].dispose();
  18331. }
  18332. // Remove from scene
  18333. var index = this._scene.lensFlareSystems.indexOf(this);
  18334. this._scene.lensFlareSystems.splice(index, 1);
  18335. };
  18336. return LensFlareSystem;
  18337. })();
  18338. BABYLON.LensFlareSystem = LensFlareSystem;
  18339. })(BABYLON || (BABYLON = {}));
  18340. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18341. (function (BABYLON) {
  18342. var IntersectionInfo = (function () {
  18343. function IntersectionInfo(bu, bv, distance) {
  18344. this.bu = bu;
  18345. this.bv = bv;
  18346. this.distance = distance;
  18347. this.faceId = 0;
  18348. this.subMeshId = 0;
  18349. }
  18350. return IntersectionInfo;
  18351. })();
  18352. BABYLON.IntersectionInfo = IntersectionInfo;
  18353. var PickingInfo = (function () {
  18354. function PickingInfo() {
  18355. this.hit = false;
  18356. this.distance = 0;
  18357. this.pickedPoint = null;
  18358. this.pickedMesh = null;
  18359. this.bu = 0;
  18360. this.bv = 0;
  18361. this.faceId = -1;
  18362. this.subMeshId = 0;
  18363. }
  18364. // Methods
  18365. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18366. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18367. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18368. return null;
  18369. }
  18370. var indices = this.pickedMesh.getIndices();
  18371. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18372. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18373. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18374. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18375. normal0 = normal0.scale(this.bu);
  18376. normal1 = normal1.scale(this.bv);
  18377. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18378. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18379. if (useWorldCoordinates) {
  18380. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18381. }
  18382. return result;
  18383. };
  18384. PickingInfo.prototype.getTextureCoordinates = function () {
  18385. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18386. return null;
  18387. }
  18388. var indices = this.pickedMesh.getIndices();
  18389. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18390. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18391. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18392. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18393. uv0 = uv0.scale(this.bu);
  18394. uv1 = uv1.scale(this.bv);
  18395. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18396. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18397. };
  18398. return PickingInfo;
  18399. })();
  18400. BABYLON.PickingInfo = PickingInfo;
  18401. })(BABYLON || (BABYLON = {}));
  18402. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18403. (function (BABYLON) {
  18404. var FilesInput = (function () {
  18405. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18406. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18407. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18408. this._engine = p_engine;
  18409. this._canvas = p_canvas;
  18410. this._currentScene = p_scene;
  18411. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18412. this._progressCallback = p_progressCallback;
  18413. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18414. this._textureLoadingCallback = p_textureLoadingCallback;
  18415. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18416. }
  18417. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18418. var _this = this;
  18419. if (p_elementToMonitor) {
  18420. this._elementToMonitor = p_elementToMonitor;
  18421. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18422. _this.drag(e);
  18423. }, false);
  18424. this._elementToMonitor.addEventListener("dragover", function (e) {
  18425. _this.drag(e);
  18426. }, false);
  18427. this._elementToMonitor.addEventListener("drop", function (e) {
  18428. _this.drop(e);
  18429. }, false);
  18430. }
  18431. };
  18432. FilesInput.prototype.renderFunction = function () {
  18433. if (this._additionnalRenderLoopLogicCallback) {
  18434. this._additionnalRenderLoopLogicCallback();
  18435. }
  18436. if (this._currentScene) {
  18437. if (this._textureLoadingCallback) {
  18438. var remaining = this._currentScene.getWaitingItemsCount();
  18439. if (remaining > 0) {
  18440. this._textureLoadingCallback(remaining);
  18441. }
  18442. }
  18443. this._currentScene.render();
  18444. }
  18445. };
  18446. FilesInput.prototype.drag = function (e) {
  18447. e.stopPropagation();
  18448. e.preventDefault();
  18449. };
  18450. FilesInput.prototype.drop = function (eventDrop) {
  18451. eventDrop.stopPropagation();
  18452. eventDrop.preventDefault();
  18453. this.loadFiles(eventDrop);
  18454. };
  18455. FilesInput.prototype.loadFiles = function (event) {
  18456. if (this._startingProcessingFilesCallback)
  18457. this._startingProcessingFilesCallback();
  18458. // Handling data transfer via drag'n'drop
  18459. if (event && event.dataTransfer && event.dataTransfer.files) {
  18460. this._filesToLoad = event.dataTransfer.files;
  18461. }
  18462. // Handling files from input files
  18463. if (event && event.target && event.target.files) {
  18464. this._filesToLoad = event.target.files;
  18465. }
  18466. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18467. for (var i = 0; i < this._filesToLoad.length; i++) {
  18468. switch (this._filesToLoad[i].type) {
  18469. case "image/jpeg":
  18470. case "image/png":
  18471. case "image/bmp":
  18472. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18473. break;
  18474. case "image/targa":
  18475. case "image/vnd.ms-dds":
  18476. case "audio/wav":
  18477. case "audio/x-wav":
  18478. case "audio/mp3":
  18479. case "audio/mpeg":
  18480. case "audio/mpeg3":
  18481. case "audio/x-mpeg-3":
  18482. case "audio/ogg":
  18483. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18484. break;
  18485. default:
  18486. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  18487. this._sceneFileToLoad = this._filesToLoad[i];
  18488. }
  18489. break;
  18490. }
  18491. }
  18492. this.reload();
  18493. }
  18494. };
  18495. FilesInput.prototype.reload = function () {
  18496. var _this = this;
  18497. var that = this;
  18498. // If a ".babylon" file has been provided
  18499. if (this._sceneFileToLoad) {
  18500. if (this._currentScene) {
  18501. this._engine.stopRenderLoop();
  18502. this._currentScene.dispose();
  18503. }
  18504. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18505. that._currentScene = newScene;
  18506. // Wait for textures and shaders to be ready
  18507. that._currentScene.executeWhenReady(function () {
  18508. // Attach camera to canvas inputs
  18509. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18510. that._currentScene.createDefaultCameraOrLight();
  18511. }
  18512. that._currentScene.activeCamera.attachControl(that._canvas);
  18513. if (that._sceneLoadedCallback) {
  18514. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18515. }
  18516. that._engine.runRenderLoop(function () {
  18517. that.renderFunction();
  18518. });
  18519. });
  18520. }, function (progress) {
  18521. if (_this._progressCallback) {
  18522. _this._progressCallback(progress);
  18523. }
  18524. });
  18525. }
  18526. else {
  18527. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18528. }
  18529. };
  18530. FilesInput.FilesTextures = new Array();
  18531. FilesInput.FilesToLoad = new Array();
  18532. return FilesInput;
  18533. })();
  18534. BABYLON.FilesInput = FilesInput;
  18535. })(BABYLON || (BABYLON = {}));
  18536. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18537. (function (BABYLON) {
  18538. var OimoJSPlugin = (function () {
  18539. function OimoJSPlugin() {
  18540. this._registeredMeshes = [];
  18541. /**
  18542. * Update the body position according to the mesh position
  18543. * @param mesh
  18544. */
  18545. this.updateBodyPosition = function (mesh) {
  18546. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18547. var registeredMesh = this._registeredMeshes[index];
  18548. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18549. var body = registeredMesh.body.body;
  18550. mesh.computeWorldMatrix(true);
  18551. var center = mesh.getBoundingInfo().boundingBox.center;
  18552. body.setPosition(center.x, center.y, center.z);
  18553. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18554. return;
  18555. }
  18556. // Case where the parent has been updated
  18557. if (registeredMesh.mesh.parent === mesh) {
  18558. mesh.computeWorldMatrix(true);
  18559. registeredMesh.mesh.computeWorldMatrix(true);
  18560. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18561. var absoluteRotation = mesh.rotation;
  18562. body = registeredMesh.body.body;
  18563. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18564. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18565. return;
  18566. }
  18567. }
  18568. };
  18569. }
  18570. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18571. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18572. };
  18573. OimoJSPlugin.prototype.initialize = function (iterations) {
  18574. this._world = new OIMO.World();
  18575. this._world.clear();
  18576. };
  18577. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18578. this._world.gravity = gravity;
  18579. };
  18580. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18581. var body = null;
  18582. this.unregisterMesh(mesh);
  18583. mesh.computeWorldMatrix(true);
  18584. var initialRotation = null;
  18585. if (mesh.rotationQuaternion) {
  18586. initialRotation = mesh.rotationQuaternion.clone();
  18587. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18588. mesh.computeWorldMatrix(true);
  18589. }
  18590. var bbox = mesh.getBoundingInfo().boundingBox;
  18591. // The delta between the mesh position and the mesh bounding box center
  18592. var deltaPosition = mesh.position.subtract(bbox.center);
  18593. // Transform delta position with the rotation
  18594. if (initialRotation) {
  18595. var m = new BABYLON.Matrix();
  18596. initialRotation.toRotationMatrix(m);
  18597. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18598. }
  18599. switch (impostor) {
  18600. case BABYLON.PhysicsEngine.SphereImpostor:
  18601. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18602. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18603. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18604. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18605. body = new OIMO.Body({
  18606. type: 'sphere',
  18607. size: [size],
  18608. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18609. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18610. move: options.mass != 0,
  18611. config: [options.mass, options.friction, options.restitution],
  18612. world: this._world
  18613. });
  18614. break;
  18615. case BABYLON.PhysicsEngine.PlaneImpostor:
  18616. case BABYLON.PhysicsEngine.CylinderImpostor:
  18617. case BABYLON.PhysicsEngine.BoxImpostor:
  18618. var min = bbox.minimumWorld;
  18619. var max = bbox.maximumWorld;
  18620. var box = max.subtract(min);
  18621. var sizeX = this._checkWithEpsilon(box.x);
  18622. var sizeY = this._checkWithEpsilon(box.y);
  18623. var sizeZ = this._checkWithEpsilon(box.z);
  18624. body = new OIMO.Body({
  18625. type: 'box',
  18626. size: [sizeX, sizeY, sizeZ],
  18627. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18628. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18629. move: options.mass != 0,
  18630. config: [options.mass, options.friction, options.restitution],
  18631. world: this._world
  18632. });
  18633. break;
  18634. }
  18635. //If quaternion was set as the rotation of the object
  18636. if (initialRotation) {
  18637. //We have to access the rigid body's properties to set the quaternion.
  18638. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18639. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18640. //update the internal rotation matrix
  18641. body.body.syncShapes();
  18642. }
  18643. this._registeredMeshes.push({
  18644. mesh: mesh,
  18645. body: body,
  18646. delta: deltaPosition
  18647. });
  18648. return body;
  18649. };
  18650. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18651. var types = [], sizes = [], positions = [], rotations = [];
  18652. var initialMesh = parts[0].mesh;
  18653. for (var index = 0; index < parts.length; index++) {
  18654. var part = parts[index];
  18655. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18656. types.push(bodyParameters.type);
  18657. sizes.push.apply(sizes, bodyParameters.size);
  18658. positions.push.apply(positions, bodyParameters.pos);
  18659. rotations.push.apply(rotations, bodyParameters.rot);
  18660. }
  18661. var body = new OIMO.Body({
  18662. type: types,
  18663. size: sizes,
  18664. pos: positions,
  18665. rot: rotations,
  18666. move: options.mass != 0,
  18667. config: [options.mass, options.friction, options.restitution],
  18668. world: this._world
  18669. });
  18670. this._registeredMeshes.push({
  18671. mesh: initialMesh,
  18672. body: body
  18673. });
  18674. return body;
  18675. };
  18676. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18677. var bodyParameters = null;
  18678. var mesh = part.mesh;
  18679. // We need the bounding box/sphere info to compute the physics body
  18680. mesh.computeWorldMatrix();
  18681. switch (part.impostor) {
  18682. case BABYLON.PhysicsEngine.SphereImpostor:
  18683. var bbox = mesh.getBoundingInfo().boundingBox;
  18684. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18685. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18686. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18687. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18688. bodyParameters = {
  18689. type: 'sphere',
  18690. /* bug with oimo : sphere needs 3 sizes in this case */
  18691. size: [size, -1, -1],
  18692. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18693. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18694. };
  18695. break;
  18696. case BABYLON.PhysicsEngine.PlaneImpostor:
  18697. case BABYLON.PhysicsEngine.BoxImpostor:
  18698. bbox = mesh.getBoundingInfo().boundingBox;
  18699. var min = bbox.minimumWorld;
  18700. var max = bbox.maximumWorld;
  18701. var box = max.subtract(min);
  18702. var sizeX = this._checkWithEpsilon(box.x);
  18703. var sizeY = this._checkWithEpsilon(box.y);
  18704. var sizeZ = this._checkWithEpsilon(box.z);
  18705. var relativePosition = mesh.position;
  18706. bodyParameters = {
  18707. type: 'box',
  18708. size: [sizeX, sizeY, sizeZ],
  18709. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18710. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18711. };
  18712. break;
  18713. }
  18714. return bodyParameters;
  18715. };
  18716. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18717. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18718. var registeredMesh = this._registeredMeshes[index];
  18719. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18720. if (registeredMesh.body) {
  18721. this._world.removeRigidBody(registeredMesh.body.body);
  18722. this._unbindBody(registeredMesh.body);
  18723. }
  18724. this._registeredMeshes.splice(index, 1);
  18725. return;
  18726. }
  18727. }
  18728. };
  18729. OimoJSPlugin.prototype._unbindBody = function (body) {
  18730. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18731. var registeredMesh = this._registeredMeshes[index];
  18732. if (registeredMesh.body === body) {
  18733. registeredMesh.body = null;
  18734. }
  18735. }
  18736. };
  18737. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18738. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18739. var registeredMesh = this._registeredMeshes[index];
  18740. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18741. // Get object mass to have a behaviour similar to cannon.js
  18742. var mass = registeredMesh.body.body.massInfo.mass;
  18743. // The force is scaled with the mass of object
  18744. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18745. return;
  18746. }
  18747. }
  18748. };
  18749. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18750. var body1 = null, body2 = null;
  18751. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18752. var registeredMesh = this._registeredMeshes[index];
  18753. if (registeredMesh.mesh === mesh1) {
  18754. body1 = registeredMesh.body.body;
  18755. }
  18756. else if (registeredMesh.mesh === mesh2) {
  18757. body2 = registeredMesh.body.body;
  18758. }
  18759. }
  18760. if (!body1 || !body2) {
  18761. return false;
  18762. }
  18763. if (!options) {
  18764. options = {};
  18765. }
  18766. new OIMO.Link({
  18767. type: options.type,
  18768. body1: body1,
  18769. body2: body2,
  18770. min: options.min,
  18771. max: options.max,
  18772. axe1: options.axe1,
  18773. axe2: options.axe2,
  18774. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18775. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18776. collision: options.collision,
  18777. spring: options.spring,
  18778. world: this._world
  18779. });
  18780. return true;
  18781. };
  18782. OimoJSPlugin.prototype.dispose = function () {
  18783. this._world.clear();
  18784. while (this._registeredMeshes.length) {
  18785. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18786. }
  18787. };
  18788. OimoJSPlugin.prototype.isSupported = function () {
  18789. return OIMO !== undefined;
  18790. };
  18791. OimoJSPlugin.prototype._getLastShape = function (body) {
  18792. var lastShape = body.shapes;
  18793. while (lastShape.next) {
  18794. lastShape = lastShape.next;
  18795. }
  18796. return lastShape;
  18797. };
  18798. OimoJSPlugin.prototype.runOneStep = function (time) {
  18799. this._world.step();
  18800. // Update the position of all registered meshes
  18801. var i = this._registeredMeshes.length;
  18802. var m;
  18803. while (i--) {
  18804. var body = this._registeredMeshes[i].body.body;
  18805. var mesh = this._registeredMeshes[i].mesh;
  18806. var delta = this._registeredMeshes[i].delta;
  18807. if (!body.sleeping) {
  18808. if (body.shapes.next) {
  18809. var parentShape = this._getLastShape(body);
  18810. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18811. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18812. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18813. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18814. if (!mesh.rotationQuaternion) {
  18815. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18816. }
  18817. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18818. mesh.computeWorldMatrix();
  18819. }
  18820. else {
  18821. m = body.getMatrix();
  18822. mtx = BABYLON.Matrix.FromArray(m);
  18823. // Body position
  18824. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18825. if (!delta) {
  18826. mesh.position.x = bodyX;
  18827. mesh.position.y = bodyY;
  18828. mesh.position.z = bodyZ;
  18829. }
  18830. else {
  18831. mesh.position.x = bodyX + delta.x;
  18832. mesh.position.y = bodyY + delta.y;
  18833. mesh.position.z = bodyZ + delta.z;
  18834. }
  18835. if (!mesh.rotationQuaternion) {
  18836. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18837. }
  18838. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18839. mesh.computeWorldMatrix();
  18840. }
  18841. }
  18842. }
  18843. };
  18844. return OimoJSPlugin;
  18845. })();
  18846. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18847. })(BABYLON || (BABYLON = {}));
  18848. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18849. (function (BABYLON) {
  18850. var PhysicsEngine = (function () {
  18851. function PhysicsEngine(plugin) {
  18852. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18853. }
  18854. PhysicsEngine.prototype._initialize = function (gravity) {
  18855. this._currentPlugin.initialize();
  18856. this._setGravity(gravity);
  18857. };
  18858. PhysicsEngine.prototype._runOneStep = function (delta) {
  18859. if (delta > 0.1) {
  18860. delta = 0.1;
  18861. }
  18862. else if (delta <= 0) {
  18863. delta = 1.0 / 60.0;
  18864. }
  18865. this._currentPlugin.runOneStep(delta);
  18866. };
  18867. PhysicsEngine.prototype._setGravity = function (gravity) {
  18868. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18869. this._currentPlugin.setGravity(this.gravity);
  18870. };
  18871. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18872. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18873. };
  18874. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18875. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18876. };
  18877. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18878. this._currentPlugin.unregisterMesh(mesh);
  18879. };
  18880. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18881. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18882. };
  18883. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18884. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18885. };
  18886. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18887. this._currentPlugin.updateBodyPosition(mesh);
  18888. };
  18889. PhysicsEngine.prototype.dispose = function () {
  18890. this._currentPlugin.dispose();
  18891. };
  18892. PhysicsEngine.prototype.isSupported = function () {
  18893. return this._currentPlugin.isSupported();
  18894. };
  18895. // Statics
  18896. PhysicsEngine.NoImpostor = 0;
  18897. PhysicsEngine.SphereImpostor = 1;
  18898. PhysicsEngine.BoxImpostor = 2;
  18899. PhysicsEngine.PlaneImpostor = 3;
  18900. PhysicsEngine.MeshImpostor = 4;
  18901. PhysicsEngine.CapsuleImpostor = 5;
  18902. PhysicsEngine.ConeImpostor = 6;
  18903. PhysicsEngine.CylinderImpostor = 7;
  18904. PhysicsEngine.ConvexHullImpostor = 8;
  18905. PhysicsEngine.Epsilon = 0.001;
  18906. return PhysicsEngine;
  18907. })();
  18908. BABYLON.PhysicsEngine = PhysicsEngine;
  18909. })(BABYLON || (BABYLON = {}));
  18910. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18911. (function (BABYLON) {
  18912. var serializeLight = function (light) {
  18913. var serializationObject = {};
  18914. serializationObject.name = light.name;
  18915. serializationObject.id = light.id;
  18916. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18917. if (light instanceof BABYLON.PointLight) {
  18918. serializationObject.type = 0;
  18919. serializationObject.position = light.position.asArray();
  18920. }
  18921. else if (light instanceof BABYLON.DirectionalLight) {
  18922. serializationObject.type = 1;
  18923. var directionalLight = light;
  18924. serializationObject.position = directionalLight.position.asArray();
  18925. serializationObject.direction = directionalLight.direction.asArray();
  18926. }
  18927. else if (light instanceof BABYLON.SpotLight) {
  18928. serializationObject.type = 2;
  18929. var spotLight = light;
  18930. serializationObject.position = spotLight.position.asArray();
  18931. serializationObject.direction = spotLight.position.asArray();
  18932. serializationObject.angle = spotLight.angle;
  18933. serializationObject.exponent = spotLight.exponent;
  18934. }
  18935. else if (light instanceof BABYLON.HemisphericLight) {
  18936. serializationObject.type = 3;
  18937. var hemisphericLight = light;
  18938. serializationObject.direction = hemisphericLight.direction.asArray();
  18939. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18940. }
  18941. if (light.intensity) {
  18942. serializationObject.intensity = light.intensity;
  18943. }
  18944. serializationObject.range = light.range;
  18945. serializationObject.diffuse = light.diffuse.asArray();
  18946. serializationObject.specular = light.specular.asArray();
  18947. return serializationObject;
  18948. };
  18949. var serializeFresnelParameter = function (fresnelParameter) {
  18950. var serializationObject = {};
  18951. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18952. serializationObject.leftColor = fresnelParameter.leftColor;
  18953. serializationObject.rightColor = fresnelParameter.rightColor;
  18954. serializationObject.bias = fresnelParameter.bias;
  18955. serializationObject.power = fresnelParameter.power;
  18956. return serializationObject;
  18957. };
  18958. var appendAnimations = function (source, destination) {
  18959. if (source.animations) {
  18960. destination.animations = [];
  18961. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18962. var animation = source.animations[animationIndex];
  18963. destination.animations.push(serializeAnimation(animation));
  18964. }
  18965. }
  18966. };
  18967. var serializeCamera = function (camera) {
  18968. var serializationObject = {};
  18969. serializationObject.name = camera.name;
  18970. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18971. serializationObject.id = camera.id;
  18972. serializationObject.position = camera.position.asArray();
  18973. // Parent
  18974. if (camera.parent) {
  18975. serializationObject.parentId = camera.parent.id;
  18976. }
  18977. serializationObject.fov = camera.fov;
  18978. serializationObject.minZ = camera.minZ;
  18979. serializationObject.maxZ = camera.maxZ;
  18980. serializationObject.inertia = camera.inertia;
  18981. //setting the type
  18982. if (camera instanceof BABYLON.FreeCamera) {
  18983. serializationObject.type = "FreeCamera";
  18984. }
  18985. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18986. serializationObject.type = "ArcRotateCamera";
  18987. }
  18988. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18989. serializationObject.type = "AnaglyphArcRotateCamera";
  18990. }
  18991. else if (camera instanceof BABYLON.GamepadCamera) {
  18992. serializationObject.type = "GamepadCamera";
  18993. }
  18994. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18995. serializationObject.type = "AnaglyphFreeCamera";
  18996. }
  18997. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18998. serializationObject.type = "DeviceOrientationCamera";
  18999. }
  19000. else if (camera instanceof BABYLON.FollowCamera) {
  19001. serializationObject.type = "FollowCamera";
  19002. }
  19003. else if (camera instanceof BABYLON.OculusCamera) {
  19004. serializationObject.type = "OculusCamera";
  19005. }
  19006. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  19007. serializationObject.type = "OculusGamepadCamera";
  19008. }
  19009. else if (camera instanceof BABYLON.TouchCamera) {
  19010. serializationObject.type = "TouchCamera";
  19011. }
  19012. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  19013. serializationObject.type = "VirtualJoysticksCamera";
  19014. }
  19015. else if (camera instanceof BABYLON.WebVRCamera) {
  19016. serializationObject.type = "WebVRCamera";
  19017. }
  19018. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  19019. serializationObject.type = "VRDeviceOrientationCamera";
  19020. }
  19021. //special properties of specific cameras
  19022. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  19023. var arcCamera = camera;
  19024. serializationObject.alpha = arcCamera.alpha;
  19025. serializationObject.beta = arcCamera.beta;
  19026. serializationObject.radius = arcCamera.radius;
  19027. if (arcCamera.target && arcCamera.target.id) {
  19028. serializationObject.lockedTargetId = arcCamera.target.id;
  19029. }
  19030. }
  19031. else if (camera instanceof BABYLON.FollowCamera) {
  19032. var followCam = camera;
  19033. serializationObject.radius = followCam.radius;
  19034. serializationObject.heightOffset = followCam.heightOffset;
  19035. serializationObject.rotationOffset = followCam.rotationOffset;
  19036. }
  19037. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  19038. //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.
  19039. if (camera['_eyeSpace'] !== undefined) {
  19040. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  19041. }
  19042. }
  19043. //general properties that not all cameras have. The [] is due to typescript's type safety
  19044. if (camera['speed'] !== undefined) {
  19045. serializationObject.speed = camera['speed'];
  19046. }
  19047. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  19048. serializationObject.target = camera['target'].asArray();
  19049. }
  19050. // Target
  19051. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  19052. serializationObject.rotation = camera['rotation'].asArray();
  19053. }
  19054. // Locked target
  19055. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  19056. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  19057. }
  19058. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  19059. serializationObject.applyGravity = camera['applyGravity'] || false;
  19060. if (camera['ellipsoid']) {
  19061. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  19062. }
  19063. // Animations
  19064. appendAnimations(camera, serializationObject);
  19065. // Layer mask
  19066. serializationObject.layerMask = camera.layerMask;
  19067. return serializationObject;
  19068. };
  19069. var serializeAnimation = function (animation) {
  19070. var serializationObject = {};
  19071. serializationObject.name = animation.name;
  19072. serializationObject.property = animation.targetProperty;
  19073. serializationObject.framePerSecond = animation.framePerSecond;
  19074. serializationObject.dataType = animation.dataType;
  19075. serializationObject.loopBehavior = animation.loopMode;
  19076. var dataType = animation.dataType;
  19077. serializationObject.keys = [];
  19078. var keys = animation.getKeys();
  19079. for (var index = 0; index < keys.length; index++) {
  19080. var animationKey = keys[index];
  19081. var key = {};
  19082. key.frame = animationKey.frame;
  19083. switch (dataType) {
  19084. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19085. key.values = [animationKey.value];
  19086. break;
  19087. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19088. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19089. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19090. key.values = animationKey.value.asArray();
  19091. break;
  19092. }
  19093. serializationObject.keys.push(key);
  19094. }
  19095. return serializationObject;
  19096. };
  19097. var serializeMultiMaterial = function (material) {
  19098. var serializationObject = {};
  19099. serializationObject.name = material.name;
  19100. serializationObject.id = material.id;
  19101. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19102. serializationObject.materials = [];
  19103. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  19104. var subMat = material.subMaterials[matIndex];
  19105. if (subMat) {
  19106. serializationObject.materials.push(subMat.id);
  19107. }
  19108. else {
  19109. serializationObject.materials.push(null);
  19110. }
  19111. }
  19112. return serializationObject;
  19113. };
  19114. var serializeMaterial = function (material) {
  19115. var serializationObject = {};
  19116. serializationObject.name = material.name;
  19117. serializationObject.ambient = material.ambientColor.asArray();
  19118. serializationObject.diffuse = material.diffuseColor.asArray();
  19119. serializationObject.specular = material.specularColor.asArray();
  19120. serializationObject.specularPower = material.specularPower;
  19121. serializationObject.emissive = material.emissiveColor.asArray();
  19122. serializationObject.alpha = material.alpha;
  19123. serializationObject.id = material.id;
  19124. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19125. serializationObject.backFaceCulling = material.backFaceCulling;
  19126. if (material.diffuseTexture) {
  19127. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  19128. }
  19129. if (material.diffuseFresnelParameters) {
  19130. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  19131. }
  19132. if (material.ambientTexture) {
  19133. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  19134. }
  19135. if (material.opacityTexture) {
  19136. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  19137. }
  19138. if (material.opacityFresnelParameters) {
  19139. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  19140. }
  19141. if (material.reflectionTexture) {
  19142. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  19143. }
  19144. if (material.reflectionFresnelParameters) {
  19145. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  19146. }
  19147. if (material.emissiveTexture) {
  19148. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  19149. }
  19150. if (material.emissiveFresnelParameters) {
  19151. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  19152. }
  19153. if (material.specularTexture) {
  19154. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  19155. }
  19156. if (material.bumpTexture) {
  19157. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  19158. }
  19159. return serializationObject;
  19160. };
  19161. var serializeTexture = function (texture) {
  19162. var serializationObject = {};
  19163. if (!texture.name) {
  19164. return null;
  19165. }
  19166. if (texture instanceof BABYLON.CubeTexture) {
  19167. serializationObject.name = texture.name;
  19168. serializationObject.hasAlpha = texture.hasAlpha;
  19169. serializationObject.level = texture.level;
  19170. serializationObject.coordinatesMode = texture.coordinatesMode;
  19171. return serializationObject;
  19172. }
  19173. if (texture instanceof BABYLON.MirrorTexture) {
  19174. var mirrorTexture = texture;
  19175. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  19176. serializationObject.renderList = [];
  19177. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  19178. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  19179. }
  19180. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  19181. }
  19182. else if (texture instanceof BABYLON.RenderTargetTexture) {
  19183. var renderTargetTexture = texture;
  19184. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  19185. serializationObject.renderList = [];
  19186. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  19187. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  19188. }
  19189. }
  19190. var regularTexture = texture;
  19191. serializationObject.name = texture.name;
  19192. serializationObject.hasAlpha = texture.hasAlpha;
  19193. serializationObject.level = texture.level;
  19194. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  19195. serializationObject.coordinatesMode = texture.coordinatesMode;
  19196. serializationObject.uOffset = regularTexture.uOffset;
  19197. serializationObject.vOffset = regularTexture.vOffset;
  19198. serializationObject.uScale = regularTexture.uScale;
  19199. serializationObject.vScale = regularTexture.vScale;
  19200. serializationObject.uAng = regularTexture.uAng;
  19201. serializationObject.vAng = regularTexture.vAng;
  19202. serializationObject.wAng = regularTexture.wAng;
  19203. serializationObject.wrapU = texture.wrapU;
  19204. serializationObject.wrapV = texture.wrapV;
  19205. // Animations
  19206. appendAnimations(texture, serializationObject);
  19207. return serializationObject;
  19208. };
  19209. var serializeSkeleton = function (skeleton) {
  19210. var serializationObject = {};
  19211. serializationObject.name = skeleton.name;
  19212. serializationObject.id = skeleton.id;
  19213. serializationObject.bones = [];
  19214. for (var index = 0; index < skeleton.bones.length; index++) {
  19215. var bone = skeleton.bones[index];
  19216. var serializedBone = {
  19217. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  19218. name: bone.name,
  19219. matrix: bone.getLocalMatrix().toArray()
  19220. };
  19221. serializationObject.bones.push(serializedBone);
  19222. if (bone.animations && bone.animations.length > 0) {
  19223. serializedBone.animation = serializeAnimation(bone.animations[0]);
  19224. }
  19225. }
  19226. return serializationObject;
  19227. };
  19228. var serializeParticleSystem = function (particleSystem) {
  19229. var serializationObject = {};
  19230. serializationObject.emitterId = particleSystem.emitter.id;
  19231. serializationObject.capacity = particleSystem.getCapacity();
  19232. if (particleSystem.particleTexture) {
  19233. serializationObject.textureName = particleSystem.particleTexture.name;
  19234. }
  19235. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  19236. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  19237. serializationObject.minSize = particleSystem.minSize;
  19238. serializationObject.maxSize = particleSystem.maxSize;
  19239. serializationObject.minLifeTime = particleSystem.minLifeTime;
  19240. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  19241. serializationObject.emitRate = particleSystem.emitRate;
  19242. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  19243. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  19244. serializationObject.gravity = particleSystem.gravity.asArray();
  19245. serializationObject.direction1 = particleSystem.direction1.asArray();
  19246. serializationObject.direction2 = particleSystem.direction2.asArray();
  19247. serializationObject.color1 = particleSystem.color1.asArray();
  19248. serializationObject.color2 = particleSystem.color2.asArray();
  19249. serializationObject.colorDead = particleSystem.colorDead.asArray();
  19250. serializationObject.updateSpeed = particleSystem.updateSpeed;
  19251. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  19252. serializationObject.textureMask = particleSystem.textureMask.asArray();
  19253. serializationObject.blendMode = particleSystem.blendMode;
  19254. return serializationObject;
  19255. };
  19256. var serializeLensFlareSystem = function (lensFlareSystem) {
  19257. var serializationObject = {};
  19258. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  19259. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  19260. serializationObject.flares = [];
  19261. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  19262. var flare = lensFlareSystem.lensFlares[index];
  19263. serializationObject.flares.push({
  19264. size: flare.size,
  19265. position: flare.position,
  19266. color: flare.color.asArray(),
  19267. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  19268. });
  19269. }
  19270. return serializationObject;
  19271. };
  19272. var serializeShadowGenerator = function (light) {
  19273. var serializationObject = {};
  19274. var shadowGenerator = light.getShadowGenerator();
  19275. serializationObject.lightId = light.id;
  19276. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  19277. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  19278. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  19279. serializationObject.renderList = [];
  19280. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19281. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19282. serializationObject.renderList.push(mesh.id);
  19283. }
  19284. return serializationObject;
  19285. };
  19286. var serializedGeometries = [];
  19287. var serializeGeometry = function (geometry, serializationGeometries) {
  19288. if (serializedGeometries[geometry.id]) {
  19289. return;
  19290. }
  19291. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19292. serializationGeometries.boxes.push(serializeBox(geometry));
  19293. }
  19294. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19295. serializationGeometries.spheres.push(serializeSphere(geometry));
  19296. }
  19297. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19298. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19299. }
  19300. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19301. serializationGeometries.toruses.push(serializeTorus(geometry));
  19302. }
  19303. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19304. serializationGeometries.grounds.push(serializeGround(geometry));
  19305. }
  19306. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19307. serializationGeometries.planes.push(serializePlane(geometry));
  19308. }
  19309. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19310. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19311. }
  19312. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19313. throw new Error("Unknow primitive type");
  19314. }
  19315. else {
  19316. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19317. }
  19318. serializedGeometries[geometry.id] = true;
  19319. };
  19320. var serializeGeometryBase = function (geometry) {
  19321. var serializationObject = {};
  19322. serializationObject.id = geometry.id;
  19323. if (BABYLON.Tags.HasTags(geometry)) {
  19324. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19325. }
  19326. return serializationObject;
  19327. };
  19328. var serializeVertexData = function (vertexData) {
  19329. var serializationObject = serializeGeometryBase(vertexData);
  19330. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19331. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19332. }
  19333. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19334. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19335. }
  19336. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19337. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19338. }
  19339. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19340. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19341. }
  19342. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19343. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19344. }
  19345. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19346. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19347. serializationObject.matricesIndices._isExpanded = true;
  19348. }
  19349. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19350. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19351. }
  19352. serializationObject.indices = vertexData.getIndices();
  19353. return serializationObject;
  19354. };
  19355. var serializePrimitive = function (primitive) {
  19356. var serializationObject = serializeGeometryBase(primitive);
  19357. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19358. return serializationObject;
  19359. };
  19360. var serializeBox = function (box) {
  19361. var serializationObject = serializePrimitive(box);
  19362. serializationObject.size = box.size;
  19363. return serializationObject;
  19364. };
  19365. var serializeSphere = function (sphere) {
  19366. var serializationObject = serializePrimitive(sphere);
  19367. serializationObject.segments = sphere.segments;
  19368. serializationObject.diameter = sphere.diameter;
  19369. return serializationObject;
  19370. };
  19371. var serializeCylinder = function (cylinder) {
  19372. var serializationObject = serializePrimitive(cylinder);
  19373. serializationObject.height = cylinder.height;
  19374. serializationObject.diameterTop = cylinder.diameterTop;
  19375. serializationObject.diameterBottom = cylinder.diameterBottom;
  19376. serializationObject.tessellation = cylinder.tessellation;
  19377. return serializationObject;
  19378. };
  19379. var serializeTorus = function (torus) {
  19380. var serializationObject = serializePrimitive(torus);
  19381. serializationObject.diameter = torus.diameter;
  19382. serializationObject.thickness = torus.thickness;
  19383. serializationObject.tessellation = torus.tessellation;
  19384. return serializationObject;
  19385. };
  19386. var serializeGround = function (ground) {
  19387. var serializationObject = serializePrimitive(ground);
  19388. serializationObject.width = ground.width;
  19389. serializationObject.height = ground.height;
  19390. serializationObject.subdivisions = ground.subdivisions;
  19391. return serializationObject;
  19392. };
  19393. var serializePlane = function (plane) {
  19394. var serializationObject = serializePrimitive(plane);
  19395. serializationObject.size = plane.size;
  19396. return serializationObject;
  19397. };
  19398. var serializeTorusKnot = function (torusKnot) {
  19399. var serializationObject = serializePrimitive(torusKnot);
  19400. serializationObject.radius = torusKnot.radius;
  19401. serializationObject.tube = torusKnot.tube;
  19402. serializationObject.radialSegments = torusKnot.radialSegments;
  19403. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19404. serializationObject.p = torusKnot.p;
  19405. serializationObject.q = torusKnot.q;
  19406. return serializationObject;
  19407. };
  19408. var serializeMesh = function (mesh, serializationScene) {
  19409. var serializationObject = {};
  19410. serializationObject.name = mesh.name;
  19411. serializationObject.id = mesh.id;
  19412. if (BABYLON.Tags.HasTags(mesh)) {
  19413. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19414. }
  19415. serializationObject.position = mesh.position.asArray();
  19416. if (mesh.rotationQuaternion) {
  19417. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19418. }
  19419. else if (mesh.rotation) {
  19420. serializationObject.rotation = mesh.rotation.asArray();
  19421. }
  19422. serializationObject.scaling = mesh.scaling.asArray();
  19423. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19424. serializationObject.isEnabled = mesh.isEnabled();
  19425. serializationObject.isVisible = mesh.isVisible;
  19426. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19427. serializationObject.pickable = mesh.isPickable;
  19428. serializationObject.receiveShadows = mesh.receiveShadows;
  19429. serializationObject.billboardMode = mesh.billboardMode;
  19430. serializationObject.visibility = mesh.visibility;
  19431. serializationObject.checkCollisions = mesh.checkCollisions;
  19432. // Parent
  19433. if (mesh.parent) {
  19434. serializationObject.parentId = mesh.parent.id;
  19435. }
  19436. // Geometry
  19437. var geometry = mesh._geometry;
  19438. if (geometry) {
  19439. var geometryId = geometry.id;
  19440. serializationObject.geometryId = geometryId;
  19441. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19442. // 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
  19443. serializeGeometry(geometry, serializationScene.geometries);
  19444. }
  19445. // SubMeshes
  19446. serializationObject.subMeshes = [];
  19447. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19448. var subMesh = mesh.subMeshes[subIndex];
  19449. serializationObject.subMeshes.push({
  19450. materialIndex: subMesh.materialIndex,
  19451. verticesStart: subMesh.verticesStart,
  19452. verticesCount: subMesh.verticesCount,
  19453. indexStart: subMesh.indexStart,
  19454. indexCount: subMesh.indexCount
  19455. });
  19456. }
  19457. }
  19458. // Material
  19459. if (mesh.material) {
  19460. serializationObject.materialId = mesh.material.id;
  19461. }
  19462. else {
  19463. mesh.material = null;
  19464. }
  19465. // Skeleton
  19466. if (mesh.skeleton) {
  19467. serializationObject.skeletonId = mesh.skeleton.id;
  19468. }
  19469. // Physics
  19470. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19471. serializationObject.physicsMass = mesh.getPhysicsMass();
  19472. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19473. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19474. switch (mesh.getPhysicsImpostor()) {
  19475. case BABYLON.PhysicsEngine.BoxImpostor:
  19476. serializationObject.physicsImpostor = 1;
  19477. break;
  19478. case BABYLON.PhysicsEngine.SphereImpostor:
  19479. serializationObject.physicsImpostor = 2;
  19480. break;
  19481. }
  19482. }
  19483. // Instances
  19484. serializationObject.instances = [];
  19485. for (var index = 0; index < mesh.instances.length; index++) {
  19486. var instance = mesh.instances[index];
  19487. var serializationInstance = {
  19488. name: instance.name,
  19489. position: instance.position,
  19490. rotation: instance.rotation,
  19491. rotationQuaternion: instance.rotationQuaternion,
  19492. scaling: instance.scaling
  19493. };
  19494. serializationObject.instances.push(serializationInstance);
  19495. // Animations
  19496. appendAnimations(instance, serializationInstance);
  19497. }
  19498. // Animations
  19499. appendAnimations(mesh, serializationObject);
  19500. // Layer mask
  19501. serializationObject.layerMask = mesh.layerMask;
  19502. return serializationObject;
  19503. };
  19504. var SceneSerializer = (function () {
  19505. function SceneSerializer() {
  19506. }
  19507. SceneSerializer.Serialize = function (scene) {
  19508. var serializationObject = {};
  19509. // Scene
  19510. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19511. serializationObject.autoClear = scene.autoClear;
  19512. serializationObject.clearColor = scene.clearColor.asArray();
  19513. serializationObject.ambientColor = scene.ambientColor.asArray();
  19514. serializationObject.gravity = scene.gravity.asArray();
  19515. // Fog
  19516. if (scene.fogMode && scene.fogMode !== 0) {
  19517. serializationObject.fogMode = scene.fogMode;
  19518. serializationObject.fogColor = scene.fogColor.asArray();
  19519. serializationObject.fogStart = scene.fogStart;
  19520. serializationObject.fogEnd = scene.fogEnd;
  19521. serializationObject.fogDensity = scene.fogDensity;
  19522. }
  19523. // Lights
  19524. serializationObject.lights = [];
  19525. for (var index = 0; index < scene.lights.length; index++) {
  19526. var light = scene.lights[index];
  19527. serializationObject.lights.push(serializeLight(light));
  19528. }
  19529. // Cameras
  19530. serializationObject.cameras = [];
  19531. for (index = 0; index < scene.cameras.length; index++) {
  19532. var camera = scene.cameras[index];
  19533. serializationObject.cameras.push(serializeCamera(camera));
  19534. }
  19535. if (scene.activeCamera) {
  19536. serializationObject.activeCameraID = scene.activeCamera.id;
  19537. }
  19538. // Materials
  19539. serializationObject.materials = [];
  19540. serializationObject.multiMaterials = [];
  19541. for (index = 0; index < scene.materials.length; index++) {
  19542. var material = scene.materials[index];
  19543. if (material instanceof BABYLON.StandardMaterial) {
  19544. serializationObject.materials.push(serializeMaterial(material));
  19545. }
  19546. else if (material instanceof BABYLON.MultiMaterial) {
  19547. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19548. }
  19549. }
  19550. // Skeletons
  19551. serializationObject.skeletons = [];
  19552. for (index = 0; index < scene.skeletons.length; index++) {
  19553. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19554. }
  19555. // Geometries
  19556. serializationObject.geometries = {};
  19557. serializationObject.geometries.boxes = [];
  19558. serializationObject.geometries.spheres = [];
  19559. serializationObject.geometries.cylinders = [];
  19560. serializationObject.geometries.toruses = [];
  19561. serializationObject.geometries.grounds = [];
  19562. serializationObject.geometries.planes = [];
  19563. serializationObject.geometries.torusKnots = [];
  19564. serializationObject.geometries.vertexData = [];
  19565. serializedGeometries = [];
  19566. var geometries = scene.getGeometries();
  19567. for (index = 0; index < geometries.length; index++) {
  19568. var geometry = geometries[index];
  19569. if (geometry.isReady()) {
  19570. serializeGeometry(geometry, serializationObject.geometries);
  19571. }
  19572. }
  19573. // Meshes
  19574. serializationObject.meshes = [];
  19575. for (index = 0; index < scene.meshes.length; index++) {
  19576. var abstractMesh = scene.meshes[index];
  19577. if (abstractMesh instanceof BABYLON.Mesh) {
  19578. var mesh = abstractMesh;
  19579. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19580. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19581. }
  19582. }
  19583. }
  19584. // Particles Systems
  19585. serializationObject.particleSystems = [];
  19586. for (index = 0; index < scene.particleSystems.length; index++) {
  19587. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19588. }
  19589. // Lens flares
  19590. serializationObject.lensFlareSystems = [];
  19591. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19592. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19593. }
  19594. // Shadows
  19595. serializationObject.shadowGenerators = [];
  19596. for (index = 0; index < scene.lights.length; index++) {
  19597. light = scene.lights[index];
  19598. if (light.getShadowGenerator()) {
  19599. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19600. }
  19601. }
  19602. return serializationObject;
  19603. };
  19604. return SceneSerializer;
  19605. })();
  19606. BABYLON.SceneSerializer = SceneSerializer;
  19607. })(BABYLON || (BABYLON = {}));
  19608. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19609. (function (BABYLON) {
  19610. var SceneLoader = (function () {
  19611. function SceneLoader() {
  19612. }
  19613. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19614. get: function () {
  19615. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19616. },
  19617. set: function (value) {
  19618. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19619. },
  19620. enumerable: true,
  19621. configurable: true
  19622. });
  19623. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19624. get: function () {
  19625. return SceneLoader._ShowLoadingScreen;
  19626. },
  19627. set: function (value) {
  19628. SceneLoader._ShowLoadingScreen = value;
  19629. },
  19630. enumerable: true,
  19631. configurable: true
  19632. });
  19633. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19634. var dotPosition = sceneFilename.lastIndexOf(".");
  19635. var queryStringPosition = sceneFilename.indexOf("?");
  19636. if (queryStringPosition === -1) {
  19637. queryStringPosition = sceneFilename.length;
  19638. }
  19639. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19640. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19641. var plugin = this._registeredPlugins[index];
  19642. if (plugin.extensions.indexOf(extension) !== -1) {
  19643. return plugin;
  19644. }
  19645. }
  19646. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19647. };
  19648. // Public functions
  19649. SceneLoader.RegisterPlugin = function (plugin) {
  19650. plugin.extensions = plugin.extensions.toLowerCase();
  19651. SceneLoader._registeredPlugins.push(plugin);
  19652. };
  19653. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19654. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19655. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19656. return;
  19657. }
  19658. var manifestChecked = function (success) {
  19659. scene.database = database;
  19660. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19661. var importMeshFromData = function (data) {
  19662. var meshes = [];
  19663. var particleSystems = [];
  19664. var skeletons = [];
  19665. try {
  19666. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19667. if (onerror) {
  19668. onerror(scene, 'unable to load the scene');
  19669. }
  19670. return;
  19671. }
  19672. }
  19673. catch (e) {
  19674. if (onerror) {
  19675. onerror(scene, e);
  19676. }
  19677. return;
  19678. }
  19679. if (onsuccess) {
  19680. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19681. onsuccess(meshes, particleSystems, skeletons);
  19682. }
  19683. };
  19684. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19685. // Direct load
  19686. importMeshFromData(sceneFilename.substr(5));
  19687. return;
  19688. }
  19689. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19690. importMeshFromData(data);
  19691. }, progressCallBack, database);
  19692. };
  19693. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19694. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19695. };
  19696. /**
  19697. * Load a scene
  19698. * @param rootUrl a string that defines the root url for scene and resources
  19699. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19700. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19701. */
  19702. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19703. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19704. };
  19705. /**
  19706. * Append a scene
  19707. * @param rootUrl a string that defines the root url for scene and resources
  19708. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19709. * @param scene is the instance of BABYLON.Scene to append to
  19710. */
  19711. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19712. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19713. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19714. return;
  19715. }
  19716. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19717. var database;
  19718. if (SceneLoader.ShowLoadingScreen) {
  19719. scene.getEngine().displayLoadingUI();
  19720. }
  19721. var loadSceneFromData = function (data) {
  19722. scene.database = database;
  19723. if (!plugin.load(scene, data, rootUrl)) {
  19724. if (onerror) {
  19725. onerror(scene);
  19726. }
  19727. scene.getEngine().hideLoadingUI();
  19728. return;
  19729. }
  19730. if (onsuccess) {
  19731. onsuccess(scene);
  19732. }
  19733. if (SceneLoader.ShowLoadingScreen) {
  19734. scene.executeWhenReady(function () {
  19735. scene.getEngine().hideLoadingUI();
  19736. });
  19737. }
  19738. };
  19739. var manifestChecked = function (success) {
  19740. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19741. };
  19742. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19743. // Direct load
  19744. loadSceneFromData(sceneFilename.substr(5));
  19745. return;
  19746. }
  19747. if (rootUrl.indexOf("file:") === -1) {
  19748. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19749. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19750. }
  19751. else {
  19752. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19753. }
  19754. };
  19755. // Flags
  19756. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19757. SceneLoader._ShowLoadingScreen = true;
  19758. // Members
  19759. SceneLoader._registeredPlugins = new Array();
  19760. return SceneLoader;
  19761. })();
  19762. BABYLON.SceneLoader = SceneLoader;
  19763. ;
  19764. })(BABYLON || (BABYLON = {}));
  19765. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19766. (function (BABYLON) {
  19767. var Internals;
  19768. (function (Internals) {
  19769. var checkColors4 = function (colors, count) {
  19770. // Check if color3 was used
  19771. if (colors.length === count * 3) {
  19772. var colors4 = [];
  19773. for (var index = 0; index < colors.length; index += 3) {
  19774. var newIndex = (index / 3) * 4;
  19775. colors4[newIndex] = colors[index];
  19776. colors4[newIndex + 1] = colors[index + 1];
  19777. colors4[newIndex + 2] = colors[index + 2];
  19778. colors4[newIndex + 3] = 1.0;
  19779. }
  19780. return colors4;
  19781. }
  19782. return colors;
  19783. };
  19784. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19785. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19786. texture.name = parsedTexture.name;
  19787. texture.hasAlpha = parsedTexture.hasAlpha;
  19788. texture.level = parsedTexture.level;
  19789. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19790. return texture;
  19791. };
  19792. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19793. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19794. return null;
  19795. }
  19796. if (parsedTexture.isCube) {
  19797. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19798. }
  19799. var texture;
  19800. if (parsedTexture.mirrorPlane) {
  19801. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19802. texture._waitingRenderList = parsedTexture.renderList;
  19803. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19804. }
  19805. else if (parsedTexture.isRenderTarget) {
  19806. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19807. texture._waitingRenderList = parsedTexture.renderList;
  19808. }
  19809. else {
  19810. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19811. }
  19812. texture.name = parsedTexture.name;
  19813. texture.hasAlpha = parsedTexture.hasAlpha;
  19814. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19815. texture.level = parsedTexture.level;
  19816. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19817. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19818. texture.uOffset = parsedTexture.uOffset;
  19819. texture.vOffset = parsedTexture.vOffset;
  19820. texture.uScale = parsedTexture.uScale;
  19821. texture.vScale = parsedTexture.vScale;
  19822. texture.uAng = parsedTexture.uAng;
  19823. texture.vAng = parsedTexture.vAng;
  19824. texture.wAng = parsedTexture.wAng;
  19825. texture.wrapU = parsedTexture.wrapU;
  19826. texture.wrapV = parsedTexture.wrapV;
  19827. // Animations
  19828. if (parsedTexture.animations) {
  19829. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19830. var parsedAnimation = parsedTexture.animations[animationIndex];
  19831. texture.animations.push(parseAnimation(parsedAnimation));
  19832. }
  19833. }
  19834. return texture;
  19835. };
  19836. var parseSkeleton = function (parsedSkeleton, scene) {
  19837. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19838. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19839. var parsedBone = parsedSkeleton.bones[index];
  19840. var parentBone = null;
  19841. if (parsedBone.parentBoneIndex > -1) {
  19842. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19843. }
  19844. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19845. if (parsedBone.animation) {
  19846. bone.animations.push(parseAnimation(parsedBone.animation));
  19847. }
  19848. }
  19849. return skeleton;
  19850. };
  19851. var parseFresnelParameters = function (parsedFresnelParameters) {
  19852. var fresnelParameters = new BABYLON.FresnelParameters();
  19853. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19854. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19855. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19856. fresnelParameters.bias = parsedFresnelParameters.bias;
  19857. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19858. return fresnelParameters;
  19859. };
  19860. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19861. var material;
  19862. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19863. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19864. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19865. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19866. material.specularPower = parsedMaterial.specularPower;
  19867. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19868. material.alpha = parsedMaterial.alpha;
  19869. material.id = parsedMaterial.id;
  19870. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19871. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19872. material.wireframe = parsedMaterial.wireframe;
  19873. if (parsedMaterial.diffuseTexture) {
  19874. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19875. }
  19876. if (parsedMaterial.diffuseFresnelParameters) {
  19877. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19878. }
  19879. if (parsedMaterial.ambientTexture) {
  19880. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19881. }
  19882. if (parsedMaterial.opacityTexture) {
  19883. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19884. }
  19885. if (parsedMaterial.opacityFresnelParameters) {
  19886. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19887. }
  19888. if (parsedMaterial.reflectionTexture) {
  19889. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19890. }
  19891. if (parsedMaterial.reflectionFresnelParameters) {
  19892. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19893. }
  19894. if (parsedMaterial.emissiveTexture) {
  19895. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19896. }
  19897. if (parsedMaterial.emissiveFresnelParameters) {
  19898. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19899. }
  19900. if (parsedMaterial.specularTexture) {
  19901. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19902. }
  19903. if (parsedMaterial.bumpTexture) {
  19904. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19905. }
  19906. return material;
  19907. };
  19908. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19909. for (var index = 0; index < parsedData.materials.length; index++) {
  19910. var parsedMaterial = parsedData.materials[index];
  19911. if (parsedMaterial.id === id) {
  19912. return parseMaterial(parsedMaterial, scene, rootUrl);
  19913. }
  19914. }
  19915. return null;
  19916. };
  19917. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19918. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19919. multiMaterial.id = parsedMultiMaterial.id;
  19920. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19921. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19922. var subMatId = parsedMultiMaterial.materials[matIndex];
  19923. if (subMatId) {
  19924. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19925. }
  19926. else {
  19927. multiMaterial.subMaterials.push(null);
  19928. }
  19929. }
  19930. return multiMaterial;
  19931. };
  19932. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19933. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19934. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19935. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19936. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19937. var parsedFlare = parsedLensFlareSystem.flares[index];
  19938. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19939. }
  19940. return lensFlareSystem;
  19941. };
  19942. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19943. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19944. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19945. if (parsedParticleSystem.textureName) {
  19946. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19947. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19948. }
  19949. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19950. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19951. particleSystem.minSize = parsedParticleSystem.minSize;
  19952. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19953. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19954. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19955. particleSystem.emitter = emitter;
  19956. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19957. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19958. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19959. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19960. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19961. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19962. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19963. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19964. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19965. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19966. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19967. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19968. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19969. particleSystem.start();
  19970. return particleSystem;
  19971. };
  19972. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19973. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19974. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19975. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19976. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19977. shadowGenerator.getShadowMap().renderList.push(mesh);
  19978. }
  19979. if (parsedShadowGenerator.usePoissonSampling) {
  19980. shadowGenerator.usePoissonSampling = true;
  19981. }
  19982. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19983. shadowGenerator.useVarianceShadowMap = true;
  19984. }
  19985. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19986. shadowGenerator.useBlurVarianceShadowMap = true;
  19987. if (parsedShadowGenerator.blurScale) {
  19988. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19989. }
  19990. if (parsedShadowGenerator.blurBoxOffset) {
  19991. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19992. }
  19993. }
  19994. if (parsedShadowGenerator.bias !== undefined) {
  19995. shadowGenerator.bias = parsedShadowGenerator.bias;
  19996. }
  19997. return shadowGenerator;
  19998. };
  19999. var parseAnimation = function (parsedAnimation) {
  20000. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  20001. var dataType = parsedAnimation.dataType;
  20002. var keys = [];
  20003. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  20004. var key = parsedAnimation.keys[index];
  20005. var data;
  20006. switch (dataType) {
  20007. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  20008. data = key.values[0];
  20009. break;
  20010. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  20011. data = BABYLON.Quaternion.FromArray(key.values);
  20012. break;
  20013. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  20014. data = BABYLON.Matrix.FromArray(key.values);
  20015. break;
  20016. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  20017. default:
  20018. data = BABYLON.Vector3.FromArray(key.values);
  20019. break;
  20020. }
  20021. keys.push({
  20022. frame: key.frame,
  20023. value: data
  20024. });
  20025. }
  20026. animation.setKeys(keys);
  20027. return animation;
  20028. };
  20029. var parseLight = function (parsedLight, scene) {
  20030. var light;
  20031. switch (parsedLight.type) {
  20032. case 0:
  20033. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  20034. break;
  20035. case 1:
  20036. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20037. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  20038. break;
  20039. case 2:
  20040. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  20041. break;
  20042. case 3:
  20043. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20044. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  20045. break;
  20046. }
  20047. light.id = parsedLight.id;
  20048. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  20049. if (parsedLight.intensity !== undefined) {
  20050. light.intensity = parsedLight.intensity;
  20051. }
  20052. if (parsedLight.range) {
  20053. light.range = parsedLight.range;
  20054. }
  20055. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  20056. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  20057. if (parsedLight.excludedMeshesIds) {
  20058. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  20059. }
  20060. // Parent
  20061. if (parsedLight.parentId) {
  20062. light._waitingParentId = parsedLight.parentId;
  20063. }
  20064. if (parsedLight.includedOnlyMeshesIds) {
  20065. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  20066. }
  20067. // Animations
  20068. if (parsedLight.animations) {
  20069. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20070. var parsedAnimation = parsedLight.animations[animationIndex];
  20071. light.animations.push(parseAnimation(parsedAnimation));
  20072. }
  20073. }
  20074. if (parsedLight.autoAnimate) {
  20075. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  20076. }
  20077. };
  20078. var parseCamera = function (parsedCamera, scene) {
  20079. var camera;
  20080. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  20081. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  20082. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  20083. var alpha = parsedCamera.alpha;
  20084. var beta = parsedCamera.beta;
  20085. var radius = parsedCamera.radius;
  20086. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  20087. var eye_space = parsedCamera.eye_space;
  20088. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  20089. }
  20090. else {
  20091. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  20092. }
  20093. }
  20094. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20095. eye_space = parsedCamera.eye_space;
  20096. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  20097. }
  20098. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20099. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20100. }
  20101. else if (parsedCamera.type === "FollowCamera") {
  20102. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20103. camera.heightOffset = parsedCamera.heightOffset;
  20104. camera.radius = parsedCamera.radius;
  20105. camera.rotationOffset = parsedCamera.rotationOffset;
  20106. if (lockedTargetMesh)
  20107. camera.target = lockedTargetMesh;
  20108. }
  20109. else if (parsedCamera.type === "GamepadCamera") {
  20110. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20111. }
  20112. else if (parsedCamera.type === "OculusCamera") {
  20113. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  20114. }
  20115. else if (parsedCamera.type === "OculusGamepadCamera") {
  20116. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  20117. }
  20118. else if (parsedCamera.type === "TouchCamera") {
  20119. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20120. }
  20121. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20122. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20123. }
  20124. else if (parsedCamera.type === "WebVRCamera") {
  20125. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  20126. }
  20127. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  20128. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  20129. }
  20130. else {
  20131. // Free Camera is the default value
  20132. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20133. }
  20134. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20135. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20136. camera.lockedTarget = lockedTargetMesh;
  20137. }
  20138. camera.id = parsedCamera.id;
  20139. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20140. // Parent
  20141. if (parsedCamera.parentId) {
  20142. camera._waitingParentId = parsedCamera.parentId;
  20143. }
  20144. // Target
  20145. if (parsedCamera.target) {
  20146. if (camera.setTarget) {
  20147. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20148. }
  20149. else {
  20150. //For ArcRotate
  20151. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20152. }
  20153. }
  20154. else {
  20155. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20156. }
  20157. camera.fov = parsedCamera.fov;
  20158. camera.minZ = parsedCamera.minZ;
  20159. camera.maxZ = parsedCamera.maxZ;
  20160. camera.speed = parsedCamera.speed;
  20161. camera.inertia = parsedCamera.inertia;
  20162. camera.checkCollisions = parsedCamera.checkCollisions;
  20163. camera.applyGravity = parsedCamera.applyGravity;
  20164. if (parsedCamera.ellipsoid) {
  20165. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20166. }
  20167. // Animations
  20168. if (parsedCamera.animations) {
  20169. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20170. var parsedAnimation = parsedCamera.animations[animationIndex];
  20171. camera.animations.push(parseAnimation(parsedAnimation));
  20172. }
  20173. }
  20174. if (parsedCamera.autoAnimate) {
  20175. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20176. }
  20177. // Layer Mask
  20178. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20179. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20180. }
  20181. else {
  20182. camera.layerMask = 0xFFFFFFFF;
  20183. }
  20184. return camera;
  20185. };
  20186. var parseGeometry = function (parsedGeometry, scene) {
  20187. var id = parsedGeometry.id;
  20188. return scene.getGeometryByID(id);
  20189. };
  20190. var parseBox = function (parsedBox, scene) {
  20191. if (parseGeometry(parsedBox, scene)) {
  20192. return null; // null since geometry could be something else than a box...
  20193. }
  20194. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20195. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20196. scene.pushGeometry(box, true);
  20197. return box;
  20198. };
  20199. var parseSphere = function (parsedSphere, scene) {
  20200. if (parseGeometry(parsedSphere, scene)) {
  20201. return null; // null since geometry could be something else than a sphere...
  20202. }
  20203. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20204. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20205. scene.pushGeometry(sphere, true);
  20206. return sphere;
  20207. };
  20208. var parseCylinder = function (parsedCylinder, scene) {
  20209. if (parseGeometry(parsedCylinder, scene)) {
  20210. return null; // null since geometry could be something else than a cylinder...
  20211. }
  20212. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20213. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20214. scene.pushGeometry(cylinder, true);
  20215. return cylinder;
  20216. };
  20217. var parseTorus = function (parsedTorus, scene) {
  20218. if (parseGeometry(parsedTorus, scene)) {
  20219. return null; // null since geometry could be something else than a torus...
  20220. }
  20221. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20222. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20223. scene.pushGeometry(torus, true);
  20224. return torus;
  20225. };
  20226. var parseGround = function (parsedGround, scene) {
  20227. if (parseGeometry(parsedGround, scene)) {
  20228. return null; // null since geometry could be something else than a ground...
  20229. }
  20230. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20231. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20232. scene.pushGeometry(ground, true);
  20233. return ground;
  20234. };
  20235. var parsePlane = function (parsedPlane, scene) {
  20236. if (parseGeometry(parsedPlane, scene)) {
  20237. return null; // null since geometry could be something else than a plane...
  20238. }
  20239. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20240. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20241. scene.pushGeometry(plane, true);
  20242. return plane;
  20243. };
  20244. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20245. if (parseGeometry(parsedTorusKnot, scene)) {
  20246. return null; // null since geometry could be something else than a torusKnot...
  20247. }
  20248. 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);
  20249. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20250. scene.pushGeometry(torusKnot, true);
  20251. return torusKnot;
  20252. };
  20253. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20254. if (parseGeometry(parsedVertexData, scene)) {
  20255. return null; // null since geometry could be a primitive
  20256. }
  20257. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20258. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20259. if (parsedVertexData.delayLoadingFile) {
  20260. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20261. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20262. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20263. geometry._delayInfo = [];
  20264. if (parsedVertexData.hasUVs) {
  20265. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20266. }
  20267. if (parsedVertexData.hasUVs2) {
  20268. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20269. }
  20270. if (parsedVertexData.hasColors) {
  20271. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20272. }
  20273. if (parsedVertexData.hasMatricesIndices) {
  20274. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20275. }
  20276. if (parsedVertexData.hasMatricesWeights) {
  20277. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20278. }
  20279. geometry._delayLoadingFunction = importVertexData;
  20280. }
  20281. else {
  20282. importVertexData(parsedVertexData, geometry);
  20283. }
  20284. scene.pushGeometry(geometry, true);
  20285. return geometry;
  20286. };
  20287. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20288. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20289. mesh.id = parsedMesh.id;
  20290. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20291. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20292. if (parsedMesh.rotationQuaternion) {
  20293. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20294. }
  20295. else if (parsedMesh.rotation) {
  20296. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20297. }
  20298. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20299. if (parsedMesh.localMatrix) {
  20300. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20301. }
  20302. else if (parsedMesh.pivotMatrix) {
  20303. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20304. }
  20305. mesh.setEnabled(parsedMesh.isEnabled);
  20306. mesh.isVisible = parsedMesh.isVisible;
  20307. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20308. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20309. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20310. if (parsedMesh.applyFog !== undefined) {
  20311. mesh.applyFog = parsedMesh.applyFog;
  20312. }
  20313. if (parsedMesh.pickable !== undefined) {
  20314. mesh.isPickable = parsedMesh.pickable;
  20315. }
  20316. if (parsedMesh.alphaIndex !== undefined) {
  20317. mesh.alphaIndex = parsedMesh.alphaIndex;
  20318. }
  20319. mesh.receiveShadows = parsedMesh.receiveShadows;
  20320. mesh.billboardMode = parsedMesh.billboardMode;
  20321. if (parsedMesh.visibility !== undefined) {
  20322. mesh.visibility = parsedMesh.visibility;
  20323. }
  20324. mesh.checkCollisions = parsedMesh.checkCollisions;
  20325. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20326. // Parent
  20327. if (parsedMesh.parentId) {
  20328. mesh._waitingParentId = parsedMesh.parentId;
  20329. }
  20330. // Actions
  20331. if (parsedMesh.actions !== undefined) {
  20332. mesh._waitingActions = parsedMesh.actions;
  20333. }
  20334. // Geometry
  20335. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20336. if (parsedMesh.delayLoadingFile) {
  20337. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20338. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20339. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20340. if (parsedMesh._binaryInfo) {
  20341. mesh._binaryInfo = parsedMesh._binaryInfo;
  20342. }
  20343. mesh._delayInfo = [];
  20344. if (parsedMesh.hasUVs) {
  20345. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20346. }
  20347. if (parsedMesh.hasUVs2) {
  20348. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20349. }
  20350. if (parsedMesh.hasColors) {
  20351. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20352. }
  20353. if (parsedMesh.hasMatricesIndices) {
  20354. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20355. }
  20356. if (parsedMesh.hasMatricesWeights) {
  20357. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20358. }
  20359. mesh._delayLoadingFunction = importGeometry;
  20360. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20361. mesh._checkDelayState();
  20362. }
  20363. }
  20364. else {
  20365. importGeometry(parsedMesh, mesh);
  20366. }
  20367. // Material
  20368. if (parsedMesh.materialId) {
  20369. mesh.setMaterialByID(parsedMesh.materialId);
  20370. }
  20371. else {
  20372. mesh.material = null;
  20373. }
  20374. // Skeleton
  20375. if (parsedMesh.skeletonId > -1) {
  20376. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20377. }
  20378. // Physics
  20379. if (parsedMesh.physicsImpostor) {
  20380. if (!scene.isPhysicsEnabled()) {
  20381. scene.enablePhysics();
  20382. }
  20383. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20384. }
  20385. // Animations
  20386. if (parsedMesh.animations) {
  20387. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20388. var parsedAnimation = parsedMesh.animations[animationIndex];
  20389. mesh.animations.push(parseAnimation(parsedAnimation));
  20390. }
  20391. }
  20392. if (parsedMesh.autoAnimate) {
  20393. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20394. }
  20395. // Layer Mask
  20396. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20397. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20398. }
  20399. else {
  20400. mesh.layerMask = 0xFFFFFFFF;
  20401. }
  20402. // Instances
  20403. if (parsedMesh.instances) {
  20404. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20405. var parsedInstance = parsedMesh.instances[index];
  20406. var instance = mesh.createInstance(parsedInstance.name);
  20407. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20408. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20409. if (parsedInstance.rotationQuaternion) {
  20410. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20411. }
  20412. else if (parsedInstance.rotation) {
  20413. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20414. }
  20415. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20416. instance.checkCollisions = mesh.checkCollisions;
  20417. if (parsedMesh.animations) {
  20418. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20419. parsedAnimation = parsedMesh.animations[animationIndex];
  20420. instance.animations.push(parseAnimation(parsedAnimation));
  20421. }
  20422. }
  20423. }
  20424. }
  20425. return mesh;
  20426. };
  20427. var parseActions = function (parsedActions, object, scene) {
  20428. var actionManager = new BABYLON.ActionManager(scene);
  20429. if (object === null)
  20430. scene.actionManager = actionManager;
  20431. else
  20432. object.actionManager = actionManager;
  20433. // instanciate a new object
  20434. var instanciate = function (name, params) {
  20435. var newInstance = Object.create(BABYLON[name].prototype);
  20436. newInstance.constructor.apply(newInstance, params);
  20437. return newInstance;
  20438. };
  20439. var parseParameter = function (name, value, target, propertyPath) {
  20440. if (propertyPath === null) {
  20441. // String, boolean or float
  20442. var floatValue = parseFloat(value);
  20443. if (value === "true" || value === "false")
  20444. return value === "true";
  20445. else
  20446. return isNaN(floatValue) ? value : floatValue;
  20447. }
  20448. var effectiveTarget = propertyPath.split(".");
  20449. var values = value.split(",");
  20450. for (var i = 0; i < effectiveTarget.length; i++) {
  20451. target = target[effectiveTarget[i]];
  20452. }
  20453. // Return appropriate value with its type
  20454. if (typeof (target) === "boolean")
  20455. return values[0] === "true";
  20456. if (typeof (target) === "string")
  20457. return values[0];
  20458. // Parameters with multiple values such as Vector3 etc.
  20459. var split = new Array();
  20460. for (var i = 0; i < values.length; i++)
  20461. split.push(parseFloat(values[i]));
  20462. if (target instanceof BABYLON.Vector3)
  20463. return BABYLON.Vector3.FromArray(split);
  20464. if (target instanceof BABYLON.Vector4)
  20465. return BABYLON.Vector4.FromArray(split);
  20466. if (target instanceof BABYLON.Color3)
  20467. return BABYLON.Color3.FromArray(split);
  20468. if (target instanceof BABYLON.Color4)
  20469. return BABYLON.Color4.FromArray(split);
  20470. return parseFloat(values[0]);
  20471. };
  20472. // traverse graph per trigger
  20473. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20474. if (combineArray === void 0) { combineArray = null; }
  20475. if (parsedAction.detached)
  20476. return;
  20477. var parameters = new Array();
  20478. var target = null;
  20479. var propertyPath = null;
  20480. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20481. // Parameters
  20482. if (parsedAction.type === 2)
  20483. parameters.push(actionManager);
  20484. else
  20485. parameters.push(trigger);
  20486. if (combine) {
  20487. var actions = new Array();
  20488. for (var j = 0; j < parsedAction.combine.length; j++) {
  20489. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20490. }
  20491. parameters.push(actions);
  20492. }
  20493. else {
  20494. for (var i = 0; i < parsedAction.properties.length; i++) {
  20495. var value = parsedAction.properties[i].value;
  20496. var name = parsedAction.properties[i].name;
  20497. var targetType = parsedAction.properties[i].targetType;
  20498. if (name === "target")
  20499. if (targetType !== null && targetType === "SceneProperties")
  20500. value = target = scene;
  20501. else
  20502. value = target = scene.getNodeByName(value);
  20503. else if (name === "parent")
  20504. value = scene.getNodeByName(value);
  20505. else if (name === "sound")
  20506. value = scene.getSoundByName(value);
  20507. else if (name !== "propertyPath") {
  20508. if (parsedAction.type === 2 && name === "operator")
  20509. value = BABYLON.ValueCondition[value];
  20510. else
  20511. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20512. }
  20513. else {
  20514. propertyPath = value;
  20515. }
  20516. parameters.push(value);
  20517. }
  20518. }
  20519. if (combineArray === null) {
  20520. parameters.push(condition);
  20521. }
  20522. else {
  20523. parameters.push(null);
  20524. }
  20525. // If interpolate value action
  20526. if (parsedAction.name === "InterpolateValueAction") {
  20527. var param = parameters[parameters.length - 2];
  20528. parameters[parameters.length - 1] = param;
  20529. parameters[parameters.length - 2] = condition;
  20530. }
  20531. // Action or condition(s) and not CombineAction
  20532. var newAction = instanciate(parsedAction.name, parameters);
  20533. if (combineArray === null) {
  20534. if (newAction instanceof BABYLON.Condition) {
  20535. condition = newAction;
  20536. newAction = action;
  20537. }
  20538. else {
  20539. condition = null;
  20540. if (action)
  20541. action.then(newAction);
  20542. else
  20543. actionManager.registerAction(newAction);
  20544. }
  20545. }
  20546. else {
  20547. combineArray.push(newAction);
  20548. }
  20549. for (var i = 0; i < parsedAction.children.length; i++)
  20550. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20551. };
  20552. for (var i = 0; i < parsedActions.children.length; i++) {
  20553. var triggerParams;
  20554. var trigger = parsedActions.children[i];
  20555. if (trigger.properties.length > 0) {
  20556. var param = trigger.properties[0].value;
  20557. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20558. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20559. }
  20560. else
  20561. triggerParams = BABYLON.ActionManager[trigger.name];
  20562. for (var j = 0; j < trigger.children.length; j++) {
  20563. if (!trigger.detached)
  20564. traverse(trigger.children[j], triggerParams, null, null);
  20565. }
  20566. }
  20567. };
  20568. var parseSound = function (parsedSound, scene, rootUrl) {
  20569. var soundName = parsedSound.name;
  20570. var soundUrl = rootUrl + soundName;
  20571. var options = {
  20572. autoplay: parsedSound.autoplay,
  20573. loop: parsedSound.loop,
  20574. volume: parsedSound.volume,
  20575. spatialSound: parsedSound.spatialSound,
  20576. maxDistance: parsedSound.maxDistance,
  20577. rolloffFactor: parsedSound.rolloffFactor,
  20578. refDistance: parsedSound.refDistance,
  20579. distanceModel: parsedSound.distanceModel,
  20580. playbackRate: parsedSound.playbackRate
  20581. };
  20582. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20583. scene._removePendingData(newSound);
  20584. }, options);
  20585. scene._addPendingData(newSound);
  20586. if (parsedSound.position) {
  20587. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20588. newSound.setPosition(soundPosition);
  20589. }
  20590. if (parsedSound.isDirectional) {
  20591. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20592. if (parsedSound.localDirectionToMesh) {
  20593. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20594. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20595. }
  20596. }
  20597. if (parsedSound.connectedMeshId) {
  20598. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20599. if (connectedMesh) {
  20600. newSound.attachToMesh(connectedMesh);
  20601. }
  20602. }
  20603. };
  20604. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20605. names = (names instanceof Array) ? names : [names];
  20606. for (var i in names) {
  20607. if (mesh.name === names[i]) {
  20608. hierarchyIds.push(mesh.id);
  20609. return true;
  20610. }
  20611. }
  20612. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20613. hierarchyIds.push(mesh.id);
  20614. return true;
  20615. }
  20616. return false;
  20617. };
  20618. var importVertexData = function (parsedVertexData, geometry) {
  20619. var vertexData = new BABYLON.VertexData();
  20620. // positions
  20621. var positions = parsedVertexData.positions;
  20622. if (positions) {
  20623. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20624. }
  20625. // normals
  20626. var normals = parsedVertexData.normals;
  20627. if (normals) {
  20628. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20629. }
  20630. // uvs
  20631. var uvs = parsedVertexData.uvs;
  20632. if (uvs) {
  20633. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20634. }
  20635. // uv2s
  20636. var uv2s = parsedVertexData.uv2s;
  20637. if (uv2s) {
  20638. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20639. }
  20640. // colors
  20641. var colors = parsedVertexData.colors;
  20642. if (colors) {
  20643. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20644. }
  20645. // matricesIndices
  20646. var matricesIndices = parsedVertexData.matricesIndices;
  20647. if (matricesIndices) {
  20648. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20649. }
  20650. // matricesWeights
  20651. var matricesWeights = parsedVertexData.matricesWeights;
  20652. if (matricesWeights) {
  20653. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20654. }
  20655. // indices
  20656. var indices = parsedVertexData.indices;
  20657. if (indices) {
  20658. vertexData.indices = indices;
  20659. }
  20660. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20661. };
  20662. var importGeometry = function (parsedGeometry, mesh) {
  20663. var scene = mesh.getScene();
  20664. // Geometry
  20665. var geometryId = parsedGeometry.geometryId;
  20666. if (geometryId) {
  20667. var geometry = scene.getGeometryByID(geometryId);
  20668. if (geometry) {
  20669. geometry.applyToMesh(mesh);
  20670. }
  20671. }
  20672. else if (parsedGeometry instanceof ArrayBuffer) {
  20673. var binaryInfo = mesh._binaryInfo;
  20674. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20675. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20676. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20677. }
  20678. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20679. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20680. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20681. }
  20682. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20683. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20684. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20685. }
  20686. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20687. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20688. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20689. }
  20690. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20691. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20692. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20693. }
  20694. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20695. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20696. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20697. }
  20698. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20699. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20700. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20701. }
  20702. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20703. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20704. mesh.setIndices(indicesData);
  20705. }
  20706. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20707. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20708. mesh.subMeshes = [];
  20709. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20710. var materialIndex = subMeshesData[(i * 5) + 0];
  20711. var verticesStart = subMeshesData[(i * 5) + 1];
  20712. var verticesCount = subMeshesData[(i * 5) + 2];
  20713. var indexStart = subMeshesData[(i * 5) + 3];
  20714. var indexCount = subMeshesData[(i * 5) + 4];
  20715. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20716. }
  20717. }
  20718. }
  20719. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20720. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20721. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20722. if (parsedGeometry.uvs) {
  20723. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20724. }
  20725. if (parsedGeometry.uvs2) {
  20726. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20727. }
  20728. if (parsedGeometry.colors) {
  20729. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20730. }
  20731. if (parsedGeometry.matricesIndices) {
  20732. if (!parsedGeometry.matricesIndices._isExpanded) {
  20733. var floatIndices = [];
  20734. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20735. var matricesIndex = parsedGeometry.matricesIndices[i];
  20736. floatIndices.push(matricesIndex & 0x000000FF);
  20737. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20738. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20739. floatIndices.push(matricesIndex >> 24);
  20740. }
  20741. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20742. }
  20743. else {
  20744. delete parsedGeometry.matricesIndices._isExpanded;
  20745. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20746. }
  20747. }
  20748. if (parsedGeometry.matricesWeights) {
  20749. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20750. }
  20751. mesh.setIndices(parsedGeometry.indices);
  20752. // SubMeshes
  20753. if (parsedGeometry.subMeshes) {
  20754. mesh.subMeshes = [];
  20755. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20756. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20757. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20758. }
  20759. }
  20760. }
  20761. // Flat shading
  20762. if (mesh._shouldGenerateFlatShading) {
  20763. mesh.convertToFlatShadedMesh();
  20764. delete mesh._shouldGenerateFlatShading;
  20765. }
  20766. // Update
  20767. mesh.computeWorldMatrix(true);
  20768. // Octree
  20769. if (scene._selectionOctree) {
  20770. scene._selectionOctree.addMesh(mesh);
  20771. }
  20772. };
  20773. BABYLON.SceneLoader.RegisterPlugin({
  20774. extensions: ".babylon",
  20775. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20776. var parsedData = JSON.parse(data);
  20777. var loadedSkeletonsIds = [];
  20778. var loadedMaterialsIds = [];
  20779. var hierarchyIds = [];
  20780. for (var index = 0; index < parsedData.meshes.length; index++) {
  20781. var parsedMesh = parsedData.meshes[index];
  20782. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20783. if (meshesNames instanceof Array) {
  20784. // Remove found mesh name from list.
  20785. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20786. }
  20787. // Material ?
  20788. if (parsedMesh.materialId) {
  20789. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20790. if (!materialFound) {
  20791. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20792. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20793. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20794. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20795. var subMatId = parsedMultiMaterial.materials[matIndex];
  20796. loadedMaterialsIds.push(subMatId);
  20797. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20798. }
  20799. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20800. parseMultiMaterial(parsedMultiMaterial, scene);
  20801. materialFound = true;
  20802. break;
  20803. }
  20804. }
  20805. }
  20806. if (!materialFound) {
  20807. loadedMaterialsIds.push(parsedMesh.materialId);
  20808. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20809. }
  20810. }
  20811. // Skeleton ?
  20812. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20813. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20814. if (!skeletonAlreadyLoaded) {
  20815. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20816. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20817. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20818. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20819. loadedSkeletonsIds.push(parsedSkeleton.id);
  20820. }
  20821. }
  20822. }
  20823. }
  20824. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20825. meshes.push(mesh);
  20826. }
  20827. }
  20828. for (index = 0; index < scene.meshes.length; index++) {
  20829. var currentMesh = scene.meshes[index];
  20830. if (currentMesh._waitingParentId) {
  20831. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20832. currentMesh._waitingParentId = undefined;
  20833. }
  20834. }
  20835. // Particles
  20836. if (parsedData.particleSystems) {
  20837. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20838. var parsedParticleSystem = parsedData.particleSystems[index];
  20839. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20840. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20841. }
  20842. }
  20843. }
  20844. return true;
  20845. },
  20846. load: function (scene, data, rootUrl) {
  20847. var parsedData = JSON.parse(data);
  20848. // Scene
  20849. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20850. scene.autoClear = parsedData.autoClear;
  20851. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20852. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20853. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20854. // Fog
  20855. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20856. scene.fogMode = parsedData.fogMode;
  20857. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20858. scene.fogStart = parsedData.fogStart;
  20859. scene.fogEnd = parsedData.fogEnd;
  20860. scene.fogDensity = parsedData.fogDensity;
  20861. }
  20862. for (var index = 0; index < parsedData.lights.length; index++) {
  20863. var parsedLight = parsedData.lights[index];
  20864. parseLight(parsedLight, scene);
  20865. }
  20866. // Materials
  20867. if (parsedData.materials) {
  20868. for (index = 0; index < parsedData.materials.length; index++) {
  20869. var parsedMaterial = parsedData.materials[index];
  20870. parseMaterial(parsedMaterial, scene, rootUrl);
  20871. }
  20872. }
  20873. if (parsedData.multiMaterials) {
  20874. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20875. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20876. parseMultiMaterial(parsedMultiMaterial, scene);
  20877. }
  20878. }
  20879. // Skeletons
  20880. if (parsedData.skeletons) {
  20881. for (index = 0; index < parsedData.skeletons.length; index++) {
  20882. var parsedSkeleton = parsedData.skeletons[index];
  20883. parseSkeleton(parsedSkeleton, scene);
  20884. }
  20885. }
  20886. // Geometries
  20887. var geometries = parsedData.geometries;
  20888. if (geometries) {
  20889. // Boxes
  20890. var boxes = geometries.boxes;
  20891. if (boxes) {
  20892. for (index = 0; index < boxes.length; index++) {
  20893. var parsedBox = boxes[index];
  20894. parseBox(parsedBox, scene);
  20895. }
  20896. }
  20897. // Spheres
  20898. var spheres = geometries.spheres;
  20899. if (spheres) {
  20900. for (index = 0; index < spheres.length; index++) {
  20901. var parsedSphere = spheres[index];
  20902. parseSphere(parsedSphere, scene);
  20903. }
  20904. }
  20905. // Cylinders
  20906. var cylinders = geometries.cylinders;
  20907. if (cylinders) {
  20908. for (index = 0; index < cylinders.length; index++) {
  20909. var parsedCylinder = cylinders[index];
  20910. parseCylinder(parsedCylinder, scene);
  20911. }
  20912. }
  20913. // Toruses
  20914. var toruses = geometries.toruses;
  20915. if (toruses) {
  20916. for (index = 0; index < toruses.length; index++) {
  20917. var parsedTorus = toruses[index];
  20918. parseTorus(parsedTorus, scene);
  20919. }
  20920. }
  20921. // Grounds
  20922. var grounds = geometries.grounds;
  20923. if (grounds) {
  20924. for (index = 0; index < grounds.length; index++) {
  20925. var parsedGround = grounds[index];
  20926. parseGround(parsedGround, scene);
  20927. }
  20928. }
  20929. // Planes
  20930. var planes = geometries.planes;
  20931. if (planes) {
  20932. for (index = 0; index < planes.length; index++) {
  20933. var parsedPlane = planes[index];
  20934. parsePlane(parsedPlane, scene);
  20935. }
  20936. }
  20937. // TorusKnots
  20938. var torusKnots = geometries.torusKnots;
  20939. if (torusKnots) {
  20940. for (index = 0; index < torusKnots.length; index++) {
  20941. var parsedTorusKnot = torusKnots[index];
  20942. parseTorusKnot(parsedTorusKnot, scene);
  20943. }
  20944. }
  20945. // VertexData
  20946. var vertexData = geometries.vertexData;
  20947. if (vertexData) {
  20948. for (index = 0; index < vertexData.length; index++) {
  20949. var parsedVertexData = vertexData[index];
  20950. parseVertexData(parsedVertexData, scene, rootUrl);
  20951. }
  20952. }
  20953. }
  20954. for (index = 0; index < parsedData.meshes.length; index++) {
  20955. var parsedMesh = parsedData.meshes[index];
  20956. parseMesh(parsedMesh, scene, rootUrl);
  20957. }
  20958. for (index = 0; index < parsedData.cameras.length; index++) {
  20959. var parsedCamera = parsedData.cameras[index];
  20960. parseCamera(parsedCamera, scene);
  20961. }
  20962. if (parsedData.activeCameraID) {
  20963. scene.setActiveCameraByID(parsedData.activeCameraID);
  20964. }
  20965. for (index = 0; index < scene.cameras.length; index++) {
  20966. var camera = scene.cameras[index];
  20967. if (camera._waitingParentId) {
  20968. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20969. camera._waitingParentId = undefined;
  20970. }
  20971. }
  20972. for (index = 0; index < scene.lights.length; index++) {
  20973. var light = scene.lights[index];
  20974. if (light._waitingParentId) {
  20975. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20976. light._waitingParentId = undefined;
  20977. }
  20978. }
  20979. // Sounds
  20980. if (parsedData.sounds) {
  20981. for (index = 0; index < parsedData.sounds.length; index++) {
  20982. var parsedSound = parsedData.sounds[index];
  20983. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20984. parseSound(parsedSound, scene, rootUrl);
  20985. }
  20986. else {
  20987. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20988. }
  20989. }
  20990. }
  20991. for (index = 0; index < scene.meshes.length; index++) {
  20992. var mesh = scene.meshes[index];
  20993. if (mesh._waitingParentId) {
  20994. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20995. mesh._waitingParentId = undefined;
  20996. }
  20997. if (mesh._waitingActions) {
  20998. parseActions(mesh._waitingActions, mesh, scene);
  20999. mesh._waitingActions = undefined;
  21000. }
  21001. }
  21002. // Particles Systems
  21003. if (parsedData.particleSystems) {
  21004. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21005. var parsedParticleSystem = parsedData.particleSystems[index];
  21006. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  21007. }
  21008. }
  21009. // Lens flares
  21010. if (parsedData.lensFlareSystems) {
  21011. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  21012. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21013. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  21014. }
  21015. }
  21016. // Shadows
  21017. if (parsedData.shadowGenerators) {
  21018. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  21019. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21020. parseShadowGenerator(parsedShadowGenerator, scene);
  21021. }
  21022. }
  21023. // Actions (scene)
  21024. if (parsedData.actions) {
  21025. parseActions(parsedData.actions, null, scene);
  21026. }
  21027. // Finish
  21028. return true;
  21029. }
  21030. });
  21031. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21032. })(BABYLON || (BABYLON = {}));
  21033. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  21034. (function (BABYLON) {
  21035. // Unique ID when we import meshes from Babylon to CSG
  21036. var currentCSGMeshId = 0;
  21037. // # class Vertex
  21038. // Represents a vertex of a polygon. Use your own vertex class instead of this
  21039. // one to provide additional features like texture coordinates and vertex
  21040. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  21041. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  21042. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  21043. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  21044. // is not used anywhere else.
  21045. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  21046. var Vertex = (function () {
  21047. function Vertex(pos, normal, uv) {
  21048. this.pos = pos;
  21049. this.normal = normal;
  21050. this.uv = uv;
  21051. }
  21052. Vertex.prototype.clone = function () {
  21053. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  21054. };
  21055. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  21056. // orientation of a polygon is flipped.
  21057. Vertex.prototype.flip = function () {
  21058. this.normal = this.normal.scale(-1);
  21059. };
  21060. // Create a new vertex between this vertex and `other` by linearly
  21061. // interpolating all properties using a parameter of `t`. Subclasses should
  21062. // override this to interpolate additional properties.
  21063. Vertex.prototype.interpolate = function (other, t) {
  21064. 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));
  21065. };
  21066. return Vertex;
  21067. })();
  21068. // # class Plane
  21069. // Represents a plane in 3D space.
  21070. var Plane = (function () {
  21071. function Plane(normal, w) {
  21072. this.normal = normal;
  21073. this.w = w;
  21074. }
  21075. Plane.FromPoints = function (a, b, c) {
  21076. var v0 = c.subtract(a);
  21077. var v1 = b.subtract(a);
  21078. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  21079. return null;
  21080. }
  21081. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  21082. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  21083. };
  21084. Plane.prototype.clone = function () {
  21085. return new Plane(this.normal.clone(), this.w);
  21086. };
  21087. Plane.prototype.flip = function () {
  21088. this.normal.scaleInPlace(-1);
  21089. this.w = -this.w;
  21090. };
  21091. // Split `polygon` by this plane if needed, then put the polygon or polygon
  21092. // fragments in the appropriate lists. Coplanar polygons go into either
  21093. // `coplanarFront` or `coplanarBack` depending on their orientation with
  21094. // respect to this plane. Polygons in front or in back of this plane go into
  21095. // either `front` or `back`.
  21096. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  21097. var COPLANAR = 0;
  21098. var FRONT = 1;
  21099. var BACK = 2;
  21100. var SPANNING = 3;
  21101. // Classify each point as well as the entire polygon into one of the above
  21102. // four classes.
  21103. var polygonType = 0;
  21104. var types = [];
  21105. for (var i = 0; i < polygon.vertices.length; i++) {
  21106. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  21107. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  21108. polygonType |= type;
  21109. types.push(type);
  21110. }
  21111. switch (polygonType) {
  21112. case COPLANAR:
  21113. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  21114. break;
  21115. case FRONT:
  21116. front.push(polygon);
  21117. break;
  21118. case BACK:
  21119. back.push(polygon);
  21120. break;
  21121. case SPANNING:
  21122. var f = [], b = [];
  21123. for (i = 0; i < polygon.vertices.length; i++) {
  21124. var j = (i + 1) % polygon.vertices.length;
  21125. var ti = types[i], tj = types[j];
  21126. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  21127. if (ti != BACK)
  21128. f.push(vi);
  21129. if (ti != FRONT)
  21130. b.push(ti != BACK ? vi.clone() : vi);
  21131. if ((ti | tj) == SPANNING) {
  21132. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  21133. var v = vi.interpolate(vj, t);
  21134. f.push(v);
  21135. b.push(v.clone());
  21136. }
  21137. }
  21138. if (f.length >= 3) {
  21139. var poly = new Polygon(f, polygon.shared);
  21140. if (poly.plane)
  21141. front.push(poly);
  21142. }
  21143. if (b.length >= 3) {
  21144. poly = new Polygon(b, polygon.shared);
  21145. if (poly.plane)
  21146. back.push(poly);
  21147. }
  21148. break;
  21149. }
  21150. };
  21151. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  21152. // point is on the plane.
  21153. Plane.EPSILON = 1e-5;
  21154. return Plane;
  21155. })();
  21156. // # class Polygon
  21157. // Represents a convex polygon. The vertices used to initialize a polygon must
  21158. // be coplanar and form a convex loop.
  21159. //
  21160. // Each convex polygon has a `shared` property, which is shared between all
  21161. // polygons that are clones of each other or were split from the same polygon.
  21162. // This can be used to define per-polygon properties (such as surface color).
  21163. var Polygon = (function () {
  21164. function Polygon(vertices, shared) {
  21165. this.vertices = vertices;
  21166. this.shared = shared;
  21167. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  21168. }
  21169. Polygon.prototype.clone = function () {
  21170. var vertices = this.vertices.map(function (v) { return v.clone(); });
  21171. return new Polygon(vertices, this.shared);
  21172. };
  21173. Polygon.prototype.flip = function () {
  21174. this.vertices.reverse().map(function (v) {
  21175. v.flip();
  21176. });
  21177. this.plane.flip();
  21178. };
  21179. return Polygon;
  21180. })();
  21181. // # class Node
  21182. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  21183. // by picking a polygon to split along. That polygon (and all other coplanar
  21184. // polygons) are added directly to that node and the other polygons are added to
  21185. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  21186. // no distinction between internal and leaf nodes.
  21187. var Node = (function () {
  21188. function Node(polygons) {
  21189. this.plane = null;
  21190. this.front = null;
  21191. this.back = null;
  21192. this.polygons = [];
  21193. if (polygons) {
  21194. this.build(polygons);
  21195. }
  21196. }
  21197. Node.prototype.clone = function () {
  21198. var node = new Node();
  21199. node.plane = this.plane && this.plane.clone();
  21200. node.front = this.front && this.front.clone();
  21201. node.back = this.back && this.back.clone();
  21202. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  21203. return node;
  21204. };
  21205. // Convert solid space to empty space and empty space to solid space.
  21206. Node.prototype.invert = function () {
  21207. for (var i = 0; i < this.polygons.length; i++) {
  21208. this.polygons[i].flip();
  21209. }
  21210. if (this.plane) {
  21211. this.plane.flip();
  21212. }
  21213. if (this.front) {
  21214. this.front.invert();
  21215. }
  21216. if (this.back) {
  21217. this.back.invert();
  21218. }
  21219. var temp = this.front;
  21220. this.front = this.back;
  21221. this.back = temp;
  21222. };
  21223. // Recursively remove all polygons in `polygons` that are inside this BSP
  21224. // tree.
  21225. Node.prototype.clipPolygons = function (polygons) {
  21226. if (!this.plane)
  21227. return polygons.slice();
  21228. var front = [], back = [];
  21229. for (var i = 0; i < polygons.length; i++) {
  21230. this.plane.splitPolygon(polygons[i], front, back, front, back);
  21231. }
  21232. if (this.front) {
  21233. front = this.front.clipPolygons(front);
  21234. }
  21235. if (this.back) {
  21236. back = this.back.clipPolygons(back);
  21237. }
  21238. else {
  21239. back = [];
  21240. }
  21241. return front.concat(back);
  21242. };
  21243. // Remove all polygons in this BSP tree that are inside the other BSP tree
  21244. // `bsp`.
  21245. Node.prototype.clipTo = function (bsp) {
  21246. this.polygons = bsp.clipPolygons(this.polygons);
  21247. if (this.front)
  21248. this.front.clipTo(bsp);
  21249. if (this.back)
  21250. this.back.clipTo(bsp);
  21251. };
  21252. // Return a list of all polygons in this BSP tree.
  21253. Node.prototype.allPolygons = function () {
  21254. var polygons = this.polygons.slice();
  21255. if (this.front)
  21256. polygons = polygons.concat(this.front.allPolygons());
  21257. if (this.back)
  21258. polygons = polygons.concat(this.back.allPolygons());
  21259. return polygons;
  21260. };
  21261. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  21262. // new polygons are filtered down to the bottom of the tree and become new
  21263. // nodes there. Each set of polygons is partitioned using the first polygon
  21264. // (no heuristic is used to pick a good split).
  21265. Node.prototype.build = function (polygons) {
  21266. if (!polygons.length)
  21267. return;
  21268. if (!this.plane)
  21269. this.plane = polygons[0].plane.clone();
  21270. var front = [], back = [];
  21271. for (var i = 0; i < polygons.length; i++) {
  21272. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  21273. }
  21274. if (front.length) {
  21275. if (!this.front)
  21276. this.front = new Node();
  21277. this.front.build(front);
  21278. }
  21279. if (back.length) {
  21280. if (!this.back)
  21281. this.back = new Node();
  21282. this.back.build(back);
  21283. }
  21284. };
  21285. return Node;
  21286. })();
  21287. var CSG = (function () {
  21288. function CSG() {
  21289. this.polygons = new Array();
  21290. }
  21291. // Convert BABYLON.Mesh to BABYLON.CSG
  21292. CSG.FromMesh = function (mesh) {
  21293. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21294. if (mesh instanceof BABYLON.Mesh) {
  21295. mesh.computeWorldMatrix(true);
  21296. var matrix = mesh.getWorldMatrix();
  21297. var meshPosition = mesh.position.clone();
  21298. var meshRotation = mesh.rotation.clone();
  21299. var meshScaling = mesh.scaling.clone();
  21300. }
  21301. else {
  21302. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21303. }
  21304. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21305. var subMeshes = mesh.subMeshes;
  21306. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21307. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21308. vertices = [];
  21309. for (var j = 0; j < 3; j++) {
  21310. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21311. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21312. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21313. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21314. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21315. vertex = new Vertex(position, normal, uv);
  21316. vertices.push(vertex);
  21317. }
  21318. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21319. // To handle the case of degenerated triangle
  21320. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21321. if (polygon.plane)
  21322. polygons.push(polygon);
  21323. }
  21324. }
  21325. var csg = CSG.FromPolygons(polygons);
  21326. csg.matrix = matrix;
  21327. csg.position = meshPosition;
  21328. csg.rotation = meshRotation;
  21329. csg.scaling = meshScaling;
  21330. currentCSGMeshId++;
  21331. return csg;
  21332. };
  21333. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21334. CSG.FromPolygons = function (polygons) {
  21335. var csg = new BABYLON.CSG();
  21336. csg.polygons = polygons;
  21337. return csg;
  21338. };
  21339. CSG.prototype.clone = function () {
  21340. var csg = new BABYLON.CSG();
  21341. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21342. csg.copyTransformAttributes(this);
  21343. return csg;
  21344. };
  21345. CSG.prototype.toPolygons = function () {
  21346. return this.polygons;
  21347. };
  21348. CSG.prototype.union = function (csg) {
  21349. var a = new Node(this.clone().polygons);
  21350. var b = new Node(csg.clone().polygons);
  21351. a.clipTo(b);
  21352. b.clipTo(a);
  21353. b.invert();
  21354. b.clipTo(a);
  21355. b.invert();
  21356. a.build(b.allPolygons());
  21357. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21358. };
  21359. CSG.prototype.unionInPlace = function (csg) {
  21360. var a = new Node(this.polygons);
  21361. var b = new Node(csg.polygons);
  21362. a.clipTo(b);
  21363. b.clipTo(a);
  21364. b.invert();
  21365. b.clipTo(a);
  21366. b.invert();
  21367. a.build(b.allPolygons());
  21368. this.polygons = a.allPolygons();
  21369. };
  21370. CSG.prototype.subtract = function (csg) {
  21371. var a = new Node(this.clone().polygons);
  21372. var b = new Node(csg.clone().polygons);
  21373. a.invert();
  21374. a.clipTo(b);
  21375. b.clipTo(a);
  21376. b.invert();
  21377. b.clipTo(a);
  21378. b.invert();
  21379. a.build(b.allPolygons());
  21380. a.invert();
  21381. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21382. };
  21383. CSG.prototype.subtractInPlace = function (csg) {
  21384. var a = new Node(this.polygons);
  21385. var b = new Node(csg.polygons);
  21386. a.invert();
  21387. a.clipTo(b);
  21388. b.clipTo(a);
  21389. b.invert();
  21390. b.clipTo(a);
  21391. b.invert();
  21392. a.build(b.allPolygons());
  21393. a.invert();
  21394. this.polygons = a.allPolygons();
  21395. };
  21396. CSG.prototype.intersect = function (csg) {
  21397. var a = new Node(this.clone().polygons);
  21398. var b = new Node(csg.clone().polygons);
  21399. a.invert();
  21400. b.clipTo(a);
  21401. b.invert();
  21402. a.clipTo(b);
  21403. b.clipTo(a);
  21404. a.build(b.allPolygons());
  21405. a.invert();
  21406. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21407. };
  21408. CSG.prototype.intersectInPlace = function (csg) {
  21409. var a = new Node(this.polygons);
  21410. var b = new Node(csg.polygons);
  21411. a.invert();
  21412. b.clipTo(a);
  21413. b.invert();
  21414. a.clipTo(b);
  21415. b.clipTo(a);
  21416. a.build(b.allPolygons());
  21417. a.invert();
  21418. this.polygons = a.allPolygons();
  21419. };
  21420. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21421. // not modified.
  21422. CSG.prototype.inverse = function () {
  21423. var csg = this.clone();
  21424. csg.inverseInPlace();
  21425. return csg;
  21426. };
  21427. CSG.prototype.inverseInPlace = function () {
  21428. this.polygons.map(function (p) {
  21429. p.flip();
  21430. });
  21431. };
  21432. // This is used to keep meshes transformations so they can be restored
  21433. // when we build back a Babylon Mesh
  21434. // NB : All CSG operations are performed in world coordinates
  21435. CSG.prototype.copyTransformAttributes = function (csg) {
  21436. this.matrix = csg.matrix;
  21437. this.position = csg.position;
  21438. this.rotation = csg.rotation;
  21439. this.scaling = csg.scaling;
  21440. return this;
  21441. };
  21442. // Build Raw mesh from CSG
  21443. // Coordinates here are in world space
  21444. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21445. var matrix = this.matrix.clone();
  21446. matrix.invert();
  21447. 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;
  21448. if (keepSubMeshes) {
  21449. // Sort Polygons, since subMeshes are indices range
  21450. polygons.sort(function (a, b) {
  21451. if (a.shared.meshId === b.shared.meshId) {
  21452. return a.shared.subMeshId - b.shared.subMeshId;
  21453. }
  21454. else {
  21455. return a.shared.meshId - b.shared.meshId;
  21456. }
  21457. });
  21458. }
  21459. for (var i = 0, il = polygons.length; i < il; i++) {
  21460. polygon = polygons[i];
  21461. // Building SubMeshes
  21462. if (!subMesh_dict[polygon.shared.meshId]) {
  21463. subMesh_dict[polygon.shared.meshId] = {};
  21464. }
  21465. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21466. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21467. indexStart: +Infinity,
  21468. indexEnd: -Infinity,
  21469. materialIndex: polygon.shared.materialIndex
  21470. };
  21471. }
  21472. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21473. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21474. polygonIndices[0] = 0;
  21475. polygonIndices[1] = j - 1;
  21476. polygonIndices[2] = j;
  21477. for (var k = 0; k < 3; k++) {
  21478. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21479. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21480. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21481. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21482. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21483. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21484. // Check if 2 points can be merged
  21485. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  21486. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21487. uvs.push(uv.x, uv.y);
  21488. normals.push(normal.x, normal.y, normal.z);
  21489. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21490. }
  21491. indices.push(vertex_idx);
  21492. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21493. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21494. currentIndex++;
  21495. }
  21496. }
  21497. }
  21498. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21499. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21500. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21501. mesh.setIndices(indices);
  21502. if (keepSubMeshes) {
  21503. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21504. var materialIndexOffset = 0, materialMaxIndex;
  21505. mesh.subMeshes.length = 0;
  21506. for (var m in subMesh_dict) {
  21507. materialMaxIndex = -1;
  21508. for (var sm in subMesh_dict[m]) {
  21509. subMesh_obj = subMesh_dict[m][sm];
  21510. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21511. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21512. }
  21513. materialIndexOffset += ++materialMaxIndex;
  21514. }
  21515. }
  21516. return mesh;
  21517. };
  21518. // Build Mesh from CSG taking material and transforms into account
  21519. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21520. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21521. mesh.material = material;
  21522. mesh.position.copyFrom(this.position);
  21523. mesh.rotation.copyFrom(this.rotation);
  21524. mesh.scaling.copyFrom(this.scaling);
  21525. mesh.computeWorldMatrix(true);
  21526. return mesh;
  21527. };
  21528. return CSG;
  21529. })();
  21530. BABYLON.CSG = CSG;
  21531. })(BABYLON || (BABYLON = {}));
  21532. //# sourceMappingURL=babylon.csg.js.map
  21533. var BABYLON;
  21534. (function (BABYLON) {
  21535. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21536. __extends(OculusDistortionCorrectionPostProcess, _super);
  21537. //ANY
  21538. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21539. var _this = this;
  21540. _super.call(this, name, "oculusDistortionCorrection", [
  21541. 'LensCenter',
  21542. 'Scale',
  21543. 'ScaleIn',
  21544. 'HmdWarpParam'
  21545. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21546. this._isRightEye = isRightEye;
  21547. this._distortionFactors = cameraSettings.DistortionK;
  21548. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21549. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21550. this.onSizeChanged = function () {
  21551. _this.aspectRatio = _this.width * .5 / _this.height;
  21552. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21553. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21554. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21555. };
  21556. this.onApply = function (effect) {
  21557. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21558. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21559. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21560. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21561. };
  21562. }
  21563. return OculusDistortionCorrectionPostProcess;
  21564. })(BABYLON.PostProcess);
  21565. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21566. })(BABYLON || (BABYLON = {}));
  21567. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21568. // 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
  21569. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21570. var BABYLON;
  21571. (function (BABYLON) {
  21572. (function (JoystickAxis) {
  21573. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21574. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21575. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21576. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21577. var JoystickAxis = BABYLON.JoystickAxis;
  21578. var VirtualJoystick = (function () {
  21579. function VirtualJoystick(leftJoystick) {
  21580. var _this = this;
  21581. if (leftJoystick) {
  21582. this._leftJoystick = true;
  21583. }
  21584. else {
  21585. this._leftJoystick = false;
  21586. }
  21587. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21588. VirtualJoystick._globalJoystickIndex++;
  21589. // By default left & right arrow keys are moving the X
  21590. // and up & down keys are moving the Y
  21591. this._axisTargetedByLeftAndRight = 0 /* X */;
  21592. this._axisTargetedByUpAndDown = 1 /* Y */;
  21593. this.reverseLeftRight = false;
  21594. this.reverseUpDown = false;
  21595. // collections of pointers
  21596. this._touches = new BABYLON.SmartCollection();
  21597. this.deltaPosition = BABYLON.Vector3.Zero();
  21598. this._joystickSensibility = 25;
  21599. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21600. this._rotationSpeed = 25;
  21601. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21602. this._rotateOnAxisRelativeToMesh = false;
  21603. // injecting a canvas element on top of the canvas 3D game
  21604. if (!VirtualJoystick.vjCanvas) {
  21605. window.addEventListener("resize", function () {
  21606. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21607. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21608. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21609. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21610. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21611. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21612. }, false);
  21613. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21614. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21615. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21616. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21617. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21618. VirtualJoystick.vjCanvas.style.width = "100%";
  21619. VirtualJoystick.vjCanvas.style.height = "100%";
  21620. VirtualJoystick.vjCanvas.style.position = "absolute";
  21621. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21622. VirtualJoystick.vjCanvas.style.top = "0px";
  21623. VirtualJoystick.vjCanvas.style.left = "0px";
  21624. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21625. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21626. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21627. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21628. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21629. document.body.appendChild(VirtualJoystick.vjCanvas);
  21630. }
  21631. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21632. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21633. this.pressed = false;
  21634. // default joystick color
  21635. this._joystickColor = "cyan";
  21636. this._joystickPointerID = -1;
  21637. // current joystick position
  21638. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21639. // origin joystick position
  21640. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21641. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21642. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21643. _this._onPointerDown(evt);
  21644. }, false);
  21645. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21646. _this._onPointerMove(evt);
  21647. }, false);
  21648. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21649. _this._onPointerUp(evt);
  21650. }, false);
  21651. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21652. _this._onPointerUp(evt);
  21653. }, false);
  21654. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21655. evt.preventDefault(); // Disables system menu
  21656. }, false);
  21657. requestAnimationFrame(function () {
  21658. _this._drawVirtualJoystick();
  21659. });
  21660. }
  21661. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21662. this._joystickSensibility = newJoystickSensibility;
  21663. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21664. };
  21665. VirtualJoystick.prototype._onPointerDown = function (e) {
  21666. var positionOnScreenCondition;
  21667. e.preventDefault();
  21668. if (this._leftJoystick === true) {
  21669. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21670. }
  21671. else {
  21672. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21673. }
  21674. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21675. // First contact will be dedicated to the virtual joystick
  21676. this._joystickPointerID = e.pointerId;
  21677. this._joystickPointerStartPos.x = e.clientX;
  21678. this._joystickPointerStartPos.y = e.clientY;
  21679. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21680. this._deltaJoystickVector.x = 0;
  21681. this._deltaJoystickVector.y = 0;
  21682. this.pressed = true;
  21683. this._touches.add(e.pointerId.toString(), e);
  21684. }
  21685. else {
  21686. // You can only trigger the action buttons with a joystick declared
  21687. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21688. this._action();
  21689. this._touches.add(e.pointerId.toString(), e);
  21690. }
  21691. }
  21692. };
  21693. VirtualJoystick.prototype._onPointerMove = function (e) {
  21694. // If the current pointer is the one associated to the joystick (first touch contact)
  21695. if (this._joystickPointerID == e.pointerId) {
  21696. this._joystickPointerPos.x = e.clientX;
  21697. this._joystickPointerPos.y = e.clientY;
  21698. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21699. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21700. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21701. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21702. switch (this._axisTargetedByLeftAndRight) {
  21703. case 0 /* X */:
  21704. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21705. break;
  21706. case 1 /* Y */:
  21707. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21708. break;
  21709. case 2 /* Z */:
  21710. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21711. break;
  21712. }
  21713. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21714. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21715. switch (this._axisTargetedByUpAndDown) {
  21716. case 0 /* X */:
  21717. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21718. break;
  21719. case 1 /* Y */:
  21720. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21721. break;
  21722. case 2 /* Z */:
  21723. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21724. break;
  21725. }
  21726. }
  21727. else {
  21728. if (this._touches.item(e.pointerId.toString())) {
  21729. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21730. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21731. }
  21732. }
  21733. };
  21734. VirtualJoystick.prototype._onPointerUp = function (e) {
  21735. this._clearCanvas();
  21736. if (this._joystickPointerID == e.pointerId) {
  21737. this._joystickPointerID = -1;
  21738. this.pressed = false;
  21739. }
  21740. this._deltaJoystickVector.x = 0;
  21741. this._deltaJoystickVector.y = 0;
  21742. this._touches.remove(e.pointerId.toString());
  21743. };
  21744. /**
  21745. * Change the color of the virtual joystick
  21746. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21747. */
  21748. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21749. this._joystickColor = newColor;
  21750. };
  21751. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21752. this._action = action;
  21753. };
  21754. // Define which axis you'd like to control for left & right
  21755. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21756. switch (axis) {
  21757. case 0 /* X */:
  21758. case 1 /* Y */:
  21759. case 2 /* Z */:
  21760. this._axisTargetedByLeftAndRight = axis;
  21761. break;
  21762. default:
  21763. this._axisTargetedByLeftAndRight = 0 /* X */;
  21764. break;
  21765. }
  21766. };
  21767. // Define which axis you'd like to control for up & down
  21768. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21769. switch (axis) {
  21770. case 0 /* X */:
  21771. case 1 /* Y */:
  21772. case 2 /* Z */:
  21773. this._axisTargetedByUpAndDown = axis;
  21774. break;
  21775. default:
  21776. this._axisTargetedByUpAndDown = 1 /* Y */;
  21777. break;
  21778. }
  21779. };
  21780. VirtualJoystick.prototype._clearCanvas = function () {
  21781. if (this._leftJoystick) {
  21782. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21783. }
  21784. else {
  21785. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21786. }
  21787. };
  21788. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21789. var _this = this;
  21790. if (this.pressed) {
  21791. this._clearCanvas();
  21792. this._touches.forEach(function (touch) {
  21793. if (touch.pointerId === _this._joystickPointerID) {
  21794. VirtualJoystick.vjCanvasContext.beginPath();
  21795. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21796. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21797. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21798. VirtualJoystick.vjCanvasContext.stroke();
  21799. VirtualJoystick.vjCanvasContext.beginPath();
  21800. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21801. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21802. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21803. VirtualJoystick.vjCanvasContext.stroke();
  21804. VirtualJoystick.vjCanvasContext.beginPath();
  21805. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21806. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21807. VirtualJoystick.vjCanvasContext.stroke();
  21808. }
  21809. else {
  21810. VirtualJoystick.vjCanvasContext.beginPath();
  21811. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21812. VirtualJoystick.vjCanvasContext.beginPath();
  21813. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21814. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21815. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21816. VirtualJoystick.vjCanvasContext.stroke();
  21817. }
  21818. ;
  21819. });
  21820. }
  21821. requestAnimationFrame(function () {
  21822. _this._drawVirtualJoystick();
  21823. });
  21824. };
  21825. VirtualJoystick.prototype.releaseCanvas = function () {
  21826. if (VirtualJoystick.vjCanvas) {
  21827. document.body.removeChild(VirtualJoystick.vjCanvas);
  21828. VirtualJoystick.vjCanvas = null;
  21829. }
  21830. };
  21831. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21832. VirtualJoystick._globalJoystickIndex = 0;
  21833. return VirtualJoystick;
  21834. })();
  21835. BABYLON.VirtualJoystick = VirtualJoystick;
  21836. })(BABYLON || (BABYLON = {}));
  21837. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21838. var BABYLON;
  21839. (function (BABYLON) {
  21840. var OculusRiftDevKit2013_Metric = {
  21841. HResolution: 1280,
  21842. VResolution: 800,
  21843. HScreenSize: 0.149759993,
  21844. VScreenSize: 0.0935999975,
  21845. VScreenCenter: 0.0467999987,
  21846. EyeToScreenDistance: 0.0410000011,
  21847. LensSeparationDistance: 0.0635000020,
  21848. InterpupillaryDistance: 0.0640000030,
  21849. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21850. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21851. PostProcessScaleFactor: 1.714605507808412,
  21852. LensCenterOffset: 0.151976421
  21853. };
  21854. var _OculusInnerCamera = (function (_super) {
  21855. __extends(_OculusInnerCamera, _super);
  21856. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21857. _super.call(this, name, position, scene);
  21858. this._workMatrix = new BABYLON.Matrix();
  21859. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21860. // Constants
  21861. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21862. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21863. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21864. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21865. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21866. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21867. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21868. // Postprocess
  21869. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21870. }
  21871. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21872. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21873. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21874. return this._projectionMatrix;
  21875. };
  21876. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21877. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21878. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21879. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21880. // Computing target and final matrix
  21881. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21882. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21883. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21884. return this._viewMatrix;
  21885. };
  21886. return _OculusInnerCamera;
  21887. })(BABYLON.FreeCamera);
  21888. var OculusCamera = (function (_super) {
  21889. __extends(OculusCamera, _super);
  21890. function OculusCamera(name, position, scene) {
  21891. _super.call(this, name, position, scene);
  21892. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21893. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21894. this.subCameras.push(this._leftCamera);
  21895. this.subCameras.push(this._rightCamera);
  21896. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21897. }
  21898. OculusCamera.prototype._update = function () {
  21899. this._leftCamera.position.copyFrom(this.position);
  21900. this._rightCamera.position.copyFrom(this.position);
  21901. this._updateCamera(this._leftCamera);
  21902. this._updateCamera(this._rightCamera);
  21903. _super.prototype._update.call(this);
  21904. };
  21905. OculusCamera.prototype._updateCamera = function (camera) {
  21906. camera.minZ = this.minZ;
  21907. camera.maxZ = this.maxZ;
  21908. camera.rotation.x = this.rotation.x;
  21909. camera.rotation.y = this.rotation.y;
  21910. camera.rotation.z = this.rotation.z;
  21911. };
  21912. // Oculus events
  21913. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21914. var yaw = evt.alpha / 180 * Math.PI;
  21915. var pitch = evt.beta / 180 * Math.PI;
  21916. var roll = evt.gamma / 180 * Math.PI;
  21917. if (!this._offsetOrientation) {
  21918. this._offsetOrientation = {
  21919. yaw: yaw,
  21920. pitch: pitch,
  21921. roll: roll
  21922. };
  21923. return;
  21924. }
  21925. else {
  21926. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21927. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21928. this.rotation.z += this._offsetOrientation.roll - roll;
  21929. this._offsetOrientation.yaw = yaw;
  21930. this._offsetOrientation.pitch = pitch;
  21931. this._offsetOrientation.roll = roll;
  21932. }
  21933. };
  21934. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21935. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21936. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21937. };
  21938. OculusCamera.prototype.detachControl = function (element) {
  21939. _super.prototype.detachControl.call(this, element);
  21940. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21941. };
  21942. return OculusCamera;
  21943. })(BABYLON.FreeCamera);
  21944. BABYLON.OculusCamera = OculusCamera;
  21945. })(BABYLON || (BABYLON = {}));
  21946. //# sourceMappingURL=babylon.oculusCamera.js.map
  21947. var BABYLON;
  21948. (function (BABYLON) {
  21949. var OculusRiftDevKit2013_Metric = {
  21950. HResolution: 1280,
  21951. VResolution: 800,
  21952. HScreenSize: 0.149759993,
  21953. VScreenSize: 0.0935999975,
  21954. VScreenCenter: 0.0467999987,
  21955. EyeToScreenDistance: 0.0410000011,
  21956. LensSeparationDistance: 0.0635000020,
  21957. InterpupillaryDistance: 0.0640000030,
  21958. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21959. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21960. PostProcessScaleFactor: 1.714605507808412,
  21961. LensCenterOffset: 0.151976421
  21962. };
  21963. var _OculusInnerGamepadCamera = (function (_super) {
  21964. __extends(_OculusInnerGamepadCamera, _super);
  21965. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21966. _super.call(this, name, position, scene);
  21967. this._workMatrix = new BABYLON.Matrix();
  21968. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21969. // Constants
  21970. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21971. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21972. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21973. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21974. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21975. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21976. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21977. // Postprocess
  21978. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21979. }
  21980. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21981. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21982. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21983. return this._projectionMatrix;
  21984. };
  21985. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21986. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21987. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21988. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21989. // Computing target and final matrix
  21990. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21991. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21992. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21993. return this._viewMatrix;
  21994. };
  21995. return _OculusInnerGamepadCamera;
  21996. })(BABYLON.FreeCamera);
  21997. var OculusGamepadCamera = (function (_super) {
  21998. __extends(OculusGamepadCamera, _super);
  21999. function OculusGamepadCamera(name, position, scene) {
  22000. var _this = this;
  22001. _super.call(this, name, position, scene);
  22002. this.angularSensibility = 200;
  22003. this.moveSensibility = 75;
  22004. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  22005. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  22006. this.subCameras.push(this._leftCamera);
  22007. this.subCameras.push(this._rightCamera);
  22008. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  22009. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  22010. _this._onNewGameConnected(gamepad);
  22011. });
  22012. }
  22013. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  22014. // Only the first gamepad can control the camera
  22015. if (gamepad.index === 0) {
  22016. this._gamepad = gamepad;
  22017. }
  22018. };
  22019. OculusGamepadCamera.prototype._update = function () {
  22020. this._leftCamera.position.copyFrom(this.position);
  22021. this._rightCamera.position.copyFrom(this.position);
  22022. this._updateCamera(this._leftCamera);
  22023. this._updateCamera(this._rightCamera);
  22024. _super.prototype._update.call(this);
  22025. };
  22026. OculusGamepadCamera.prototype._checkInputs = function () {
  22027. if (!this._gamepad) {
  22028. return;
  22029. }
  22030. var LSValues = this._gamepad.leftStick;
  22031. var normalizedLX = LSValues.x / this.moveSensibility;
  22032. var normalizedLY = LSValues.y / this.moveSensibility;
  22033. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  22034. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  22035. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22036. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  22037. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22038. };
  22039. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  22040. camera.minZ = this.minZ;
  22041. camera.maxZ = this.maxZ;
  22042. camera.rotation.x = this.rotation.x;
  22043. camera.rotation.y = this.rotation.y;
  22044. camera.rotation.z = this.rotation.z;
  22045. };
  22046. // Oculus events
  22047. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  22048. var yaw = evt.alpha / 180 * Math.PI;
  22049. var pitch = evt.beta / 180 * Math.PI;
  22050. var roll = evt.gamma / 180 * Math.PI;
  22051. if (!this._offsetOrientation) {
  22052. this._offsetOrientation = {
  22053. yaw: yaw,
  22054. pitch: pitch,
  22055. roll: roll
  22056. };
  22057. return;
  22058. }
  22059. else {
  22060. this.rotation.y += yaw - this._offsetOrientation.yaw;
  22061. this.rotation.x += pitch - this._offsetOrientation.pitch;
  22062. this.rotation.z += this._offsetOrientation.roll - roll;
  22063. this._offsetOrientation.yaw = yaw;
  22064. this._offsetOrientation.pitch = pitch;
  22065. this._offsetOrientation.roll = roll;
  22066. }
  22067. };
  22068. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  22069. _super.prototype.attachControl.call(this, element, noPreventDefault);
  22070. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  22071. };
  22072. OculusGamepadCamera.prototype.detachControl = function (element) {
  22073. _super.prototype.detachControl.call(this, element);
  22074. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  22075. };
  22076. OculusGamepadCamera.prototype.dispose = function () {
  22077. this._gamepads.dispose();
  22078. _super.prototype.dispose.call(this);
  22079. };
  22080. return OculusGamepadCamera;
  22081. })(BABYLON.FreeCamera);
  22082. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  22083. })(BABYLON || (BABYLON = {}));
  22084. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  22085. var BABYLON;
  22086. (function (BABYLON) {
  22087. // We're mainly based on the logic defined into the FreeCamera code
  22088. var VirtualJoysticksCamera = (function (_super) {
  22089. __extends(VirtualJoysticksCamera, _super);
  22090. function VirtualJoysticksCamera(name, position, scene) {
  22091. _super.call(this, name, position, scene);
  22092. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  22093. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  22094. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  22095. this._leftjoystick.setJoystickSensibility(0.15);
  22096. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  22097. this._rightjoystick.setAxisForUpDown(0 /* X */);
  22098. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  22099. this._rightjoystick.reverseUpDown = true;
  22100. this._rightjoystick.setJoystickSensibility(0.05);
  22101. this._rightjoystick.setJoystickColor("yellow");
  22102. }
  22103. VirtualJoysticksCamera.prototype._checkInputs = function () {
  22104. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22105. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  22106. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22107. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  22108. if (!this._leftjoystick.pressed) {
  22109. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  22110. }
  22111. if (!this._rightjoystick.pressed) {
  22112. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  22113. }
  22114. };
  22115. VirtualJoysticksCamera.prototype.dispose = function () {
  22116. this._leftjoystick.releaseCanvas();
  22117. _super.prototype.dispose.call(this);
  22118. };
  22119. return VirtualJoysticksCamera;
  22120. })(BABYLON.FreeCamera);
  22121. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  22122. })(BABYLON || (BABYLON = {}));
  22123. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  22124. var BABYLON;
  22125. (function (BABYLON) {
  22126. var ShaderMaterial = (function (_super) {
  22127. __extends(ShaderMaterial, _super);
  22128. function ShaderMaterial(name, scene, shaderPath, options) {
  22129. _super.call(this, name, scene);
  22130. this._textures = new Array();
  22131. this._floats = new Array();
  22132. this._floatsArrays = {};
  22133. this._colors3 = new Array();
  22134. this._colors4 = new Array();
  22135. this._vectors2 = new Array();
  22136. this._vectors3 = new Array();
  22137. this._matrices = new Array();
  22138. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  22139. this._shaderPath = shaderPath;
  22140. options.needAlphaBlending = options.needAlphaBlending || false;
  22141. options.needAlphaTesting = options.needAlphaTesting || false;
  22142. options.attributes = options.attributes || ["position", "normal", "uv"];
  22143. options.uniforms = options.uniforms || ["worldViewProjection"];
  22144. options.samplers = options.samplers || [];
  22145. this._options = options;
  22146. }
  22147. ShaderMaterial.prototype.needAlphaBlending = function () {
  22148. return this._options.needAlphaBlending;
  22149. };
  22150. ShaderMaterial.prototype.needAlphaTesting = function () {
  22151. return this._options.needAlphaTesting;
  22152. };
  22153. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  22154. if (this._options.uniforms.indexOf(uniformName) === -1) {
  22155. this._options.uniforms.push(uniformName);
  22156. }
  22157. };
  22158. ShaderMaterial.prototype.setTexture = function (name, texture) {
  22159. if (this._options.samplers.indexOf(name) === -1) {
  22160. this._options.samplers.push(name);
  22161. }
  22162. this._textures[name] = texture;
  22163. return this;
  22164. };
  22165. ShaderMaterial.prototype.setFloat = function (name, value) {
  22166. this._checkUniform(name);
  22167. this._floats[name] = value;
  22168. return this;
  22169. };
  22170. ShaderMaterial.prototype.setFloats = function (name, value) {
  22171. this._checkUniform(name);
  22172. this._floatsArrays[name] = value;
  22173. return this;
  22174. };
  22175. ShaderMaterial.prototype.setColor3 = function (name, value) {
  22176. this._checkUniform(name);
  22177. this._colors3[name] = value;
  22178. return this;
  22179. };
  22180. ShaderMaterial.prototype.setColor4 = function (name, value) {
  22181. this._checkUniform(name);
  22182. this._colors4[name] = value;
  22183. return this;
  22184. };
  22185. ShaderMaterial.prototype.setVector2 = function (name, value) {
  22186. this._checkUniform(name);
  22187. this._vectors2[name] = value;
  22188. return this;
  22189. };
  22190. ShaderMaterial.prototype.setVector3 = function (name, value) {
  22191. this._checkUniform(name);
  22192. this._vectors3[name] = value;
  22193. return this;
  22194. };
  22195. ShaderMaterial.prototype.setMatrix = function (name, value) {
  22196. this._checkUniform(name);
  22197. this._matrices[name] = value;
  22198. return this;
  22199. };
  22200. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  22201. var scene = this.getScene();
  22202. var engine = scene.getEngine();
  22203. if (!this.checkReadyOnEveryCall) {
  22204. if (this._renderId === scene.getRenderId()) {
  22205. return true;
  22206. }
  22207. }
  22208. // Instances
  22209. var defines = [];
  22210. var fallbacks = new BABYLON.EffectFallbacks();
  22211. if (useInstances) {
  22212. defines.push("#define INSTANCES");
  22213. }
  22214. // Bones
  22215. if (mesh && mesh.useBones) {
  22216. defines.push("#define BONES");
  22217. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22218. defines.push("#define BONES4");
  22219. fallbacks.addFallback(0, "BONES4");
  22220. }
  22221. // Alpha test
  22222. if (engine.getAlphaTesting()) {
  22223. defines.push("#define ALPHATEST");
  22224. }
  22225. var previousEffect = this._effect;
  22226. var join = defines.join("\n");
  22227. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  22228. if (!this._effect.isReady()) {
  22229. return false;
  22230. }
  22231. if (previousEffect !== this._effect) {
  22232. scene.resetCachedMaterial();
  22233. }
  22234. this._renderId = scene.getRenderId();
  22235. return true;
  22236. };
  22237. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22238. var scene = this.getScene();
  22239. if (this._options.uniforms.indexOf("world") !== -1) {
  22240. this._effect.setMatrix("world", world);
  22241. }
  22242. if (this._options.uniforms.indexOf("worldView") !== -1) {
  22243. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  22244. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  22245. }
  22246. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22247. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22248. }
  22249. };
  22250. ShaderMaterial.prototype.bind = function (world, mesh) {
  22251. // Std values
  22252. this.bindOnlyWorldMatrix(world);
  22253. if (this.getScene().getCachedMaterial() !== this) {
  22254. if (this._options.uniforms.indexOf("view") !== -1) {
  22255. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22256. }
  22257. if (this._options.uniforms.indexOf("projection") !== -1) {
  22258. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22259. }
  22260. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22261. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22262. }
  22263. // Bones
  22264. if (mesh && mesh.useBones) {
  22265. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22266. }
  22267. for (var name in this._textures) {
  22268. this._effect.setTexture(name, this._textures[name]);
  22269. }
  22270. for (name in this._floats) {
  22271. this._effect.setFloat(name, this._floats[name]);
  22272. }
  22273. for (name in this._floatsArrays) {
  22274. this._effect.setArray(name, this._floatsArrays[name]);
  22275. }
  22276. for (name in this._colors3) {
  22277. this._effect.setColor3(name, this._colors3[name]);
  22278. }
  22279. for (name in this._colors4) {
  22280. var color = this._colors4[name];
  22281. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22282. }
  22283. for (name in this._vectors2) {
  22284. this._effect.setVector2(name, this._vectors2[name]);
  22285. }
  22286. for (name in this._vectors3) {
  22287. this._effect.setVector3(name, this._vectors3[name]);
  22288. }
  22289. for (name in this._matrices) {
  22290. this._effect.setMatrix(name, this._matrices[name]);
  22291. }
  22292. }
  22293. _super.prototype.bind.call(this, world, mesh);
  22294. };
  22295. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22296. for (var name in this._textures) {
  22297. this._textures[name].dispose();
  22298. }
  22299. this._textures = [];
  22300. _super.prototype.dispose.call(this, forceDisposeEffect);
  22301. };
  22302. return ShaderMaterial;
  22303. })(BABYLON.Material);
  22304. BABYLON.ShaderMaterial = ShaderMaterial;
  22305. })(BABYLON || (BABYLON = {}));
  22306. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22307. (function (BABYLON) {
  22308. var VertexData = (function () {
  22309. function VertexData() {
  22310. }
  22311. VertexData.prototype.set = function (data, kind) {
  22312. switch (kind) {
  22313. case BABYLON.VertexBuffer.PositionKind:
  22314. this.positions = data;
  22315. break;
  22316. case BABYLON.VertexBuffer.NormalKind:
  22317. this.normals = data;
  22318. break;
  22319. case BABYLON.VertexBuffer.UVKind:
  22320. this.uvs = data;
  22321. break;
  22322. case BABYLON.VertexBuffer.UV2Kind:
  22323. this.uv2s = data;
  22324. break;
  22325. case BABYLON.VertexBuffer.ColorKind:
  22326. this.colors = data;
  22327. break;
  22328. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22329. this.matricesIndices = data;
  22330. break;
  22331. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22332. this.matricesWeights = data;
  22333. break;
  22334. }
  22335. };
  22336. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22337. this._applyTo(mesh, updatable);
  22338. };
  22339. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22340. this._applyTo(geometry, updatable);
  22341. };
  22342. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22343. this._update(mesh);
  22344. };
  22345. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22346. this._update(geometry);
  22347. };
  22348. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22349. if (this.positions) {
  22350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22351. }
  22352. if (this.normals) {
  22353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22354. }
  22355. if (this.uvs) {
  22356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22357. }
  22358. if (this.uv2s) {
  22359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22360. }
  22361. if (this.colors) {
  22362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22363. }
  22364. if (this.matricesIndices) {
  22365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22366. }
  22367. if (this.matricesWeights) {
  22368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22369. }
  22370. if (this.indices) {
  22371. meshOrGeometry.setIndices(this.indices);
  22372. }
  22373. };
  22374. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22375. if (this.positions) {
  22376. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22377. }
  22378. if (this.normals) {
  22379. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22380. }
  22381. if (this.uvs) {
  22382. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22383. }
  22384. if (this.uv2s) {
  22385. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22386. }
  22387. if (this.colors) {
  22388. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22389. }
  22390. if (this.matricesIndices) {
  22391. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22392. }
  22393. if (this.matricesWeights) {
  22394. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22395. }
  22396. if (this.indices) {
  22397. meshOrGeometry.setIndices(this.indices);
  22398. }
  22399. };
  22400. VertexData.prototype.transform = function (matrix) {
  22401. var transformed = BABYLON.Vector3.Zero();
  22402. if (this.positions) {
  22403. var position = BABYLON.Vector3.Zero();
  22404. for (var index = 0; index < this.positions.length; index += 3) {
  22405. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22406. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22407. this.positions[index] = transformed.x;
  22408. this.positions[index + 1] = transformed.y;
  22409. this.positions[index + 2] = transformed.z;
  22410. }
  22411. }
  22412. if (this.normals) {
  22413. var normal = BABYLON.Vector3.Zero();
  22414. for (index = 0; index < this.normals.length; index += 3) {
  22415. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22416. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22417. this.normals[index] = transformed.x;
  22418. this.normals[index + 1] = transformed.y;
  22419. this.normals[index + 2] = transformed.z;
  22420. }
  22421. }
  22422. };
  22423. VertexData.prototype.merge = function (other) {
  22424. if (other.indices) {
  22425. if (!this.indices) {
  22426. this.indices = [];
  22427. }
  22428. var offset = this.positions ? this.positions.length / 3 : 0;
  22429. for (var index = 0; index < other.indices.length; index++) {
  22430. this.indices.push(other.indices[index] + offset);
  22431. }
  22432. }
  22433. if (other.positions) {
  22434. if (!this.positions) {
  22435. this.positions = [];
  22436. }
  22437. for (index = 0; index < other.positions.length; index++) {
  22438. this.positions.push(other.positions[index]);
  22439. }
  22440. }
  22441. if (other.normals) {
  22442. if (!this.normals) {
  22443. this.normals = [];
  22444. }
  22445. for (index = 0; index < other.normals.length; index++) {
  22446. this.normals.push(other.normals[index]);
  22447. }
  22448. }
  22449. if (other.uvs) {
  22450. if (!this.uvs) {
  22451. this.uvs = [];
  22452. }
  22453. for (index = 0; index < other.uvs.length; index++) {
  22454. this.uvs.push(other.uvs[index]);
  22455. }
  22456. }
  22457. if (other.uv2s) {
  22458. if (!this.uv2s) {
  22459. this.uv2s = [];
  22460. }
  22461. for (index = 0; index < other.uv2s.length; index++) {
  22462. this.uv2s.push(other.uv2s[index]);
  22463. }
  22464. }
  22465. if (other.matricesIndices) {
  22466. if (!this.matricesIndices) {
  22467. this.matricesIndices = [];
  22468. }
  22469. for (index = 0; index < other.matricesIndices.length; index++) {
  22470. this.matricesIndices.push(other.matricesIndices[index]);
  22471. }
  22472. }
  22473. if (other.matricesWeights) {
  22474. if (!this.matricesWeights) {
  22475. this.matricesWeights = [];
  22476. }
  22477. for (index = 0; index < other.matricesWeights.length; index++) {
  22478. this.matricesWeights.push(other.matricesWeights[index]);
  22479. }
  22480. }
  22481. if (other.colors) {
  22482. if (!this.colors) {
  22483. this.colors = [];
  22484. }
  22485. for (index = 0; index < other.colors.length; index++) {
  22486. this.colors.push(other.colors[index]);
  22487. }
  22488. }
  22489. };
  22490. // Statics
  22491. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22492. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22493. };
  22494. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22495. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22496. };
  22497. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22498. var result = new VertexData();
  22499. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22500. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22501. }
  22502. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22503. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22504. }
  22505. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22506. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22507. }
  22508. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22509. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22510. }
  22511. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22512. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22513. }
  22514. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22515. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22516. }
  22517. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22518. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22519. }
  22520. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22521. return result;
  22522. };
  22523. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22524. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22525. closeArray = closeArray || false;
  22526. closePath = closePath || false;
  22527. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22528. offset = offset || defaultOffset;
  22529. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22530. var positions = [];
  22531. var indices = [];
  22532. var normals = [];
  22533. var uvs = [];
  22534. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22535. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22536. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22537. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22538. var minlg; // minimal length among all paths from pathArray
  22539. var lg = []; // array of path lengths : nb of vertex per path
  22540. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22541. var p; // path iterator
  22542. var i; // point iterator
  22543. var j; // point iterator
  22544. // if single path in pathArray
  22545. if (pathArray.length < 2) {
  22546. var ar1 = [];
  22547. var ar2 = [];
  22548. for (i = 0; i < pathArray[0].length - offset; i++) {
  22549. ar1.push(pathArray[0][i]);
  22550. ar2.push(pathArray[0][i + offset]);
  22551. }
  22552. pathArray = [ar1, ar2];
  22553. }
  22554. // positions and horizontal distances (u)
  22555. var idc = 0;
  22556. minlg = pathArray[0].length;
  22557. for (p = 0; p < pathArray.length; p++) {
  22558. uTotalDistance[p] = 0;
  22559. us[p] = [0];
  22560. var path = pathArray[p];
  22561. var l = path.length;
  22562. minlg = (minlg < l) ? minlg : l;
  22563. lg[p] = l;
  22564. idx[p] = idc;
  22565. j = 0;
  22566. while (j < l) {
  22567. positions.push(path[j].x, path[j].y, path[j].z);
  22568. if (j > 0) {
  22569. var vectlg = path[j].subtract(path[j - 1]).length();
  22570. var dist = vectlg + uTotalDistance[p];
  22571. us[p].push(dist);
  22572. uTotalDistance[p] = dist;
  22573. }
  22574. j++;
  22575. }
  22576. if (closePath) {
  22577. vectlg = path[0].subtract(path[j - 1]).length();
  22578. dist = vectlg + uTotalDistance[p];
  22579. uTotalDistance[p] = dist;
  22580. }
  22581. idc += l;
  22582. }
  22583. for (i = 0; i < minlg; i++) {
  22584. vTotalDistance[i] = 0;
  22585. vs[i] = [0];
  22586. var path1;
  22587. var path2;
  22588. for (p = 0; p < pathArray.length - 1; p++) {
  22589. path1 = pathArray[p];
  22590. path2 = pathArray[p + 1];
  22591. vectlg = path2[i].subtract(path1[i]).length();
  22592. dist = vectlg + vTotalDistance[i];
  22593. vs[i].push(dist);
  22594. vTotalDistance[i] = dist;
  22595. }
  22596. if (closeArray) {
  22597. path1 = pathArray[p];
  22598. path2 = pathArray[0];
  22599. vectlg = path2[i].subtract(path1[i]).length();
  22600. dist = vectlg + vTotalDistance[i];
  22601. vTotalDistance[i] = dist;
  22602. }
  22603. }
  22604. // uvs
  22605. var u;
  22606. var v;
  22607. for (p = 0; p < pathArray.length; p++) {
  22608. for (i = 0; i < minlg; i++) {
  22609. u = us[p][i] / uTotalDistance[p];
  22610. v = vs[i][p] / vTotalDistance[i];
  22611. uvs.push(u, v);
  22612. }
  22613. }
  22614. // indices
  22615. p = 0; // path index
  22616. var pi = 0; // positions array index
  22617. var l1 = lg[p] - 1; // path1 length
  22618. var l2 = lg[p + 1] - 1; // path2 length
  22619. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22620. var shft = idx[1] - idx[0]; // shift
  22621. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22622. var t1; // two consecutive triangles, so 4 points : point1
  22623. var t2; // point2
  22624. var t3; // point3
  22625. var t4; // point4
  22626. while (pi <= min && p < path1nb) {
  22627. // 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
  22628. t1 = pi;
  22629. t2 = pi + shft;
  22630. t3 = pi + 1;
  22631. t4 = pi + shft + 1;
  22632. indices.push(pi, pi + shft, pi + 1);
  22633. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22634. pi += 1;
  22635. if (pi === min) {
  22636. if (closePath) {
  22637. indices.push(pi, pi + shft, idx[p]);
  22638. indices.push(idx[p] + shft, idx[p], pi + shft);
  22639. t3 = idx[p];
  22640. t4 = idx[p] + shft;
  22641. }
  22642. p++;
  22643. if (p === lg.length - 1) {
  22644. shft = idx[0] - idx[p];
  22645. l1 = lg[p] - 1;
  22646. l2 = lg[0] - 1;
  22647. }
  22648. else {
  22649. shft = idx[p + 1] - idx[p];
  22650. l1 = lg[p] - 1;
  22651. l2 = lg[p + 1] - 1;
  22652. }
  22653. pi = idx[p];
  22654. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22655. }
  22656. }
  22657. // normals
  22658. VertexData.ComputeNormals(positions, indices, normals);
  22659. // sides
  22660. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22661. // Result
  22662. var vertexData = new VertexData();
  22663. vertexData.indices = indices;
  22664. vertexData.positions = positions;
  22665. vertexData.normals = normals;
  22666. vertexData.uvs = uvs;
  22667. return vertexData;
  22668. };
  22669. VertexData.CreateBox = function (size, sideOrientation) {
  22670. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22671. var normalsSource = [
  22672. new BABYLON.Vector3(0, 0, 1),
  22673. new BABYLON.Vector3(0, 0, -1),
  22674. new BABYLON.Vector3(1, 0, 0),
  22675. new BABYLON.Vector3(-1, 0, 0),
  22676. new BABYLON.Vector3(0, 1, 0),
  22677. new BABYLON.Vector3(0, -1, 0)
  22678. ];
  22679. var indices = [];
  22680. var positions = [];
  22681. var normals = [];
  22682. var uvs = [];
  22683. size = size || 1;
  22684. for (var index = 0; index < normalsSource.length; index++) {
  22685. var normal = normalsSource[index];
  22686. // Get two vectors perpendicular to the face normal and to each other.
  22687. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22688. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22689. // Six indices (two triangles) per face.
  22690. var verticesLength = positions.length / 3;
  22691. indices.push(verticesLength);
  22692. indices.push(verticesLength + 1);
  22693. indices.push(verticesLength + 2);
  22694. indices.push(verticesLength);
  22695. indices.push(verticesLength + 2);
  22696. indices.push(verticesLength + 3);
  22697. // Four vertices per face.
  22698. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22699. positions.push(vertex.x, vertex.y, vertex.z);
  22700. normals.push(normal.x, normal.y, normal.z);
  22701. uvs.push(1.0, 1.0);
  22702. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22703. positions.push(vertex.x, vertex.y, vertex.z);
  22704. normals.push(normal.x, normal.y, normal.z);
  22705. uvs.push(0.0, 1.0);
  22706. vertex = normal.add(side1).add(side2).scale(size / 2);
  22707. positions.push(vertex.x, vertex.y, vertex.z);
  22708. normals.push(normal.x, normal.y, normal.z);
  22709. uvs.push(0.0, 0.0);
  22710. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22711. positions.push(vertex.x, vertex.y, vertex.z);
  22712. normals.push(normal.x, normal.y, normal.z);
  22713. uvs.push(1.0, 0.0);
  22714. }
  22715. // sides
  22716. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22717. // Result
  22718. var vertexData = new VertexData();
  22719. vertexData.indices = indices;
  22720. vertexData.positions = positions;
  22721. vertexData.normals = normals;
  22722. vertexData.uvs = uvs;
  22723. return vertexData;
  22724. };
  22725. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22726. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22727. segments = segments || 32;
  22728. diameter = diameter || 1;
  22729. var radius = diameter / 2;
  22730. var totalZRotationSteps = 2 + segments;
  22731. var totalYRotationSteps = 2 * totalZRotationSteps;
  22732. var indices = [];
  22733. var positions = [];
  22734. var normals = [];
  22735. var uvs = [];
  22736. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22737. var normalizedZ = zRotationStep / totalZRotationSteps;
  22738. var angleZ = (normalizedZ * Math.PI);
  22739. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22740. var normalizedY = yRotationStep / totalYRotationSteps;
  22741. var angleY = normalizedY * Math.PI * 2;
  22742. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22743. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22744. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22745. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22746. var vertex = complete.scale(radius);
  22747. var normal = BABYLON.Vector3.Normalize(vertex);
  22748. positions.push(vertex.x, vertex.y, vertex.z);
  22749. normals.push(normal.x, normal.y, normal.z);
  22750. uvs.push(normalizedZ, normalizedY);
  22751. }
  22752. if (zRotationStep > 0) {
  22753. var verticesCount = positions.length / 3;
  22754. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22755. indices.push((firstIndex));
  22756. indices.push((firstIndex + 1));
  22757. indices.push(firstIndex + totalYRotationSteps + 1);
  22758. indices.push((firstIndex + totalYRotationSteps + 1));
  22759. indices.push((firstIndex + 1));
  22760. indices.push((firstIndex + totalYRotationSteps + 2));
  22761. }
  22762. }
  22763. }
  22764. // Sides
  22765. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22766. // Result
  22767. var vertexData = new VertexData();
  22768. vertexData.indices = indices;
  22769. vertexData.positions = positions;
  22770. vertexData.normals = normals;
  22771. vertexData.uvs = uvs;
  22772. return vertexData;
  22773. };
  22774. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22775. if (subdivisions === void 0) { subdivisions = 1; }
  22776. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22777. var radiusTop = diameterTop / 2;
  22778. var radiusBottom = diameterBottom / 2;
  22779. var indices = [];
  22780. var positions = [];
  22781. var normals = [];
  22782. var uvs = [];
  22783. height = height || 1;
  22784. diameterTop = diameterTop || 0.5;
  22785. diameterBottom = diameterBottom || 1;
  22786. tessellation = tessellation || 16;
  22787. subdivisions = subdivisions || 1;
  22788. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22789. var getCircleVector = function (i) {
  22790. var angle = (i * 2.0 * Math.PI / tessellation);
  22791. var dx = Math.cos(angle);
  22792. var dz = Math.sin(angle);
  22793. return new BABYLON.Vector3(dx, 0, dz);
  22794. };
  22795. var createCylinderCap = function (isTop) {
  22796. var radius = isTop ? radiusTop : radiusBottom;
  22797. if (radius === 0) {
  22798. return;
  22799. }
  22800. var vbase = positions.length / 3;
  22801. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22802. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22803. if (!isTop) {
  22804. offset.scaleInPlace(-1);
  22805. textureScale.x = -textureScale.x;
  22806. }
  22807. for (var i = 0; i < tessellation; i++) {
  22808. var circleVector = getCircleVector(i);
  22809. var position = circleVector.scale(radius).add(offset);
  22810. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22811. positions.push(position.x, position.y, position.z);
  22812. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22813. }
  22814. for (i = 0; i < tessellation - 2; i++) {
  22815. if (!isTop) {
  22816. indices.push(vbase);
  22817. indices.push(vbase + (i + 2) % tessellation);
  22818. indices.push(vbase + (i + 1) % tessellation);
  22819. }
  22820. else {
  22821. indices.push(vbase);
  22822. indices.push(vbase + (i + 1) % tessellation);
  22823. indices.push(vbase + (i + 2) % tessellation);
  22824. }
  22825. }
  22826. };
  22827. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22828. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22829. var stride = tessellation + 1;
  22830. for (var i = 0; i <= tessellation; i++) {
  22831. var circleVector = getCircleVector(i);
  22832. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22833. var position, radius = radiusBottom;
  22834. for (var s = 0; s <= subdivisions; s++) {
  22835. // Update variables
  22836. position = circleVector.scale(radius);
  22837. position.addInPlace(base.add(offset.scale(s)));
  22838. textureCoordinate.y += 1 / subdivisions;
  22839. radius += (radiusTop - radiusBottom) / subdivisions;
  22840. // Push in arrays
  22841. positions.push(position.x, position.y, position.z);
  22842. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22843. }
  22844. }
  22845. subdivisions += 1;
  22846. for (s = 0; s < subdivisions - 1; s++) {
  22847. for (i = 0; i <= tessellation; i++) {
  22848. indices.push(i * subdivisions + s);
  22849. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22850. indices.push(i * subdivisions + (s + 1));
  22851. indices.push(i * subdivisions + (s + 1));
  22852. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22853. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22854. }
  22855. }
  22856. // Create flat triangle fan caps to seal the top and bottom.
  22857. createCylinderCap(true);
  22858. createCylinderCap(false);
  22859. // Normals
  22860. VertexData.ComputeNormals(positions, indices, normals);
  22861. // Sides
  22862. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22863. // Result
  22864. var vertexData = new VertexData();
  22865. vertexData.indices = indices;
  22866. vertexData.positions = positions;
  22867. vertexData.normals = normals;
  22868. vertexData.uvs = uvs;
  22869. return vertexData;
  22870. };
  22871. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22872. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22873. var indices = [];
  22874. var positions = [];
  22875. var normals = [];
  22876. var uvs = [];
  22877. diameter = diameter || 1;
  22878. thickness = thickness || 0.5;
  22879. tessellation = tessellation || 16;
  22880. var stride = tessellation + 1;
  22881. for (var i = 0; i <= tessellation; i++) {
  22882. var u = i / tessellation;
  22883. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22884. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22885. for (var j = 0; j <= tessellation; j++) {
  22886. var v = 1 - j / tessellation;
  22887. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22888. var dx = Math.cos(innerAngle);
  22889. var dy = Math.sin(innerAngle);
  22890. // Create a vertex.
  22891. var normal = new BABYLON.Vector3(dx, dy, 0);
  22892. var position = normal.scale(thickness / 2);
  22893. var textureCoordinate = new BABYLON.Vector2(u, v);
  22894. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22895. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22896. positions.push(position.x, position.y, position.z);
  22897. normals.push(normal.x, normal.y, normal.z);
  22898. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22899. // And create indices for two triangles.
  22900. var nextI = (i + 1) % stride;
  22901. var nextJ = (j + 1) % stride;
  22902. indices.push(i * stride + j);
  22903. indices.push(i * stride + nextJ);
  22904. indices.push(nextI * stride + j);
  22905. indices.push(i * stride + nextJ);
  22906. indices.push(nextI * stride + nextJ);
  22907. indices.push(nextI * stride + j);
  22908. }
  22909. }
  22910. // Sides
  22911. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22912. // Result
  22913. var vertexData = new VertexData();
  22914. vertexData.indices = indices;
  22915. vertexData.positions = positions;
  22916. vertexData.normals = normals;
  22917. vertexData.uvs = uvs;
  22918. return vertexData;
  22919. };
  22920. VertexData.CreateLines = function (points) {
  22921. var indices = [];
  22922. var positions = [];
  22923. for (var index = 0; index < points.length; index++) {
  22924. positions.push(points[index].x, points[index].y, points[index].z);
  22925. if (index > 0) {
  22926. indices.push(index - 1);
  22927. indices.push(index);
  22928. }
  22929. }
  22930. // Result
  22931. var vertexData = new VertexData();
  22932. vertexData.indices = indices;
  22933. vertexData.positions = positions;
  22934. return vertexData;
  22935. };
  22936. VertexData.CreateGround = function (width, height, subdivisions) {
  22937. var indices = [];
  22938. var positions = [];
  22939. var normals = [];
  22940. var uvs = [];
  22941. var row, col;
  22942. width = width || 1;
  22943. height = height || 1;
  22944. subdivisions = subdivisions || 1;
  22945. for (row = 0; row <= subdivisions; row++) {
  22946. for (col = 0; col <= subdivisions; col++) {
  22947. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22948. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22949. positions.push(position.x, position.y, position.z);
  22950. normals.push(normal.x, normal.y, normal.z);
  22951. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22952. }
  22953. }
  22954. for (row = 0; row < subdivisions; row++) {
  22955. for (col = 0; col < subdivisions; col++) {
  22956. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22957. indices.push(col + 1 + row * (subdivisions + 1));
  22958. indices.push(col + row * (subdivisions + 1));
  22959. indices.push(col + (row + 1) * (subdivisions + 1));
  22960. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22961. indices.push(col + row * (subdivisions + 1));
  22962. }
  22963. }
  22964. // Result
  22965. var vertexData = new VertexData();
  22966. vertexData.indices = indices;
  22967. vertexData.positions = positions;
  22968. vertexData.normals = normals;
  22969. vertexData.uvs = uvs;
  22970. return vertexData;
  22971. };
  22972. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22973. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22974. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22975. var indices = [];
  22976. var positions = [];
  22977. var normals = [];
  22978. var uvs = [];
  22979. var row, col, tileRow, tileCol;
  22980. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22981. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22982. precision.w = (precision.w < 1) ? 1 : precision.w;
  22983. precision.h = (precision.h < 1) ? 1 : precision.h;
  22984. var tileSize = {
  22985. 'w': (xmax - xmin) / subdivisions.w,
  22986. 'h': (zmax - zmin) / subdivisions.h
  22987. };
  22988. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22989. // Indices
  22990. var base = positions.length / 3;
  22991. var rowLength = precision.w + 1;
  22992. for (row = 0; row < precision.h; row++) {
  22993. for (col = 0; col < precision.w; col++) {
  22994. var square = [
  22995. base + col + row * rowLength,
  22996. base + (col + 1) + row * rowLength,
  22997. base + (col + 1) + (row + 1) * rowLength,
  22998. base + col + (row + 1) * rowLength
  22999. ];
  23000. indices.push(square[1]);
  23001. indices.push(square[2]);
  23002. indices.push(square[3]);
  23003. indices.push(square[0]);
  23004. indices.push(square[1]);
  23005. indices.push(square[3]);
  23006. }
  23007. }
  23008. // Position, normals and uvs
  23009. var position = BABYLON.Vector3.Zero();
  23010. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23011. for (row = 0; row <= precision.h; row++) {
  23012. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23013. for (col = 0; col <= precision.w; col++) {
  23014. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23015. position.y = 0;
  23016. positions.push(position.x, position.y, position.z);
  23017. normals.push(normal.x, normal.y, normal.z);
  23018. uvs.push(col / precision.w, row / precision.h);
  23019. }
  23020. }
  23021. }
  23022. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23023. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23024. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23025. }
  23026. }
  23027. // Result
  23028. var vertexData = new VertexData();
  23029. vertexData.indices = indices;
  23030. vertexData.positions = positions;
  23031. vertexData.normals = normals;
  23032. vertexData.uvs = uvs;
  23033. return vertexData;
  23034. };
  23035. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  23036. var indices = [];
  23037. var positions = [];
  23038. var normals = [];
  23039. var uvs = [];
  23040. var row, col;
  23041. for (row = 0; row <= subdivisions; row++) {
  23042. for (col = 0; col <= subdivisions; col++) {
  23043. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23044. // Compute height
  23045. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  23046. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  23047. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  23048. var r = buffer[pos] / 255.0;
  23049. var g = buffer[pos + 1] / 255.0;
  23050. var b = buffer[pos + 2] / 255.0;
  23051. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23052. position.y = minHeight + (maxHeight - minHeight) * gradient;
  23053. // Add vertex
  23054. positions.push(position.x, position.y, position.z);
  23055. normals.push(0, 0, 0);
  23056. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23057. }
  23058. }
  23059. for (row = 0; row < subdivisions; row++) {
  23060. for (col = 0; col < subdivisions; col++) {
  23061. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23062. indices.push(col + 1 + row * (subdivisions + 1));
  23063. indices.push(col + row * (subdivisions + 1));
  23064. indices.push(col + (row + 1) * (subdivisions + 1));
  23065. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23066. indices.push(col + row * (subdivisions + 1));
  23067. }
  23068. }
  23069. // Normals
  23070. VertexData.ComputeNormals(positions, indices, normals);
  23071. // Result
  23072. var vertexData = new VertexData();
  23073. vertexData.indices = indices;
  23074. vertexData.positions = positions;
  23075. vertexData.normals = normals;
  23076. vertexData.uvs = uvs;
  23077. return vertexData;
  23078. };
  23079. VertexData.CreatePlane = function (size, sideOrientation) {
  23080. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23081. var indices = [];
  23082. var positions = [];
  23083. var normals = [];
  23084. var uvs = [];
  23085. size = size || 1;
  23086. // Vertices
  23087. var halfSize = size / 2.0;
  23088. positions.push(-halfSize, -halfSize, 0);
  23089. normals.push(0, 0, -1.0);
  23090. uvs.push(0.0, 0.0);
  23091. positions.push(halfSize, -halfSize, 0);
  23092. normals.push(0, 0, -1.0);
  23093. uvs.push(1.0, 0.0);
  23094. positions.push(halfSize, halfSize, 0);
  23095. normals.push(0, 0, -1.0);
  23096. uvs.push(1.0, 1.0);
  23097. positions.push(-halfSize, halfSize, 0);
  23098. normals.push(0, 0, -1.0);
  23099. uvs.push(0.0, 1.0);
  23100. // Indices
  23101. indices.push(0);
  23102. indices.push(1);
  23103. indices.push(2);
  23104. indices.push(0);
  23105. indices.push(2);
  23106. indices.push(3);
  23107. // Sides
  23108. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23109. // Result
  23110. var vertexData = new VertexData();
  23111. vertexData.indices = indices;
  23112. vertexData.positions = positions;
  23113. vertexData.normals = normals;
  23114. vertexData.uvs = uvs;
  23115. return vertexData;
  23116. };
  23117. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  23118. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23119. var positions = [];
  23120. var indices = [];
  23121. var normals = [];
  23122. var uvs = [];
  23123. // positions and uvs
  23124. positions.push(0, 0, 0); // disc center first
  23125. uvs.push(0.5, 0.5);
  23126. var step = Math.PI * 2 / tessellation;
  23127. for (var a = 0; a < Math.PI * 2; a += step) {
  23128. var x = Math.cos(a);
  23129. var y = Math.sin(a);
  23130. var u = (x + 1) / 2;
  23131. var v = (1 - y) / 2;
  23132. positions.push(radius * x, radius * y, 0);
  23133. uvs.push(u, v);
  23134. }
  23135. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23136. uvs.push(uvs[2], uvs[3]);
  23137. //indices
  23138. var vertexNb = positions.length / 3;
  23139. for (var i = 1; i < vertexNb - 1; i++) {
  23140. indices.push(i + 1, 0, i);
  23141. }
  23142. // result
  23143. VertexData.ComputeNormals(positions, indices, normals);
  23144. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23145. var vertexData = new VertexData();
  23146. vertexData.indices = indices;
  23147. vertexData.positions = positions;
  23148. vertexData.normals = normals;
  23149. vertexData.uvs = uvs;
  23150. return vertexData;
  23151. };
  23152. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23153. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  23154. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23155. var indices = [];
  23156. var positions = [];
  23157. var normals = [];
  23158. var uvs = [];
  23159. radius = radius || 2;
  23160. tube = tube || 0.5;
  23161. radialSegments = radialSegments || 32;
  23162. tubularSegments = tubularSegments || 32;
  23163. p = p || 2;
  23164. q = q || 3;
  23165. // Helper
  23166. var getPos = function (angle) {
  23167. var cu = Math.cos(angle);
  23168. var su = Math.sin(angle);
  23169. var quOverP = q / p * angle;
  23170. var cs = Math.cos(quOverP);
  23171. var tx = radius * (2 + cs) * 0.5 * cu;
  23172. var ty = radius * (2 + cs) * su * 0.5;
  23173. var tz = radius * Math.sin(quOverP) * 0.5;
  23174. return new BABYLON.Vector3(tx, ty, tz);
  23175. };
  23176. for (var i = 0; i <= radialSegments; i++) {
  23177. var modI = i % radialSegments;
  23178. var u = modI / radialSegments * 2 * p * Math.PI;
  23179. var p1 = getPos(u);
  23180. var p2 = getPos(u + 0.01);
  23181. var tang = p2.subtract(p1);
  23182. var n = p2.add(p1);
  23183. var bitan = BABYLON.Vector3.Cross(tang, n);
  23184. n = BABYLON.Vector3.Cross(bitan, tang);
  23185. bitan.normalize();
  23186. n.normalize();
  23187. for (var j = 0; j < tubularSegments; j++) {
  23188. var modJ = j % tubularSegments;
  23189. var v = modJ / tubularSegments * 2 * Math.PI;
  23190. var cx = -tube * Math.cos(v);
  23191. var cy = tube * Math.sin(v);
  23192. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23193. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23194. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23195. uvs.push(i / radialSegments);
  23196. uvs.push(j / tubularSegments);
  23197. }
  23198. }
  23199. for (i = 0; i < radialSegments; i++) {
  23200. for (j = 0; j < tubularSegments; j++) {
  23201. var jNext = (j + 1) % tubularSegments;
  23202. var a = i * tubularSegments + j;
  23203. var b = (i + 1) * tubularSegments + j;
  23204. var c = (i + 1) * tubularSegments + jNext;
  23205. var d = i * tubularSegments + jNext;
  23206. indices.push(d);
  23207. indices.push(b);
  23208. indices.push(a);
  23209. indices.push(d);
  23210. indices.push(c);
  23211. indices.push(b);
  23212. }
  23213. }
  23214. // Normals
  23215. VertexData.ComputeNormals(positions, indices, normals);
  23216. // Sides
  23217. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23218. // Result
  23219. var vertexData = new VertexData();
  23220. vertexData.indices = indices;
  23221. vertexData.positions = positions;
  23222. vertexData.normals = normals;
  23223. vertexData.uvs = uvs;
  23224. return vertexData;
  23225. };
  23226. // Tools
  23227. /**
  23228. * @param {any} - positions (number[] or Float32Array)
  23229. * @param {any} - indices (number[] or Uint16Array)
  23230. * @param {any} - normals (number[] or Float32Array)
  23231. */
  23232. VertexData.ComputeNormals = function (positions, indices, normals) {
  23233. var positionVectors = [];
  23234. var facesOfVertices = [];
  23235. var index;
  23236. for (index = 0; index < positions.length; index += 3) {
  23237. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  23238. positionVectors.push(vector3);
  23239. facesOfVertices.push([]);
  23240. }
  23241. // Compute normals
  23242. var facesNormals = [];
  23243. for (index = 0; index < indices.length / 3; index++) {
  23244. var i1 = indices[index * 3];
  23245. var i2 = indices[index * 3 + 1];
  23246. var i3 = indices[index * 3 + 2];
  23247. var p1 = positionVectors[i1];
  23248. var p2 = positionVectors[i2];
  23249. var p3 = positionVectors[i3];
  23250. var p1p2 = p1.subtract(p2);
  23251. var p3p2 = p3.subtract(p2);
  23252. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23253. facesOfVertices[i1].push(index);
  23254. facesOfVertices[i2].push(index);
  23255. facesOfVertices[i3].push(index);
  23256. }
  23257. for (index = 0; index < positionVectors.length; index++) {
  23258. var faces = facesOfVertices[index];
  23259. var normal = BABYLON.Vector3.Zero();
  23260. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  23261. normal.addInPlace(facesNormals[faces[faceIndex]]);
  23262. }
  23263. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  23264. normals[index * 3] = normal.x;
  23265. normals[index * 3 + 1] = normal.y;
  23266. normals[index * 3 + 2] = normal.z;
  23267. }
  23268. };
  23269. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23270. var li = indices.length;
  23271. var ln = normals.length;
  23272. var i;
  23273. var n;
  23274. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23275. switch (sideOrientation) {
  23276. case BABYLON.Mesh.FRONTSIDE:
  23277. break;
  23278. case BABYLON.Mesh.BACKSIDE:
  23279. var tmp;
  23280. for (i = 0; i < li; i += 3) {
  23281. tmp = indices[i];
  23282. indices[i] = indices[i + 2];
  23283. indices[i + 2] = tmp;
  23284. }
  23285. for (n = 0; n < ln; n++) {
  23286. normals[n] = -normals[n];
  23287. }
  23288. break;
  23289. case BABYLON.Mesh.DOUBLESIDE:
  23290. // positions
  23291. var lp = positions.length;
  23292. var l = lp / 3;
  23293. for (var p = 0; p < lp; p++) {
  23294. positions[lp + p] = positions[p];
  23295. }
  23296. for (i = 0; i < li; i += 3) {
  23297. indices[i + li] = indices[i + 2] + l;
  23298. indices[i + 1 + li] = indices[i + 1] + l;
  23299. indices[i + 2 + li] = indices[i] + l;
  23300. }
  23301. for (n = 0; n < ln; n++) {
  23302. normals[ln + n] = -normals[n];
  23303. }
  23304. // uvs
  23305. var lu = uvs.length;
  23306. for (var u = 0; u < lu; u++) {
  23307. uvs[u + lu] = uvs[u];
  23308. }
  23309. break;
  23310. }
  23311. };
  23312. return VertexData;
  23313. })();
  23314. BABYLON.VertexData = VertexData;
  23315. })(BABYLON || (BABYLON = {}));
  23316. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23317. var BABYLON;
  23318. (function (BABYLON) {
  23319. var buildCamera = function (that, name) {
  23320. that._leftCamera.isIntermediate = true;
  23321. that.subCameras.push(that._leftCamera);
  23322. that.subCameras.push(that._rightCamera);
  23323. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23324. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23325. that._anaglyphPostProcess.onApply = function (effect) {
  23326. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23327. };
  23328. that._update();
  23329. };
  23330. var AnaglyphArcRotateCamera = (function (_super) {
  23331. __extends(AnaglyphArcRotateCamera, _super);
  23332. // ANY
  23333. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23334. _super.call(this, name, alpha, beta, radius, target, scene);
  23335. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23336. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23337. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23338. buildCamera(this, name);
  23339. }
  23340. AnaglyphArcRotateCamera.prototype._update = function () {
  23341. this._updateCamera(this._leftCamera);
  23342. this._updateCamera(this._rightCamera);
  23343. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23344. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23345. _super.prototype._update.call(this);
  23346. };
  23347. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23348. camera.beta = this.beta;
  23349. camera.radius = this.radius;
  23350. camera.minZ = this.minZ;
  23351. camera.maxZ = this.maxZ;
  23352. camera.fov = this.fov;
  23353. camera.target = this.target;
  23354. };
  23355. return AnaglyphArcRotateCamera;
  23356. })(BABYLON.ArcRotateCamera);
  23357. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23358. var AnaglyphFreeCamera = (function (_super) {
  23359. __extends(AnaglyphFreeCamera, _super);
  23360. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23361. _super.call(this, name, position, scene);
  23362. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23363. this._transformMatrix = new BABYLON.Matrix();
  23364. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23365. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23366. buildCamera(this, name);
  23367. }
  23368. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23369. var target = this.getTarget();
  23370. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23371. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23372. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23373. };
  23374. AnaglyphFreeCamera.prototype._update = function () {
  23375. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23376. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23377. this._updateCamera(this._leftCamera);
  23378. this._updateCamera(this._rightCamera);
  23379. _super.prototype._update.call(this);
  23380. };
  23381. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23382. camera.minZ = this.minZ;
  23383. camera.maxZ = this.maxZ;
  23384. camera.fov = this.fov;
  23385. camera.viewport = this.viewport;
  23386. camera.setTarget(this.getTarget());
  23387. };
  23388. return AnaglyphFreeCamera;
  23389. })(BABYLON.FreeCamera);
  23390. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23391. })(BABYLON || (BABYLON = {}));
  23392. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23393. var BABYLON;
  23394. (function (BABYLON) {
  23395. var AnaglyphPostProcess = (function (_super) {
  23396. __extends(AnaglyphPostProcess, _super);
  23397. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23398. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23399. }
  23400. return AnaglyphPostProcess;
  23401. })(BABYLON.PostProcess);
  23402. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23403. })(BABYLON || (BABYLON = {}));
  23404. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23405. (function (BABYLON) {
  23406. var Tags = (function () {
  23407. function Tags() {
  23408. }
  23409. Tags.EnableFor = function (obj) {
  23410. obj._tags = obj._tags || {};
  23411. obj.hasTags = function () {
  23412. return Tags.HasTags(obj);
  23413. };
  23414. obj.addTags = function (tagsString) {
  23415. return Tags.AddTagsTo(obj, tagsString);
  23416. };
  23417. obj.removeTags = function (tagsString) {
  23418. return Tags.RemoveTagsFrom(obj, tagsString);
  23419. };
  23420. obj.matchesTagsQuery = function (tagsQuery) {
  23421. return Tags.MatchesQuery(obj, tagsQuery);
  23422. };
  23423. };
  23424. Tags.DisableFor = function (obj) {
  23425. delete obj._tags;
  23426. delete obj.hasTags;
  23427. delete obj.addTags;
  23428. delete obj.removeTags;
  23429. delete obj.matchesTagsQuery;
  23430. };
  23431. Tags.HasTags = function (obj) {
  23432. if (!obj._tags) {
  23433. return false;
  23434. }
  23435. return !BABYLON.Tools.IsEmpty(obj._tags);
  23436. };
  23437. Tags.GetTags = function (obj) {
  23438. if (!obj._tags) {
  23439. return null;
  23440. }
  23441. return obj._tags;
  23442. };
  23443. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23444. // a tag cannot start with '||', '&&', and '!'
  23445. // it cannot contain whitespaces
  23446. Tags.AddTagsTo = function (obj, tagsString) {
  23447. if (!tagsString) {
  23448. return;
  23449. }
  23450. var tags = tagsString.split(" ");
  23451. for (var t in tags) {
  23452. Tags._AddTagTo(obj, tags[t]);
  23453. }
  23454. };
  23455. Tags._AddTagTo = function (obj, tag) {
  23456. tag = tag.trim();
  23457. if (tag === "" || tag === "true" || tag === "false") {
  23458. return;
  23459. }
  23460. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23461. return;
  23462. }
  23463. Tags.EnableFor(obj);
  23464. obj._tags[tag] = true;
  23465. };
  23466. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23467. if (!Tags.HasTags(obj)) {
  23468. return;
  23469. }
  23470. var tags = tagsString.split(" ");
  23471. for (var t in tags) {
  23472. Tags._RemoveTagFrom(obj, tags[t]);
  23473. }
  23474. };
  23475. Tags._RemoveTagFrom = function (obj, tag) {
  23476. delete obj._tags[tag];
  23477. };
  23478. Tags.MatchesQuery = function (obj, tagsQuery) {
  23479. if (tagsQuery === undefined) {
  23480. return true;
  23481. }
  23482. if (tagsQuery === "") {
  23483. return Tags.HasTags(obj);
  23484. }
  23485. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23486. };
  23487. return Tags;
  23488. })();
  23489. BABYLON.Tags = Tags;
  23490. })(BABYLON || (BABYLON = {}));
  23491. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23492. (function (BABYLON) {
  23493. var Internals;
  23494. (function (Internals) {
  23495. var AndOrNotEvaluator = (function () {
  23496. function AndOrNotEvaluator() {
  23497. }
  23498. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23499. if (!query.match(/\([^\(\)]*\)/g)) {
  23500. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23501. }
  23502. else {
  23503. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23504. // remove parenthesis
  23505. r = r.slice(1, r.length - 1);
  23506. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23507. });
  23508. }
  23509. if (query === "true") {
  23510. return true;
  23511. }
  23512. if (query === "false") {
  23513. return false;
  23514. }
  23515. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23516. };
  23517. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23518. evaluateCallback = evaluateCallback || (function (r) {
  23519. return r === "true" ? true : false;
  23520. });
  23521. var result;
  23522. var or = parenthesisContent.split("||");
  23523. for (var i in or) {
  23524. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23525. var and = ori.split("&&");
  23526. if (and.length > 1) {
  23527. for (var j = 0; j < and.length; ++j) {
  23528. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23529. if (andj !== "true" && andj !== "false") {
  23530. if (andj[0] === "!") {
  23531. result = !evaluateCallback(andj.substring(1));
  23532. }
  23533. else {
  23534. result = evaluateCallback(andj);
  23535. }
  23536. }
  23537. else {
  23538. result = andj === "true" ? true : false;
  23539. }
  23540. if (!result) {
  23541. ori = "false";
  23542. break;
  23543. }
  23544. }
  23545. }
  23546. if (result || ori === "true") {
  23547. result = true;
  23548. break;
  23549. }
  23550. // result equals false (or undefined)
  23551. if (ori !== "true" && ori !== "false") {
  23552. if (ori[0] === "!") {
  23553. result = !evaluateCallback(ori.substring(1));
  23554. }
  23555. else {
  23556. result = evaluateCallback(ori);
  23557. }
  23558. }
  23559. else {
  23560. result = ori === "true" ? true : false;
  23561. }
  23562. }
  23563. // the whole parenthesis scope is replaced by 'true' or 'false'
  23564. return result ? "true" : "false";
  23565. };
  23566. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23567. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23568. // remove whitespaces
  23569. r = r.replace(/[\s]/g, function () { return ""; });
  23570. return r.length % 2 ? "!" : "";
  23571. });
  23572. booleanString = booleanString.trim();
  23573. if (booleanString === "!true") {
  23574. booleanString = "false";
  23575. }
  23576. else if (booleanString === "!false") {
  23577. booleanString = "true";
  23578. }
  23579. return booleanString;
  23580. };
  23581. return AndOrNotEvaluator;
  23582. })();
  23583. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23584. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23585. })(BABYLON || (BABYLON = {}));
  23586. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23587. (function (BABYLON) {
  23588. var PostProcessRenderPass = (function () {
  23589. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23590. this._enabled = true;
  23591. this._refCount = 0;
  23592. this._name = name;
  23593. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23594. this.setRenderList(renderList);
  23595. this._renderTexture.onBeforeRender = beforeRender;
  23596. this._renderTexture.onAfterRender = afterRender;
  23597. this._scene = scene;
  23598. this._renderList = renderList;
  23599. }
  23600. // private
  23601. PostProcessRenderPass.prototype._incRefCount = function () {
  23602. if (this._refCount === 0) {
  23603. this._scene.customRenderTargets.push(this._renderTexture);
  23604. }
  23605. return ++this._refCount;
  23606. };
  23607. PostProcessRenderPass.prototype._decRefCount = function () {
  23608. this._refCount--;
  23609. if (this._refCount <= 0) {
  23610. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23611. }
  23612. return this._refCount;
  23613. };
  23614. PostProcessRenderPass.prototype._update = function () {
  23615. this.setRenderList(this._renderList);
  23616. };
  23617. // public
  23618. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23619. this._renderTexture.renderList = renderList;
  23620. };
  23621. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23622. return this._renderTexture;
  23623. };
  23624. return PostProcessRenderPass;
  23625. })();
  23626. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23627. })(BABYLON || (BABYLON = {}));
  23628. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23629. (function (BABYLON) {
  23630. var PostProcessRenderEffect = (function () {
  23631. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23632. this._engine = engine;
  23633. this._name = name;
  23634. this._singleInstance = singleInstance || true;
  23635. this._getPostProcess = getPostProcess;
  23636. this._cameras = [];
  23637. this._indicesForCamera = [];
  23638. this._postProcesses = {};
  23639. this._renderPasses = {};
  23640. this._renderEffectAsPasses = {};
  23641. }
  23642. PostProcessRenderEffect.prototype._update = function () {
  23643. for (var renderPassName in this._renderPasses) {
  23644. this._renderPasses[renderPassName]._update();
  23645. }
  23646. };
  23647. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23648. this._renderPasses[renderPass._name] = renderPass;
  23649. this._linkParameters();
  23650. };
  23651. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23652. delete this._renderPasses[renderPass._name];
  23653. this._linkParameters();
  23654. };
  23655. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23656. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23657. this._linkParameters();
  23658. };
  23659. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23660. for (var renderPassName in this._renderPasses) {
  23661. if (renderPassName === passName) {
  23662. return this._renderPasses[passName];
  23663. }
  23664. }
  23665. };
  23666. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23667. this._renderPasses = {};
  23668. this._linkParameters();
  23669. };
  23670. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23671. var cameraKey;
  23672. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23673. for (var i = 0; i < _cam.length; i++) {
  23674. var camera = _cam[i];
  23675. var cameraName = camera.name;
  23676. if (this._singleInstance) {
  23677. cameraKey = 0;
  23678. }
  23679. else {
  23680. cameraKey = cameraName;
  23681. }
  23682. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23683. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23684. if (!this._indicesForCamera[cameraName]) {
  23685. this._indicesForCamera[cameraName] = [];
  23686. }
  23687. this._indicesForCamera[cameraName].push(index);
  23688. if (this._cameras.indexOf(camera) === -1) {
  23689. this._cameras[cameraName] = camera;
  23690. }
  23691. for (var passName in this._renderPasses) {
  23692. this._renderPasses[passName]._incRefCount();
  23693. }
  23694. }
  23695. this._linkParameters();
  23696. };
  23697. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23698. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23699. for (var i = 0; i < _cam.length; i++) {
  23700. var camera = _cam[i];
  23701. var cameraName = camera.name;
  23702. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23703. var index = this._cameras.indexOf(cameraName);
  23704. this._indicesForCamera.splice(index, 1);
  23705. this._cameras.splice(index, 1);
  23706. for (var passName in this._renderPasses) {
  23707. this._renderPasses[passName]._decRefCount();
  23708. }
  23709. }
  23710. };
  23711. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23712. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23713. for (var i = 0; i < _cam.length; i++) {
  23714. var camera = _cam[i];
  23715. var cameraName = camera.name;
  23716. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23717. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23718. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23719. }
  23720. }
  23721. for (var passName in this._renderPasses) {
  23722. this._renderPasses[passName]._incRefCount();
  23723. }
  23724. }
  23725. };
  23726. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23727. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23728. for (var i = 0; i < _cam.length; i++) {
  23729. var camera = _cam[i];
  23730. var cameraName = camera.Name;
  23731. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23732. for (var passName in this._renderPasses) {
  23733. this._renderPasses[passName]._decRefCount();
  23734. }
  23735. }
  23736. };
  23737. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23738. if (this._singleInstance) {
  23739. return this._postProcesses[0];
  23740. }
  23741. else {
  23742. return this._postProcesses[camera.name];
  23743. }
  23744. };
  23745. PostProcessRenderEffect.prototype._linkParameters = function () {
  23746. var _this = this;
  23747. for (var index in this._postProcesses) {
  23748. if (this.applyParameters) {
  23749. this.applyParameters(this._postProcesses[index]);
  23750. }
  23751. this._postProcesses[index].onBeforeRender = function (effect) {
  23752. _this._linkTextures(effect);
  23753. };
  23754. }
  23755. };
  23756. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23757. for (var renderPassName in this._renderPasses) {
  23758. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23759. }
  23760. for (var renderEffectName in this._renderEffectAsPasses) {
  23761. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23762. }
  23763. };
  23764. return PostProcessRenderEffect;
  23765. })();
  23766. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23767. })(BABYLON || (BABYLON = {}));
  23768. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23769. (function (BABYLON) {
  23770. var PostProcessRenderPipeline = (function () {
  23771. function PostProcessRenderPipeline(engine, name) {
  23772. this._engine = engine;
  23773. this._name = name;
  23774. this._renderEffects = {};
  23775. this._renderEffectsForIsolatedPass = {};
  23776. this._cameras = [];
  23777. }
  23778. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23779. this._renderEffects[renderEffect._name] = renderEffect;
  23780. };
  23781. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23782. var renderEffects = this._renderEffects[renderEffectName];
  23783. if (!renderEffects) {
  23784. return;
  23785. }
  23786. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23787. };
  23788. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23789. var renderEffects = this._renderEffects[renderEffectName];
  23790. if (!renderEffects) {
  23791. return;
  23792. }
  23793. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23794. };
  23795. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23796. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23797. var indicesToDelete = [];
  23798. for (var i = 0; i < _cam.length; i++) {
  23799. var camera = _cam[i];
  23800. var cameraName = camera.name;
  23801. if (this._cameras.indexOf(camera) === -1) {
  23802. this._cameras[cameraName] = camera;
  23803. }
  23804. else if (unique) {
  23805. indicesToDelete.push(i);
  23806. }
  23807. }
  23808. for (var i = 0; i < indicesToDelete.length; i++) {
  23809. cameras.splice(indicesToDelete[i], 1);
  23810. }
  23811. for (var renderEffectName in this._renderEffects) {
  23812. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23813. }
  23814. };
  23815. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23816. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23817. for (var renderEffectName in this._renderEffects) {
  23818. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23819. }
  23820. for (var i = 0; i < _cam.length; i++) {
  23821. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23822. }
  23823. };
  23824. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23825. var _this = this;
  23826. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23827. var pass = null;
  23828. for (var renderEffectName in this._renderEffects) {
  23829. pass = this._renderEffects[renderEffectName].getPass(passName);
  23830. if (pass != null) {
  23831. break;
  23832. }
  23833. }
  23834. if (pass === null) {
  23835. return;
  23836. }
  23837. for (var renderEffectName in this._renderEffects) {
  23838. this._renderEffects[renderEffectName]._disable(_cam);
  23839. }
  23840. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23841. for (var i = 0; i < _cam.length; i++) {
  23842. var camera = _cam[i];
  23843. var cameraName = camera.name;
  23844. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23845. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23846. });
  23847. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23848. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23849. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23850. }
  23851. };
  23852. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23853. var _this = this;
  23854. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23855. for (var i = 0; i < _cam.length; i++) {
  23856. var camera = _cam[i];
  23857. var cameraName = camera.name;
  23858. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23859. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23860. });
  23861. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23862. }
  23863. for (var renderEffectName in this._renderEffects) {
  23864. this._renderEffects[renderEffectName]._enable(_cam);
  23865. }
  23866. };
  23867. PostProcessRenderPipeline.prototype._update = function () {
  23868. for (var renderEffectName in this._renderEffects) {
  23869. this._renderEffects[renderEffectName]._update();
  23870. }
  23871. for (var i = 0; i < this._cameras.length; i++) {
  23872. var cameraName = this._cameras[i].name;
  23873. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23874. this._renderEffectsForIsolatedPass[cameraName]._update();
  23875. }
  23876. }
  23877. };
  23878. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23879. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23880. return PostProcessRenderPipeline;
  23881. })();
  23882. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23883. })(BABYLON || (BABYLON = {}));
  23884. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23885. (function (BABYLON) {
  23886. var PostProcessRenderPipelineManager = (function () {
  23887. function PostProcessRenderPipelineManager() {
  23888. this._renderPipelines = {};
  23889. }
  23890. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23891. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23892. };
  23893. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23894. var renderPipeline = this._renderPipelines[renderPipelineName];
  23895. if (!renderPipeline) {
  23896. return;
  23897. }
  23898. renderPipeline._attachCameras(cameras, unique);
  23899. };
  23900. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23901. var renderPipeline = this._renderPipelines[renderPipelineName];
  23902. if (!renderPipeline) {
  23903. return;
  23904. }
  23905. renderPipeline._detachCameras(cameras);
  23906. };
  23907. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23908. var renderPipeline = this._renderPipelines[renderPipelineName];
  23909. if (!renderPipeline) {
  23910. return;
  23911. }
  23912. renderPipeline._enableEffect(renderEffectName, cameras);
  23913. };
  23914. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23915. var renderPipeline = this._renderPipelines[renderPipelineName];
  23916. if (!renderPipeline) {
  23917. return;
  23918. }
  23919. renderPipeline._disableEffect(renderEffectName, cameras);
  23920. };
  23921. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23922. var renderPipeline = this._renderPipelines[renderPipelineName];
  23923. if (!renderPipeline) {
  23924. return;
  23925. }
  23926. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23927. };
  23928. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23929. var renderPipeline = this._renderPipelines[renderPipelineName];
  23930. if (!renderPipeline) {
  23931. return;
  23932. }
  23933. renderPipeline._disableDisplayOnlyPass(cameras);
  23934. };
  23935. PostProcessRenderPipelineManager.prototype.update = function () {
  23936. for (var renderPipelineName in this._renderPipelines) {
  23937. this._renderPipelines[renderPipelineName]._update();
  23938. }
  23939. };
  23940. return PostProcessRenderPipelineManager;
  23941. })();
  23942. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23943. })(BABYLON || (BABYLON = {}));
  23944. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23945. var BABYLON;
  23946. (function (BABYLON) {
  23947. var DisplayPassPostProcess = (function (_super) {
  23948. __extends(DisplayPassPostProcess, _super);
  23949. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23950. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23951. }
  23952. return DisplayPassPostProcess;
  23953. })(BABYLON.PostProcess);
  23954. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23955. })(BABYLON || (BABYLON = {}));
  23956. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23957. (function (BABYLON) {
  23958. var BoundingBoxRenderer = (function () {
  23959. function BoundingBoxRenderer(scene) {
  23960. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23961. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23962. this.showBackLines = true;
  23963. this.renderList = new BABYLON.SmartArray(32);
  23964. this._scene = scene;
  23965. }
  23966. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23967. if (this._colorShader) {
  23968. return;
  23969. }
  23970. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23971. attributes: ["position"],
  23972. uniforms: ["worldViewProjection", "color"]
  23973. });
  23974. var engine = this._scene.getEngine();
  23975. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23976. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23977. 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]);
  23978. };
  23979. BoundingBoxRenderer.prototype.reset = function () {
  23980. this.renderList.reset();
  23981. };
  23982. BoundingBoxRenderer.prototype.render = function () {
  23983. if (this.renderList.length === 0) {
  23984. return;
  23985. }
  23986. this._prepareRessources();
  23987. if (!this._colorShader.isReady()) {
  23988. return;
  23989. }
  23990. var engine = this._scene.getEngine();
  23991. engine.setDepthWrite(false);
  23992. this._colorShader._preBind();
  23993. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23994. var boundingBox = this.renderList.data[boundingBoxIndex];
  23995. var min = boundingBox.minimum;
  23996. var max = boundingBox.maximum;
  23997. var diff = max.subtract(min);
  23998. var median = min.add(diff.scale(0.5));
  23999. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  24000. // VBOs
  24001. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  24002. if (this.showBackLines) {
  24003. // Back
  24004. engine.setDepthFunctionToGreaterOrEqual();
  24005. this._scene.resetCachedMaterial();
  24006. this._colorShader.setColor4("color", this.backColor.toColor4());
  24007. this._colorShader.bind(worldMatrix);
  24008. // Draw order
  24009. engine.draw(false, 0, 24);
  24010. }
  24011. // Front
  24012. engine.setDepthFunctionToLess();
  24013. this._scene.resetCachedMaterial();
  24014. this._colorShader.setColor4("color", this.frontColor.toColor4());
  24015. this._colorShader.bind(worldMatrix);
  24016. // Draw order
  24017. engine.draw(false, 0, 24);
  24018. }
  24019. this._colorShader.unbind();
  24020. engine.setDepthFunctionToLessOrEqual();
  24021. engine.setDepthWrite(true);
  24022. };
  24023. BoundingBoxRenderer.prototype.dispose = function () {
  24024. if (!this._colorShader) {
  24025. return;
  24026. }
  24027. this._colorShader.dispose();
  24028. this._vb.dispose();
  24029. this._scene.getEngine()._releaseBuffer(this._ib);
  24030. };
  24031. return BoundingBoxRenderer;
  24032. })();
  24033. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  24034. })(BABYLON || (BABYLON = {}));
  24035. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  24036. (function (BABYLON) {
  24037. var Internals;
  24038. (function (Internals) {
  24039. /*
  24040. * Based on jsTGALoader - Javascript loader for TGA file
  24041. * By Vincent Thibault
  24042. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  24043. */
  24044. var TGATools = (function () {
  24045. function TGATools() {
  24046. }
  24047. TGATools.GetTGAHeader = function (data) {
  24048. var offset = 0;
  24049. var header = {
  24050. id_length: data[offset++],
  24051. colormap_type: data[offset++],
  24052. image_type: data[offset++],
  24053. colormap_index: data[offset++] | data[offset++] << 8,
  24054. colormap_length: data[offset++] | data[offset++] << 8,
  24055. colormap_size: data[offset++],
  24056. origin: [
  24057. data[offset++] | data[offset++] << 8,
  24058. data[offset++] | data[offset++] << 8
  24059. ],
  24060. width: data[offset++] | data[offset++] << 8,
  24061. height: data[offset++] | data[offset++] << 8,
  24062. pixel_size: data[offset++],
  24063. flags: data[offset++]
  24064. };
  24065. return header;
  24066. };
  24067. TGATools.UploadContent = function (gl, data) {
  24068. // Not enough data to contain header ?
  24069. if (data.length < 19) {
  24070. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  24071. return;
  24072. }
  24073. // Read Header
  24074. var offset = 18;
  24075. var header = TGATools.GetTGAHeader(data);
  24076. // Assume it's a valid Targa file.
  24077. if (header.id_length + offset > data.length) {
  24078. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  24079. return;
  24080. }
  24081. // Skip not needed data
  24082. offset += header.id_length;
  24083. var use_rle = false;
  24084. var use_pal = false;
  24085. var use_rgb = false;
  24086. var use_grey = false;
  24087. switch (header.image_type) {
  24088. case TGATools._TYPE_RLE_INDEXED:
  24089. use_rle = true;
  24090. case TGATools._TYPE_INDEXED:
  24091. use_pal = true;
  24092. break;
  24093. case TGATools._TYPE_RLE_RGB:
  24094. use_rle = true;
  24095. case TGATools._TYPE_RGB:
  24096. use_rgb = true;
  24097. break;
  24098. case TGATools._TYPE_RLE_GREY:
  24099. use_rle = true;
  24100. case TGATools._TYPE_GREY:
  24101. use_grey = true;
  24102. break;
  24103. }
  24104. var pixel_data;
  24105. var numAlphaBits = header.flags & 0xf;
  24106. var pixel_size = header.pixel_size >> 3;
  24107. var pixel_total = header.width * header.height * pixel_size;
  24108. // Read palettes
  24109. var palettes;
  24110. if (use_pal) {
  24111. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  24112. }
  24113. // Read LRE
  24114. if (use_rle) {
  24115. pixel_data = new Uint8Array(pixel_total);
  24116. var c, count, i;
  24117. var localOffset = 0;
  24118. var pixels = new Uint8Array(pixel_size);
  24119. while (offset < pixel_total && localOffset < pixel_total) {
  24120. c = data[offset++];
  24121. count = (c & 0x7f) + 1;
  24122. // RLE pixels
  24123. if (c & 0x80) {
  24124. for (i = 0; i < pixel_size; ++i) {
  24125. pixels[i] = data[offset++];
  24126. }
  24127. for (i = 0; i < count; ++i) {
  24128. pixel_data.set(pixels, localOffset + i * pixel_size);
  24129. }
  24130. localOffset += pixel_size * count;
  24131. }
  24132. else {
  24133. count *= pixel_size;
  24134. for (i = 0; i < count; ++i) {
  24135. pixel_data[localOffset + i] = data[offset++];
  24136. }
  24137. localOffset += count;
  24138. }
  24139. }
  24140. }
  24141. else {
  24142. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  24143. }
  24144. // Load to texture
  24145. var x_start, y_start, x_step, y_step, y_end, x_end;
  24146. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  24147. default:
  24148. case TGATools._ORIGIN_UL:
  24149. x_start = 0;
  24150. x_step = 1;
  24151. x_end = header.width;
  24152. y_start = 0;
  24153. y_step = 1;
  24154. y_end = header.height;
  24155. break;
  24156. case TGATools._ORIGIN_BL:
  24157. x_start = 0;
  24158. x_step = 1;
  24159. x_end = header.width;
  24160. y_start = header.height - 1;
  24161. y_step = -1;
  24162. y_end = -1;
  24163. break;
  24164. case TGATools._ORIGIN_UR:
  24165. x_start = header.width - 1;
  24166. x_step = -1;
  24167. x_end = -1;
  24168. y_start = 0;
  24169. y_step = 1;
  24170. y_end = header.height;
  24171. break;
  24172. case TGATools._ORIGIN_BR:
  24173. x_start = header.width - 1;
  24174. x_step = -1;
  24175. x_end = -1;
  24176. y_start = header.height - 1;
  24177. y_step = -1;
  24178. y_end = -1;
  24179. break;
  24180. }
  24181. // Load the specify method
  24182. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  24183. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  24184. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  24185. };
  24186. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24187. var image = pixel_data, colormap = palettes;
  24188. var width = header.width, height = header.height;
  24189. var color, i = 0, x, y;
  24190. var imageData = new Uint8Array(width * height * 4);
  24191. for (y = y_start; y !== y_end; y += y_step) {
  24192. for (x = x_start; x !== x_end; x += x_step, i++) {
  24193. color = image[i];
  24194. imageData[(x + width * y) * 4 + 3] = 255;
  24195. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  24196. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  24197. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  24198. }
  24199. }
  24200. return imageData;
  24201. };
  24202. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24203. var image = pixel_data;
  24204. var width = header.width, height = header.height;
  24205. var color, i = 0, x, y;
  24206. var imageData = new Uint8Array(width * height * 4);
  24207. for (y = y_start; y !== y_end; y += y_step) {
  24208. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24209. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  24210. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  24211. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  24212. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  24213. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  24214. }
  24215. }
  24216. return imageData;
  24217. };
  24218. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24219. var image = pixel_data;
  24220. var width = header.width, height = header.height;
  24221. var i = 0, x, y;
  24222. var imageData = new Uint8Array(width * height * 4);
  24223. for (y = y_start; y !== y_end; y += y_step) {
  24224. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  24225. imageData[(x + width * y) * 4 + 3] = 255;
  24226. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24227. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24228. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24229. }
  24230. }
  24231. return imageData;
  24232. };
  24233. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24234. var image = pixel_data;
  24235. var width = header.width, height = header.height;
  24236. var i = 0, x, y;
  24237. var imageData = new Uint8Array(width * height * 4);
  24238. for (y = y_start; y !== y_end; y += y_step) {
  24239. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  24240. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24241. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24242. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24243. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  24244. }
  24245. }
  24246. return imageData;
  24247. };
  24248. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24249. var image = pixel_data;
  24250. var width = header.width, height = header.height;
  24251. var color, i = 0, x, y;
  24252. var imageData = new Uint8Array(width * height * 4);
  24253. for (y = y_start; y !== y_end; y += y_step) {
  24254. for (x = x_start; x !== x_end; x += x_step, i++) {
  24255. color = image[i];
  24256. imageData[(x + width * y) * 4 + 0] = color;
  24257. imageData[(x + width * y) * 4 + 1] = color;
  24258. imageData[(x + width * y) * 4 + 2] = color;
  24259. imageData[(x + width * y) * 4 + 3] = 255;
  24260. }
  24261. }
  24262. return imageData;
  24263. };
  24264. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24265. var image = pixel_data;
  24266. var width = header.width, height = header.height;
  24267. var i = 0, x, y;
  24268. var imageData = new Uint8Array(width * height * 4);
  24269. for (y = y_start; y !== y_end; y += y_step) {
  24270. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24271. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  24272. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  24273. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24274. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  24275. }
  24276. }
  24277. return imageData;
  24278. };
  24279. TGATools._TYPE_NO_DATA = 0;
  24280. TGATools._TYPE_INDEXED = 1;
  24281. TGATools._TYPE_RGB = 2;
  24282. TGATools._TYPE_GREY = 3;
  24283. TGATools._TYPE_RLE_INDEXED = 9;
  24284. TGATools._TYPE_RLE_RGB = 10;
  24285. TGATools._TYPE_RLE_GREY = 11;
  24286. TGATools._ORIGIN_MASK = 0x30;
  24287. TGATools._ORIGIN_SHIFT = 0x04;
  24288. TGATools._ORIGIN_BL = 0x00;
  24289. TGATools._ORIGIN_BR = 0x01;
  24290. TGATools._ORIGIN_UL = 0x02;
  24291. TGATools._ORIGIN_UR = 0x03;
  24292. return TGATools;
  24293. })();
  24294. Internals.TGATools = TGATools;
  24295. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24296. })(BABYLON || (BABYLON = {}));
  24297. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24298. (function (BABYLON) {
  24299. var Internals;
  24300. (function (Internals) {
  24301. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24302. // All values and structures referenced from:
  24303. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24304. var DDS_MAGIC = 0x20534444;
  24305. 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;
  24306. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24307. 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;
  24308. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24309. function FourCCToInt32(value) {
  24310. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24311. }
  24312. function Int32ToFourCC(value) {
  24313. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24314. }
  24315. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24316. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24317. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24318. var headerLengthInt = 31; // The header length in 32 bit ints
  24319. // Offsets into the header array
  24320. var off_magic = 0;
  24321. var off_size = 1;
  24322. var off_flags = 2;
  24323. var off_height = 3;
  24324. var off_width = 4;
  24325. var off_mipmapCount = 7;
  24326. var off_pfFlags = 20;
  24327. var off_pfFourCC = 21;
  24328. var off_RGBbpp = 22;
  24329. var off_RMask = 23;
  24330. var off_GMask = 24;
  24331. var off_BMask = 25;
  24332. var off_AMask = 26;
  24333. var off_caps1 = 27;
  24334. var off_caps2 = 28;
  24335. ;
  24336. var DDSTools = (function () {
  24337. function DDSTools() {
  24338. }
  24339. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24340. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24341. var mipmapCount = 1;
  24342. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24343. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24344. }
  24345. return {
  24346. width: header[off_width],
  24347. height: header[off_height],
  24348. mipmapCount: mipmapCount,
  24349. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24350. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24351. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24352. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24353. };
  24354. };
  24355. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24356. var byteArray = new Uint8Array(dataLength);
  24357. var srcData = new Uint8Array(arrayBuffer);
  24358. var index = 0;
  24359. for (var y = height - 1; y >= 0; y--) {
  24360. for (var x = 0; x < width; x++) {
  24361. var srcPos = dataOffset + (x + y * width) * 4;
  24362. byteArray[index + 2] = srcData[srcPos];
  24363. byteArray[index + 1] = srcData[srcPos + 1];
  24364. byteArray[index] = srcData[srcPos + 2];
  24365. byteArray[index + 3] = srcData[srcPos + 3];
  24366. index += 4;
  24367. }
  24368. }
  24369. return byteArray;
  24370. };
  24371. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24372. var byteArray = new Uint8Array(dataLength);
  24373. var srcData = new Uint8Array(arrayBuffer);
  24374. var index = 0;
  24375. for (var y = height - 1; y >= 0; y--) {
  24376. for (var x = 0; x < width; x++) {
  24377. var srcPos = dataOffset + (x + y * width) * 3;
  24378. byteArray[index + 2] = srcData[srcPos];
  24379. byteArray[index + 1] = srcData[srcPos + 1];
  24380. byteArray[index] = srcData[srcPos + 2];
  24381. index += 3;
  24382. }
  24383. }
  24384. return byteArray;
  24385. };
  24386. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24387. var byteArray = new Uint8Array(dataLength);
  24388. var srcData = new Uint8Array(arrayBuffer);
  24389. var index = 0;
  24390. for (var y = height - 1; y >= 0; y--) {
  24391. for (var x = 0; x < width; x++) {
  24392. var srcPos = dataOffset + (x + y * width);
  24393. byteArray[index] = srcData[srcPos];
  24394. index++;
  24395. }
  24396. }
  24397. return byteArray;
  24398. };
  24399. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24400. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24401. if (header[off_magic] != DDS_MAGIC) {
  24402. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24403. return;
  24404. }
  24405. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24406. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24407. return;
  24408. }
  24409. if (info.isFourCC) {
  24410. fourCC = header[off_pfFourCC];
  24411. switch (fourCC) {
  24412. case FOURCC_DXT1:
  24413. blockBytes = 8;
  24414. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24415. break;
  24416. case FOURCC_DXT3:
  24417. blockBytes = 16;
  24418. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24419. break;
  24420. case FOURCC_DXT5:
  24421. blockBytes = 16;
  24422. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24423. break;
  24424. default:
  24425. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24426. return;
  24427. }
  24428. }
  24429. mipmapCount = 1;
  24430. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24431. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24432. }
  24433. var bpp = header[off_RGBbpp];
  24434. for (var face = 0; face < faces; face++) {
  24435. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24436. width = header[off_width];
  24437. height = header[off_height];
  24438. dataOffset = header[off_size] + 4;
  24439. for (i = 0; i < mipmapCount; ++i) {
  24440. if (info.isRGB) {
  24441. if (bpp == 24) {
  24442. dataLength = width * height * 3;
  24443. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24444. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24445. }
  24446. else {
  24447. dataLength = width * height * 4;
  24448. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24449. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24450. }
  24451. }
  24452. else if (info.isLuminance) {
  24453. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24454. var unpaddedRowSize = width;
  24455. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24456. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24457. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24458. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24459. }
  24460. else {
  24461. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24462. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24463. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24464. }
  24465. dataOffset += dataLength;
  24466. width *= 0.5;
  24467. height *= 0.5;
  24468. width = Math.max(1.0, width);
  24469. height = Math.max(1.0, height);
  24470. }
  24471. }
  24472. };
  24473. return DDSTools;
  24474. })();
  24475. Internals.DDSTools = DDSTools;
  24476. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24477. })(BABYLON || (BABYLON = {}));
  24478. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24479. (function (BABYLON) {
  24480. var SmartArray = (function () {
  24481. function SmartArray(capacity) {
  24482. this.length = 0;
  24483. this._duplicateId = 0;
  24484. this.data = new Array(capacity);
  24485. this._id = SmartArray._GlobalId++;
  24486. }
  24487. SmartArray.prototype.push = function (value) {
  24488. this.data[this.length++] = value;
  24489. if (this.length > this.data.length) {
  24490. this.data.length *= 2;
  24491. }
  24492. if (!value.__smartArrayFlags) {
  24493. value.__smartArrayFlags = {};
  24494. }
  24495. value.__smartArrayFlags[this._id] = this._duplicateId;
  24496. };
  24497. SmartArray.prototype.pushNoDuplicate = function (value) {
  24498. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24499. return;
  24500. }
  24501. this.push(value);
  24502. };
  24503. SmartArray.prototype.sort = function (compareFn) {
  24504. this.data.sort(compareFn);
  24505. };
  24506. SmartArray.prototype.reset = function () {
  24507. this.length = 0;
  24508. this._duplicateId++;
  24509. };
  24510. SmartArray.prototype.concat = function (array) {
  24511. if (array.length === 0) {
  24512. return;
  24513. }
  24514. if (this.length + array.length > this.data.length) {
  24515. this.data.length = (this.length + array.length) * 2;
  24516. }
  24517. for (var index = 0; index < array.length; index++) {
  24518. this.data[this.length++] = (array.data || array)[index];
  24519. }
  24520. };
  24521. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24522. if (array.length === 0) {
  24523. return;
  24524. }
  24525. if (this.length + array.length > this.data.length) {
  24526. this.data.length = (this.length + array.length) * 2;
  24527. }
  24528. for (var index = 0; index < array.length; index++) {
  24529. var item = (array.data || array)[index];
  24530. this.pushNoDuplicate(item);
  24531. }
  24532. };
  24533. SmartArray.prototype.indexOf = function (value) {
  24534. var position = this.data.indexOf(value);
  24535. if (position >= this.length) {
  24536. return -1;
  24537. }
  24538. return position;
  24539. };
  24540. // Statics
  24541. SmartArray._GlobalId = 0;
  24542. return SmartArray;
  24543. })();
  24544. BABYLON.SmartArray = SmartArray;
  24545. })(BABYLON || (BABYLON = {}));
  24546. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24547. (function (BABYLON) {
  24548. var CannonJSPlugin = (function () {
  24549. function CannonJSPlugin() {
  24550. this._registeredMeshes = [];
  24551. this._physicsMaterials = [];
  24552. this.updateBodyPosition = function (mesh) {
  24553. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24554. var registeredMesh = this._registeredMeshes[index];
  24555. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24556. var body = registeredMesh.body;
  24557. var center = mesh.getBoundingInfo().boundingBox.center;
  24558. body.position.set(center.x, center.z, center.y);
  24559. body.quaternion.x = mesh.rotationQuaternion.x;
  24560. body.quaternion.z = mesh.rotationQuaternion.y;
  24561. body.quaternion.y = mesh.rotationQuaternion.z;
  24562. body.quaternion.w = -mesh.rotationQuaternion.w;
  24563. return;
  24564. }
  24565. }
  24566. };
  24567. }
  24568. CannonJSPlugin.prototype.initialize = function (iterations) {
  24569. if (iterations === void 0) { iterations = 10; }
  24570. this._world = new CANNON.World();
  24571. this._world.broadphase = new CANNON.NaiveBroadphase();
  24572. this._world.solver.iterations = iterations;
  24573. };
  24574. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24575. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24576. };
  24577. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24578. this._world.step(delta);
  24579. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24580. var registeredMesh = this._registeredMeshes[index];
  24581. if (registeredMesh.isChild) {
  24582. continue;
  24583. }
  24584. // Body position
  24585. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24586. var deltaPos = registeredMesh.delta;
  24587. if (deltaPos) {
  24588. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24589. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24590. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24591. }
  24592. else {
  24593. registeredMesh.mesh.position.x = bodyX;
  24594. registeredMesh.mesh.position.y = bodyZ;
  24595. registeredMesh.mesh.position.z = bodyY;
  24596. }
  24597. if (!registeredMesh.mesh.rotationQuaternion) {
  24598. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24599. }
  24600. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24601. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24602. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24603. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24604. }
  24605. };
  24606. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24607. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24608. };
  24609. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24610. this.unregisterMesh(mesh);
  24611. mesh.computeWorldMatrix(true);
  24612. switch (impostor) {
  24613. case BABYLON.PhysicsEngine.SphereImpostor:
  24614. var bbox = mesh.getBoundingInfo().boundingBox;
  24615. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24616. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24617. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24618. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24619. case BABYLON.PhysicsEngine.BoxImpostor:
  24620. bbox = mesh.getBoundingInfo().boundingBox;
  24621. var min = bbox.minimumWorld;
  24622. var max = bbox.maximumWorld;
  24623. var box = max.subtract(min).scale(0.5);
  24624. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24625. case BABYLON.PhysicsEngine.PlaneImpostor:
  24626. return this._createPlane(mesh, options);
  24627. case BABYLON.PhysicsEngine.MeshImpostor:
  24628. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24629. var rawFaces = mesh.getIndices();
  24630. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24631. }
  24632. return null;
  24633. };
  24634. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24635. var shape = new CANNON.Sphere(radius);
  24636. if (!options) {
  24637. return shape;
  24638. }
  24639. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24640. };
  24641. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24642. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24643. if (!options) {
  24644. return shape;
  24645. }
  24646. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24647. };
  24648. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24649. var shape = new CANNON.Plane();
  24650. if (!options) {
  24651. return shape;
  24652. }
  24653. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24654. };
  24655. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24656. var verts = [], faces = [];
  24657. mesh.computeWorldMatrix(true);
  24658. for (var i = 0; i < rawVerts.length; i += 3) {
  24659. var transformed = BABYLON.Vector3.Zero();
  24660. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24661. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24662. }
  24663. for (var j = 0; j < rawFaces.length; j += 3) {
  24664. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24665. }
  24666. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24667. if (!options) {
  24668. return shape;
  24669. }
  24670. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24671. };
  24672. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24673. var index;
  24674. var mat;
  24675. for (index = 0; index < this._physicsMaterials.length; index++) {
  24676. mat = this._physicsMaterials[index];
  24677. if (mat.friction === friction && mat.restitution === restitution) {
  24678. return mat;
  24679. }
  24680. }
  24681. var currentMat = new CANNON.Material();
  24682. currentMat.friction = friction;
  24683. currentMat.restitution = restitution;
  24684. this._physicsMaterials.push(currentMat);
  24685. for (index = 0; index < this._physicsMaterials.length; index++) {
  24686. mat = this._physicsMaterials[index];
  24687. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24688. contactMaterial.contactEquationStiffness = 1e10;
  24689. contactMaterial.contactEquationRegularizationTime = 10;
  24690. this._world.addContactMaterial(contactMaterial);
  24691. }
  24692. return currentMat;
  24693. };
  24694. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24695. var initialRotation = null;
  24696. if (mesh.rotationQuaternion) {
  24697. initialRotation = mesh.rotationQuaternion.clone();
  24698. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24699. }
  24700. // The delta between the mesh position and the mesh bounding box center
  24701. var bbox = mesh.getBoundingInfo().boundingBox;
  24702. var deltaPosition = mesh.position.subtract(bbox.center);
  24703. var material = this._addMaterial(friction, restitution);
  24704. var body = new CANNON.RigidBody(mass, shape, material);
  24705. if (initialRotation) {
  24706. body.quaternion.x = initialRotation.x;
  24707. body.quaternion.z = initialRotation.y;
  24708. body.quaternion.y = initialRotation.z;
  24709. body.quaternion.w = -initialRotation.w;
  24710. }
  24711. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24712. this._world.add(body);
  24713. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24714. return body;
  24715. };
  24716. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24717. var compoundShape = new CANNON.Compound();
  24718. for (var index = 0; index < parts.length; index++) {
  24719. var mesh = parts[index].mesh;
  24720. var shape = this.registerMesh(mesh, parts[index].impostor);
  24721. if (index == 0) {
  24722. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24723. }
  24724. else {
  24725. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24726. }
  24727. }
  24728. var initialMesh = parts[0].mesh;
  24729. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24730. body.parts = parts;
  24731. return body;
  24732. };
  24733. CannonJSPlugin.prototype._unbindBody = function (body) {
  24734. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24735. var registeredMesh = this._registeredMeshes[index];
  24736. if (registeredMesh.body === body) {
  24737. registeredMesh.body = null;
  24738. registeredMesh.delta = 0;
  24739. }
  24740. }
  24741. };
  24742. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24743. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24744. var registeredMesh = this._registeredMeshes[index];
  24745. if (registeredMesh.mesh === mesh) {
  24746. // Remove body
  24747. if (registeredMesh.body) {
  24748. this._world.remove(registeredMesh.body);
  24749. this._unbindBody(registeredMesh.body);
  24750. }
  24751. this._registeredMeshes.splice(index, 1);
  24752. return;
  24753. }
  24754. }
  24755. };
  24756. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24757. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24758. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24759. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24760. var registeredMesh = this._registeredMeshes[index];
  24761. if (registeredMesh.mesh === mesh) {
  24762. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24763. return;
  24764. }
  24765. }
  24766. };
  24767. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24768. var body1 = null, body2 = null;
  24769. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24770. var registeredMesh = this._registeredMeshes[index];
  24771. if (registeredMesh.mesh === mesh1) {
  24772. body1 = registeredMesh.body;
  24773. }
  24774. else if (registeredMesh.mesh === mesh2) {
  24775. body2 = registeredMesh.body;
  24776. }
  24777. }
  24778. if (!body1 || !body2) {
  24779. return false;
  24780. }
  24781. 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));
  24782. this._world.addConstraint(constraint);
  24783. return true;
  24784. };
  24785. CannonJSPlugin.prototype.dispose = function () {
  24786. while (this._registeredMeshes.length) {
  24787. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24788. }
  24789. };
  24790. CannonJSPlugin.prototype.isSupported = function () {
  24791. return window.CANNON !== undefined;
  24792. };
  24793. return CannonJSPlugin;
  24794. })();
  24795. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24796. })(BABYLON || (BABYLON = {}));
  24797. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24798. var BABYLON;
  24799. (function (BABYLON) {
  24800. var Condition = (function () {
  24801. function Condition(actionManager) {
  24802. this._actionManager = actionManager;
  24803. }
  24804. Condition.prototype.isValid = function () {
  24805. return true;
  24806. };
  24807. Condition.prototype._getProperty = function (propertyPath) {
  24808. return this._actionManager._getProperty(propertyPath);
  24809. };
  24810. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24811. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24812. };
  24813. return Condition;
  24814. })();
  24815. BABYLON.Condition = Condition;
  24816. var ValueCondition = (function (_super) {
  24817. __extends(ValueCondition, _super);
  24818. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24819. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24820. _super.call(this, actionManager);
  24821. this.propertyPath = propertyPath;
  24822. this.value = value;
  24823. this.operator = operator;
  24824. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24825. this._property = this._getProperty(this.propertyPath);
  24826. }
  24827. Object.defineProperty(ValueCondition, "IsEqual", {
  24828. get: function () {
  24829. return ValueCondition._IsEqual;
  24830. },
  24831. enumerable: true,
  24832. configurable: true
  24833. });
  24834. Object.defineProperty(ValueCondition, "IsDifferent", {
  24835. get: function () {
  24836. return ValueCondition._IsDifferent;
  24837. },
  24838. enumerable: true,
  24839. configurable: true
  24840. });
  24841. Object.defineProperty(ValueCondition, "IsGreater", {
  24842. get: function () {
  24843. return ValueCondition._IsGreater;
  24844. },
  24845. enumerable: true,
  24846. configurable: true
  24847. });
  24848. Object.defineProperty(ValueCondition, "IsLesser", {
  24849. get: function () {
  24850. return ValueCondition._IsLesser;
  24851. },
  24852. enumerable: true,
  24853. configurable: true
  24854. });
  24855. // Methods
  24856. ValueCondition.prototype.isValid = function () {
  24857. switch (this.operator) {
  24858. case ValueCondition.IsGreater:
  24859. return this._target[this._property] > this.value;
  24860. case ValueCondition.IsLesser:
  24861. return this._target[this._property] < this.value;
  24862. case ValueCondition.IsEqual:
  24863. case ValueCondition.IsDifferent:
  24864. var check;
  24865. if (this.value.equals) {
  24866. check = this.value.equals(this._target[this._property]);
  24867. }
  24868. else {
  24869. check = this.value === this._target[this._property];
  24870. }
  24871. return this.operator === ValueCondition.IsEqual ? check : !check;
  24872. }
  24873. return false;
  24874. };
  24875. // Statics
  24876. ValueCondition._IsEqual = 0;
  24877. ValueCondition._IsDifferent = 1;
  24878. ValueCondition._IsGreater = 2;
  24879. ValueCondition._IsLesser = 3;
  24880. return ValueCondition;
  24881. })(Condition);
  24882. BABYLON.ValueCondition = ValueCondition;
  24883. var PredicateCondition = (function (_super) {
  24884. __extends(PredicateCondition, _super);
  24885. function PredicateCondition(actionManager, predicate) {
  24886. _super.call(this, actionManager);
  24887. this.predicate = predicate;
  24888. }
  24889. PredicateCondition.prototype.isValid = function () {
  24890. return this.predicate();
  24891. };
  24892. return PredicateCondition;
  24893. })(Condition);
  24894. BABYLON.PredicateCondition = PredicateCondition;
  24895. var StateCondition = (function (_super) {
  24896. __extends(StateCondition, _super);
  24897. function StateCondition(actionManager, target, value) {
  24898. _super.call(this, actionManager);
  24899. this.value = value;
  24900. this._target = target;
  24901. }
  24902. // Methods
  24903. StateCondition.prototype.isValid = function () {
  24904. return this._target.state === this.value;
  24905. };
  24906. return StateCondition;
  24907. })(Condition);
  24908. BABYLON.StateCondition = StateCondition;
  24909. })(BABYLON || (BABYLON = {}));
  24910. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24911. (function (BABYLON) {
  24912. var Action = (function () {
  24913. function Action(triggerOptions, condition) {
  24914. this.triggerOptions = triggerOptions;
  24915. if (triggerOptions.parameter) {
  24916. this.trigger = triggerOptions.trigger;
  24917. this._triggerParameter = triggerOptions.parameter;
  24918. }
  24919. else {
  24920. this.trigger = triggerOptions;
  24921. }
  24922. this._nextActiveAction = this;
  24923. this._condition = condition;
  24924. }
  24925. // Methods
  24926. Action.prototype._prepare = function () {
  24927. };
  24928. Action.prototype.getTriggerParameter = function () {
  24929. return this._triggerParameter;
  24930. };
  24931. Action.prototype._executeCurrent = function (evt) {
  24932. if (this._nextActiveAction._condition) {
  24933. var condition = this._nextActiveAction._condition;
  24934. var currentRenderId = this._actionManager.getScene().getRenderId();
  24935. // We cache the current evaluation for the current frame
  24936. if (condition._evaluationId === currentRenderId) {
  24937. if (!condition._currentResult) {
  24938. return;
  24939. }
  24940. }
  24941. else {
  24942. condition._evaluationId = currentRenderId;
  24943. if (!condition.isValid()) {
  24944. condition._currentResult = false;
  24945. return;
  24946. }
  24947. condition._currentResult = true;
  24948. }
  24949. }
  24950. this._nextActiveAction.execute(evt);
  24951. if (this._nextActiveAction._child) {
  24952. if (!this._nextActiveAction._child._actionManager) {
  24953. this._nextActiveAction._child._actionManager = this._actionManager;
  24954. }
  24955. this._nextActiveAction = this._nextActiveAction._child;
  24956. }
  24957. else {
  24958. this._nextActiveAction = this;
  24959. }
  24960. };
  24961. Action.prototype.execute = function (evt) {
  24962. };
  24963. Action.prototype.then = function (action) {
  24964. this._child = action;
  24965. action._actionManager = this._actionManager;
  24966. action._prepare();
  24967. return action;
  24968. };
  24969. Action.prototype._getProperty = function (propertyPath) {
  24970. return this._actionManager._getProperty(propertyPath);
  24971. };
  24972. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24973. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24974. };
  24975. return Action;
  24976. })();
  24977. BABYLON.Action = Action;
  24978. })(BABYLON || (BABYLON = {}));
  24979. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24980. (function (BABYLON) {
  24981. /**
  24982. * ActionEvent is the event beint sent when an action is triggered.
  24983. */
  24984. var ActionEvent = (function () {
  24985. /**
  24986. * @constructor
  24987. * @param source The mesh that triggered the action.
  24988. * @param pointerX the X mouse cursor position at the time of the event
  24989. * @param pointerY the Y mouse cursor position at the time of the event
  24990. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24991. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24992. */
  24993. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24994. this.source = source;
  24995. this.pointerX = pointerX;
  24996. this.pointerY = pointerY;
  24997. this.meshUnderPointer = meshUnderPointer;
  24998. this.sourceEvent = sourceEvent;
  24999. }
  25000. /**
  25001. * Helper function to auto-create an ActionEvent from a source mesh.
  25002. * @param source the source mesh that triggered the event
  25003. * @param evt {Event} The original (browser) event
  25004. */
  25005. ActionEvent.CreateNew = function (source, evt) {
  25006. var scene = source.getScene();
  25007. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25008. };
  25009. /**
  25010. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25011. * @param scene the scene where the event occurred
  25012. * @param evt {Event} The original (browser) event
  25013. */
  25014. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25015. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25016. };
  25017. return ActionEvent;
  25018. })();
  25019. BABYLON.ActionEvent = ActionEvent;
  25020. /**
  25021. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25022. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25023. */
  25024. var ActionManager = (function () {
  25025. function ActionManager(scene) {
  25026. // Members
  25027. this.actions = new Array();
  25028. this._scene = scene;
  25029. scene._actionManagers.push(this);
  25030. }
  25031. Object.defineProperty(ActionManager, "NothingTrigger", {
  25032. get: function () {
  25033. return ActionManager._NothingTrigger;
  25034. },
  25035. enumerable: true,
  25036. configurable: true
  25037. });
  25038. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25039. get: function () {
  25040. return ActionManager._OnPickTrigger;
  25041. },
  25042. enumerable: true,
  25043. configurable: true
  25044. });
  25045. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25046. get: function () {
  25047. return ActionManager._OnLeftPickTrigger;
  25048. },
  25049. enumerable: true,
  25050. configurable: true
  25051. });
  25052. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25053. get: function () {
  25054. return ActionManager._OnRightPickTrigger;
  25055. },
  25056. enumerable: true,
  25057. configurable: true
  25058. });
  25059. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25060. get: function () {
  25061. return ActionManager._OnCenterPickTrigger;
  25062. },
  25063. enumerable: true,
  25064. configurable: true
  25065. });
  25066. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25067. get: function () {
  25068. return ActionManager._OnPointerOverTrigger;
  25069. },
  25070. enumerable: true,
  25071. configurable: true
  25072. });
  25073. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25074. get: function () {
  25075. return ActionManager._OnPointerOutTrigger;
  25076. },
  25077. enumerable: true,
  25078. configurable: true
  25079. });
  25080. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25081. get: function () {
  25082. return ActionManager._OnEveryFrameTrigger;
  25083. },
  25084. enumerable: true,
  25085. configurable: true
  25086. });
  25087. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25088. get: function () {
  25089. return ActionManager._OnIntersectionEnterTrigger;
  25090. },
  25091. enumerable: true,
  25092. configurable: true
  25093. });
  25094. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25095. get: function () {
  25096. return ActionManager._OnIntersectionExitTrigger;
  25097. },
  25098. enumerable: true,
  25099. configurable: true
  25100. });
  25101. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25102. get: function () {
  25103. return ActionManager._OnKeyDownTrigger;
  25104. },
  25105. enumerable: true,
  25106. configurable: true
  25107. });
  25108. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25109. get: function () {
  25110. return ActionManager._OnKeyUpTrigger;
  25111. },
  25112. enumerable: true,
  25113. configurable: true
  25114. });
  25115. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25116. get: function () {
  25117. return ActionManager._OnPickUpTrigger;
  25118. },
  25119. enumerable: true,
  25120. configurable: true
  25121. });
  25122. // Methods
  25123. ActionManager.prototype.dispose = function () {
  25124. var index = this._scene._actionManagers.indexOf(this);
  25125. if (index > -1) {
  25126. this._scene._actionManagers.splice(index, 1);
  25127. }
  25128. };
  25129. ActionManager.prototype.getScene = function () {
  25130. return this._scene;
  25131. };
  25132. /**
  25133. * Does this action manager handles actions of any of the given triggers
  25134. * @param {number[]} triggers - the triggers to be tested
  25135. * @return {boolean} whether one (or more) of the triggers is handeled
  25136. */
  25137. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25138. for (var index = 0; index < this.actions.length; index++) {
  25139. var action = this.actions[index];
  25140. if (triggers.indexOf(action.trigger) > -1) {
  25141. return true;
  25142. }
  25143. }
  25144. return false;
  25145. };
  25146. /**
  25147. * Does this action manager handles actions of a given trigger
  25148. * @param {number} trigger - the trigger to be tested
  25149. * @return {boolean} whether the trigger is handeled
  25150. */
  25151. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25152. for (var index = 0; index < this.actions.length; index++) {
  25153. var action = this.actions[index];
  25154. if (action.trigger === trigger) {
  25155. return true;
  25156. }
  25157. }
  25158. return false;
  25159. };
  25160. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25161. /**
  25162. * Does this action manager has pointer triggers
  25163. * @return {boolean} whether or not it has pointer triggers
  25164. */
  25165. get: function () {
  25166. for (var index = 0; index < this.actions.length; index++) {
  25167. var action = this.actions[index];
  25168. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25169. return true;
  25170. }
  25171. if (action.trigger == ActionManager._OnPickUpTrigger) {
  25172. return true;
  25173. }
  25174. }
  25175. return false;
  25176. },
  25177. enumerable: true,
  25178. configurable: true
  25179. });
  25180. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25181. /**
  25182. * Does this action manager has pick triggers
  25183. * @return {boolean} whether or not it has pick triggers
  25184. */
  25185. get: function () {
  25186. for (var index = 0; index < this.actions.length; index++) {
  25187. var action = this.actions[index];
  25188. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25189. return true;
  25190. }
  25191. }
  25192. return false;
  25193. },
  25194. enumerable: true,
  25195. configurable: true
  25196. });
  25197. /**
  25198. * Registers an action to this action manager
  25199. * @param {BABYLON.Action} action - the action to be registered
  25200. * @return {BABYLON.Action} the action amended (prepared) after registration
  25201. */
  25202. ActionManager.prototype.registerAction = function (action) {
  25203. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25204. if (this.getScene().actionManager !== this) {
  25205. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25206. return null;
  25207. }
  25208. }
  25209. this.actions.push(action);
  25210. action._actionManager = this;
  25211. action._prepare();
  25212. return action;
  25213. };
  25214. /**
  25215. * Process a specific trigger
  25216. * @param {number} trigger - the trigger to process
  25217. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25218. */
  25219. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25220. for (var index = 0; index < this.actions.length; index++) {
  25221. var action = this.actions[index];
  25222. if (action.trigger === trigger) {
  25223. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  25224. var parameter = action.getTriggerParameter();
  25225. if (parameter) {
  25226. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25227. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25228. if (actualkey !== parameter.toLowerCase()) {
  25229. continue;
  25230. }
  25231. }
  25232. }
  25233. action._executeCurrent(evt);
  25234. }
  25235. }
  25236. };
  25237. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25238. var properties = propertyPath.split(".");
  25239. for (var index = 0; index < properties.length - 1; index++) {
  25240. target = target[properties[index]];
  25241. }
  25242. return target;
  25243. };
  25244. ActionManager.prototype._getProperty = function (propertyPath) {
  25245. var properties = propertyPath.split(".");
  25246. return properties[properties.length - 1];
  25247. };
  25248. // Statics
  25249. ActionManager._NothingTrigger = 0;
  25250. ActionManager._OnPickTrigger = 1;
  25251. ActionManager._OnLeftPickTrigger = 2;
  25252. ActionManager._OnRightPickTrigger = 3;
  25253. ActionManager._OnCenterPickTrigger = 4;
  25254. ActionManager._OnPointerOverTrigger = 5;
  25255. ActionManager._OnPointerOutTrigger = 6;
  25256. ActionManager._OnEveryFrameTrigger = 7;
  25257. ActionManager._OnIntersectionEnterTrigger = 8;
  25258. ActionManager._OnIntersectionExitTrigger = 9;
  25259. ActionManager._OnKeyDownTrigger = 10;
  25260. ActionManager._OnKeyUpTrigger = 11;
  25261. ActionManager._OnPickUpTrigger = 12;
  25262. return ActionManager;
  25263. })();
  25264. BABYLON.ActionManager = ActionManager;
  25265. })(BABYLON || (BABYLON = {}));
  25266. //# sourceMappingURL=babylon.actionManager.js.map
  25267. var BABYLON;
  25268. (function (BABYLON) {
  25269. var InterpolateValueAction = (function (_super) {
  25270. __extends(InterpolateValueAction, _super);
  25271. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  25272. if (duration === void 0) { duration = 1000; }
  25273. _super.call(this, triggerOptions, condition);
  25274. this.propertyPath = propertyPath;
  25275. this.value = value;
  25276. this.duration = duration;
  25277. this.stopOtherAnimations = stopOtherAnimations;
  25278. this._target = target;
  25279. }
  25280. InterpolateValueAction.prototype._prepare = function () {
  25281. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25282. this._property = this._getProperty(this.propertyPath);
  25283. };
  25284. InterpolateValueAction.prototype.execute = function () {
  25285. var scene = this._actionManager.getScene();
  25286. var keys = [
  25287. {
  25288. frame: 0,
  25289. value: this._target[this._property]
  25290. },
  25291. {
  25292. frame: 100,
  25293. value: this.value
  25294. }
  25295. ];
  25296. var dataType;
  25297. if (typeof this.value === "number") {
  25298. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25299. }
  25300. else if (this.value instanceof BABYLON.Color3) {
  25301. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25302. }
  25303. else if (this.value instanceof BABYLON.Vector3) {
  25304. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25305. }
  25306. else if (this.value instanceof BABYLON.Matrix) {
  25307. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25308. }
  25309. else if (this.value instanceof BABYLON.Quaternion) {
  25310. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25311. }
  25312. else {
  25313. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25314. return;
  25315. }
  25316. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25317. animation.setKeys(keys);
  25318. if (this.stopOtherAnimations) {
  25319. scene.stopAnimation(this._target);
  25320. }
  25321. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25322. };
  25323. return InterpolateValueAction;
  25324. })(BABYLON.Action);
  25325. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25326. })(BABYLON || (BABYLON = {}));
  25327. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25328. var BABYLON;
  25329. (function (BABYLON) {
  25330. var SwitchBooleanAction = (function (_super) {
  25331. __extends(SwitchBooleanAction, _super);
  25332. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25333. _super.call(this, triggerOptions, condition);
  25334. this.propertyPath = propertyPath;
  25335. this._target = target;
  25336. }
  25337. SwitchBooleanAction.prototype._prepare = function () {
  25338. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25339. this._property = this._getProperty(this.propertyPath);
  25340. };
  25341. SwitchBooleanAction.prototype.execute = function () {
  25342. this._target[this._property] = !this._target[this._property];
  25343. };
  25344. return SwitchBooleanAction;
  25345. })(BABYLON.Action);
  25346. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25347. var SetStateAction = (function (_super) {
  25348. __extends(SetStateAction, _super);
  25349. function SetStateAction(triggerOptions, target, value, condition) {
  25350. _super.call(this, triggerOptions, condition);
  25351. this.value = value;
  25352. this._target = target;
  25353. }
  25354. SetStateAction.prototype.execute = function () {
  25355. this._target.state = this.value;
  25356. };
  25357. return SetStateAction;
  25358. })(BABYLON.Action);
  25359. BABYLON.SetStateAction = SetStateAction;
  25360. var SetValueAction = (function (_super) {
  25361. __extends(SetValueAction, _super);
  25362. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25363. _super.call(this, triggerOptions, condition);
  25364. this.propertyPath = propertyPath;
  25365. this.value = value;
  25366. this._target = target;
  25367. }
  25368. SetValueAction.prototype._prepare = function () {
  25369. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25370. this._property = this._getProperty(this.propertyPath);
  25371. };
  25372. SetValueAction.prototype.execute = function () {
  25373. this._target[this._property] = this.value;
  25374. };
  25375. return SetValueAction;
  25376. })(BABYLON.Action);
  25377. BABYLON.SetValueAction = SetValueAction;
  25378. var IncrementValueAction = (function (_super) {
  25379. __extends(IncrementValueAction, _super);
  25380. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25381. _super.call(this, triggerOptions, condition);
  25382. this.propertyPath = propertyPath;
  25383. this.value = value;
  25384. this._target = target;
  25385. }
  25386. IncrementValueAction.prototype._prepare = function () {
  25387. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25388. this._property = this._getProperty(this.propertyPath);
  25389. if (typeof this._target[this._property] !== "number") {
  25390. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25391. }
  25392. };
  25393. IncrementValueAction.prototype.execute = function () {
  25394. this._target[this._property] += this.value;
  25395. };
  25396. return IncrementValueAction;
  25397. })(BABYLON.Action);
  25398. BABYLON.IncrementValueAction = IncrementValueAction;
  25399. var PlayAnimationAction = (function (_super) {
  25400. __extends(PlayAnimationAction, _super);
  25401. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25402. _super.call(this, triggerOptions, condition);
  25403. this.from = from;
  25404. this.to = to;
  25405. this.loop = loop;
  25406. this._target = target;
  25407. }
  25408. PlayAnimationAction.prototype._prepare = function () {
  25409. };
  25410. PlayAnimationAction.prototype.execute = function () {
  25411. var scene = this._actionManager.getScene();
  25412. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25413. };
  25414. return PlayAnimationAction;
  25415. })(BABYLON.Action);
  25416. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25417. var StopAnimationAction = (function (_super) {
  25418. __extends(StopAnimationAction, _super);
  25419. function StopAnimationAction(triggerOptions, target, condition) {
  25420. _super.call(this, triggerOptions, condition);
  25421. this._target = target;
  25422. }
  25423. StopAnimationAction.prototype._prepare = function () {
  25424. };
  25425. StopAnimationAction.prototype.execute = function () {
  25426. var scene = this._actionManager.getScene();
  25427. scene.stopAnimation(this._target);
  25428. };
  25429. return StopAnimationAction;
  25430. })(BABYLON.Action);
  25431. BABYLON.StopAnimationAction = StopAnimationAction;
  25432. var DoNothingAction = (function (_super) {
  25433. __extends(DoNothingAction, _super);
  25434. function DoNothingAction(triggerOptions, condition) {
  25435. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25436. _super.call(this, triggerOptions, condition);
  25437. }
  25438. DoNothingAction.prototype.execute = function () {
  25439. };
  25440. return DoNothingAction;
  25441. })(BABYLON.Action);
  25442. BABYLON.DoNothingAction = DoNothingAction;
  25443. var CombineAction = (function (_super) {
  25444. __extends(CombineAction, _super);
  25445. function CombineAction(triggerOptions, children, condition) {
  25446. _super.call(this, triggerOptions, condition);
  25447. this.children = children;
  25448. }
  25449. CombineAction.prototype._prepare = function () {
  25450. for (var index = 0; index < this.children.length; index++) {
  25451. this.children[index]._actionManager = this._actionManager;
  25452. this.children[index]._prepare();
  25453. }
  25454. };
  25455. CombineAction.prototype.execute = function (evt) {
  25456. for (var index = 0; index < this.children.length; index++) {
  25457. this.children[index].execute(evt);
  25458. }
  25459. };
  25460. return CombineAction;
  25461. })(BABYLON.Action);
  25462. BABYLON.CombineAction = CombineAction;
  25463. var ExecuteCodeAction = (function (_super) {
  25464. __extends(ExecuteCodeAction, _super);
  25465. function ExecuteCodeAction(triggerOptions, func, condition) {
  25466. _super.call(this, triggerOptions, condition);
  25467. this.func = func;
  25468. }
  25469. ExecuteCodeAction.prototype.execute = function (evt) {
  25470. this.func(evt);
  25471. };
  25472. return ExecuteCodeAction;
  25473. })(BABYLON.Action);
  25474. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25475. var SetParentAction = (function (_super) {
  25476. __extends(SetParentAction, _super);
  25477. function SetParentAction(triggerOptions, target, parent, condition) {
  25478. _super.call(this, triggerOptions, condition);
  25479. this._target = target;
  25480. this._parent = parent;
  25481. }
  25482. SetParentAction.prototype._prepare = function () {
  25483. };
  25484. SetParentAction.prototype.execute = function () {
  25485. if (this._target.parent === this._parent) {
  25486. return;
  25487. }
  25488. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25489. invertParentWorldMatrix.invert();
  25490. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25491. this._target.parent = this._parent;
  25492. };
  25493. return SetParentAction;
  25494. })(BABYLON.Action);
  25495. BABYLON.SetParentAction = SetParentAction;
  25496. var PlaySoundAction = (function (_super) {
  25497. __extends(PlaySoundAction, _super);
  25498. function PlaySoundAction(triggerOptions, sound, condition) {
  25499. _super.call(this, triggerOptions, condition);
  25500. this._sound = sound;
  25501. }
  25502. PlaySoundAction.prototype._prepare = function () {
  25503. };
  25504. PlaySoundAction.prototype.execute = function () {
  25505. if (this._sound !== undefined)
  25506. this._sound.play();
  25507. };
  25508. return PlaySoundAction;
  25509. })(BABYLON.Action);
  25510. BABYLON.PlaySoundAction = PlaySoundAction;
  25511. var StopSoundAction = (function (_super) {
  25512. __extends(StopSoundAction, _super);
  25513. function StopSoundAction(triggerOptions, sound, condition) {
  25514. _super.call(this, triggerOptions, condition);
  25515. this._sound = sound;
  25516. }
  25517. StopSoundAction.prototype._prepare = function () {
  25518. };
  25519. StopSoundAction.prototype.execute = function () {
  25520. if (this._sound !== undefined)
  25521. this._sound.stop();
  25522. };
  25523. return StopSoundAction;
  25524. })(BABYLON.Action);
  25525. BABYLON.StopSoundAction = StopSoundAction;
  25526. })(BABYLON || (BABYLON = {}));
  25527. //# sourceMappingURL=babylon.directActions.js.map
  25528. var BABYLON;
  25529. (function (BABYLON) {
  25530. var Geometry = (function () {
  25531. function Geometry(id, scene, vertexData, updatable, mesh) {
  25532. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25533. this._totalVertices = 0;
  25534. this._indices = [];
  25535. this._isDisposed = false;
  25536. this.id = id;
  25537. this._engine = scene.getEngine();
  25538. this._meshes = [];
  25539. this._scene = scene;
  25540. // vertexData
  25541. if (vertexData) {
  25542. this.setAllVerticesData(vertexData, updatable);
  25543. }
  25544. else {
  25545. this._totalVertices = 0;
  25546. this._indices = [];
  25547. }
  25548. // applyToMesh
  25549. if (mesh) {
  25550. this.applyToMesh(mesh);
  25551. mesh.computeWorldMatrix(true);
  25552. }
  25553. }
  25554. Geometry.prototype.getScene = function () {
  25555. return this._scene;
  25556. };
  25557. Geometry.prototype.getEngine = function () {
  25558. return this._engine;
  25559. };
  25560. Geometry.prototype.isReady = function () {
  25561. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25562. };
  25563. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25564. vertexData.applyToGeometry(this, updatable);
  25565. this.notifyUpdate();
  25566. };
  25567. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25568. this._vertexBuffers = this._vertexBuffers || {};
  25569. if (this._vertexBuffers[kind]) {
  25570. this._vertexBuffers[kind].dispose();
  25571. }
  25572. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25573. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25574. stride = this._vertexBuffers[kind].getStrideSize();
  25575. this._totalVertices = data.length / stride;
  25576. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25577. var meshes = this._meshes;
  25578. var numOfMeshes = meshes.length;
  25579. for (var index = 0; index < numOfMeshes; index++) {
  25580. var mesh = meshes[index];
  25581. mesh._resetPointsArrayCache();
  25582. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25583. mesh._createGlobalSubMesh();
  25584. mesh.computeWorldMatrix(true);
  25585. }
  25586. }
  25587. this.notifyUpdate(kind);
  25588. };
  25589. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25590. var vertexBuffer = this.getVertexBuffer(kind);
  25591. if (!vertexBuffer) {
  25592. return;
  25593. }
  25594. vertexBuffer.updateDirectly(data, offset);
  25595. this.notifyUpdate(kind);
  25596. };
  25597. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25598. var vertexBuffer = this.getVertexBuffer(kind);
  25599. if (!vertexBuffer) {
  25600. return;
  25601. }
  25602. vertexBuffer.update(data);
  25603. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25604. var extend;
  25605. var stride = vertexBuffer.getStrideSize();
  25606. this._totalVertices = data.length / stride;
  25607. if (updateExtends) {
  25608. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25609. }
  25610. var meshes = this._meshes;
  25611. var numOfMeshes = meshes.length;
  25612. for (var index = 0; index < numOfMeshes; index++) {
  25613. var mesh = meshes[index];
  25614. mesh._resetPointsArrayCache();
  25615. if (updateExtends) {
  25616. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25617. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25618. var subMesh = mesh.subMeshes[subIndex];
  25619. subMesh.refreshBoundingInfo();
  25620. }
  25621. }
  25622. }
  25623. }
  25624. this.notifyUpdate(kind);
  25625. };
  25626. Geometry.prototype.getTotalVertices = function () {
  25627. if (!this.isReady()) {
  25628. return 0;
  25629. }
  25630. return this._totalVertices;
  25631. };
  25632. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25633. var vertexBuffer = this.getVertexBuffer(kind);
  25634. if (!vertexBuffer) {
  25635. return null;
  25636. }
  25637. var orig = vertexBuffer.getData();
  25638. if (!copyWhenShared || this._meshes.length === 1) {
  25639. return orig;
  25640. }
  25641. else {
  25642. var len = orig.length;
  25643. var copy = [];
  25644. for (var i = 0; i < len; i++) {
  25645. copy.push(orig[i]);
  25646. }
  25647. return copy;
  25648. }
  25649. };
  25650. Geometry.prototype.getVertexBuffer = function (kind) {
  25651. if (!this.isReady()) {
  25652. return null;
  25653. }
  25654. return this._vertexBuffers[kind];
  25655. };
  25656. Geometry.prototype.getVertexBuffers = function () {
  25657. if (!this.isReady()) {
  25658. return null;
  25659. }
  25660. return this._vertexBuffers;
  25661. };
  25662. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25663. if (!this._vertexBuffers) {
  25664. if (this._delayInfo) {
  25665. return this._delayInfo.indexOf(kind) !== -1;
  25666. }
  25667. return false;
  25668. }
  25669. return this._vertexBuffers[kind] !== undefined;
  25670. };
  25671. Geometry.prototype.getVerticesDataKinds = function () {
  25672. var result = [];
  25673. if (!this._vertexBuffers && this._delayInfo) {
  25674. for (var kind in this._delayInfo) {
  25675. result.push(kind);
  25676. }
  25677. }
  25678. else {
  25679. for (kind in this._vertexBuffers) {
  25680. result.push(kind);
  25681. }
  25682. }
  25683. return result;
  25684. };
  25685. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25686. if (this._indexBuffer) {
  25687. this._engine._releaseBuffer(this._indexBuffer);
  25688. }
  25689. this._indices = indices;
  25690. if (this._meshes.length !== 0 && this._indices) {
  25691. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25692. }
  25693. if (totalVertices !== undefined) {
  25694. this._totalVertices = totalVertices;
  25695. }
  25696. var meshes = this._meshes;
  25697. var numOfMeshes = meshes.length;
  25698. for (var index = 0; index < numOfMeshes; index++) {
  25699. meshes[index]._createGlobalSubMesh();
  25700. }
  25701. this.notifyUpdate();
  25702. };
  25703. Geometry.prototype.getTotalIndices = function () {
  25704. if (!this.isReady()) {
  25705. return 0;
  25706. }
  25707. return this._indices.length;
  25708. };
  25709. Geometry.prototype.getIndices = function (copyWhenShared) {
  25710. if (!this.isReady()) {
  25711. return null;
  25712. }
  25713. var orig = this._indices;
  25714. if (!copyWhenShared || this._meshes.length === 1) {
  25715. return orig;
  25716. }
  25717. else {
  25718. var len = orig.length;
  25719. var copy = [];
  25720. for (var i = 0; i < len; i++) {
  25721. copy.push(orig[i]);
  25722. }
  25723. return copy;
  25724. }
  25725. };
  25726. Geometry.prototype.getIndexBuffer = function () {
  25727. if (!this.isReady()) {
  25728. return null;
  25729. }
  25730. return this._indexBuffer;
  25731. };
  25732. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25733. var meshes = this._meshes;
  25734. var index = meshes.indexOf(mesh);
  25735. if (index === -1) {
  25736. return;
  25737. }
  25738. for (var kind in this._vertexBuffers) {
  25739. this._vertexBuffers[kind].dispose();
  25740. }
  25741. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25742. this._indexBuffer = null;
  25743. }
  25744. meshes.splice(index, 1);
  25745. mesh._geometry = null;
  25746. if (meshes.length === 0 && shouldDispose) {
  25747. this.dispose();
  25748. }
  25749. };
  25750. Geometry.prototype.applyToMesh = function (mesh) {
  25751. if (mesh._geometry === this) {
  25752. return;
  25753. }
  25754. var previousGeometry = mesh._geometry;
  25755. if (previousGeometry) {
  25756. previousGeometry.releaseForMesh(mesh);
  25757. }
  25758. var meshes = this._meshes;
  25759. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25760. mesh._geometry = this;
  25761. this._scene.pushGeometry(this);
  25762. meshes.push(mesh);
  25763. if (this.isReady()) {
  25764. this._applyToMesh(mesh);
  25765. }
  25766. else {
  25767. mesh._boundingInfo = this._boundingInfo;
  25768. }
  25769. };
  25770. Geometry.prototype._applyToMesh = function (mesh) {
  25771. var numOfMeshes = this._meshes.length;
  25772. for (var kind in this._vertexBuffers) {
  25773. if (numOfMeshes === 1) {
  25774. this._vertexBuffers[kind].create();
  25775. }
  25776. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25777. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25778. mesh._resetPointsArrayCache();
  25779. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25780. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25781. mesh._createGlobalSubMesh();
  25782. //bounding info was just created again, world matrix should be applied again.
  25783. mesh._updateBoundingInfo();
  25784. }
  25785. }
  25786. // indexBuffer
  25787. if (numOfMeshes === 1 && this._indices) {
  25788. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25789. }
  25790. if (this._indexBuffer) {
  25791. this._indexBuffer.references = numOfMeshes;
  25792. }
  25793. };
  25794. Geometry.prototype.notifyUpdate = function (kind) {
  25795. if (this.onGeometryUpdated) {
  25796. this.onGeometryUpdated(this, kind);
  25797. }
  25798. };
  25799. Geometry.prototype.load = function (scene, onLoaded) {
  25800. var _this = this;
  25801. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25802. return;
  25803. }
  25804. if (this.isReady()) {
  25805. if (onLoaded) {
  25806. onLoaded();
  25807. }
  25808. return;
  25809. }
  25810. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25811. scene._addPendingData(this);
  25812. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25813. _this._delayLoadingFunction(JSON.parse(data), _this);
  25814. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25815. _this._delayInfo = [];
  25816. scene._removePendingData(_this);
  25817. var meshes = _this._meshes;
  25818. var numOfMeshes = meshes.length;
  25819. for (var index = 0; index < numOfMeshes; index++) {
  25820. _this._applyToMesh(meshes[index]);
  25821. }
  25822. if (onLoaded) {
  25823. onLoaded();
  25824. }
  25825. }, function () {
  25826. }, scene.database);
  25827. };
  25828. Geometry.prototype.isDisposed = function () {
  25829. return this._isDisposed;
  25830. };
  25831. Geometry.prototype.dispose = function () {
  25832. var meshes = this._meshes;
  25833. var numOfMeshes = meshes.length;
  25834. var index;
  25835. for (index = 0; index < numOfMeshes; index++) {
  25836. this.releaseForMesh(meshes[index]);
  25837. }
  25838. this._meshes = [];
  25839. for (var kind in this._vertexBuffers) {
  25840. this._vertexBuffers[kind].dispose();
  25841. }
  25842. this._vertexBuffers = [];
  25843. this._totalVertices = 0;
  25844. if (this._indexBuffer) {
  25845. this._engine._releaseBuffer(this._indexBuffer);
  25846. }
  25847. this._indexBuffer = null;
  25848. this._indices = [];
  25849. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25850. this.delayLoadingFile = null;
  25851. this._delayLoadingFunction = null;
  25852. this._delayInfo = [];
  25853. this._boundingInfo = null; // todo: .dispose()
  25854. this._scene.removeGeometry(this);
  25855. this._isDisposed = true;
  25856. };
  25857. Geometry.prototype.copy = function (id) {
  25858. var vertexData = new BABYLON.VertexData();
  25859. vertexData.indices = [];
  25860. var indices = this.getIndices();
  25861. for (var index = 0; index < indices.length; index++) {
  25862. vertexData.indices.push(indices[index]);
  25863. }
  25864. var updatable = false;
  25865. var stopChecking = false;
  25866. for (var kind in this._vertexBuffers) {
  25867. // using slice() to make a copy of the array and not just reference it
  25868. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25869. if (!stopChecking) {
  25870. updatable = this.getVertexBuffer(kind).isUpdatable();
  25871. stopChecking = !updatable;
  25872. }
  25873. }
  25874. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25875. geometry.delayLoadState = this.delayLoadState;
  25876. geometry.delayLoadingFile = this.delayLoadingFile;
  25877. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25878. for (kind in this._delayInfo) {
  25879. geometry._delayInfo = geometry._delayInfo || [];
  25880. geometry._delayInfo.push(kind);
  25881. }
  25882. // Bounding info
  25883. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25884. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25885. return geometry;
  25886. };
  25887. // Statics
  25888. Geometry.ExtractFromMesh = function (mesh, id) {
  25889. var geometry = mesh._geometry;
  25890. if (!geometry) {
  25891. return null;
  25892. }
  25893. return geometry.copy(id);
  25894. };
  25895. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25896. // be aware Math.random() could cause collisions
  25897. Geometry.RandomId = function () {
  25898. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25899. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25900. return v.toString(16);
  25901. });
  25902. };
  25903. return Geometry;
  25904. })();
  25905. BABYLON.Geometry = Geometry;
  25906. /////// Primitives //////////////////////////////////////////////
  25907. var Geometry;
  25908. (function (Geometry) {
  25909. var Primitives;
  25910. (function (Primitives) {
  25911. /// Abstract class
  25912. var _Primitive = (function (_super) {
  25913. __extends(_Primitive, _super);
  25914. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25915. this._beingRegenerated = true;
  25916. this._canBeRegenerated = canBeRegenerated;
  25917. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25918. this._beingRegenerated = false;
  25919. }
  25920. _Primitive.prototype.canBeRegenerated = function () {
  25921. return this._canBeRegenerated;
  25922. };
  25923. _Primitive.prototype.regenerate = function () {
  25924. if (!this._canBeRegenerated) {
  25925. return;
  25926. }
  25927. this._beingRegenerated = true;
  25928. this.setAllVerticesData(this._regenerateVertexData(), false);
  25929. this._beingRegenerated = false;
  25930. };
  25931. _Primitive.prototype.asNewGeometry = function (id) {
  25932. return _super.prototype.copy.call(this, id);
  25933. };
  25934. // overrides
  25935. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25936. if (!this._beingRegenerated) {
  25937. return;
  25938. }
  25939. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25940. };
  25941. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25942. if (!this._beingRegenerated) {
  25943. return;
  25944. }
  25945. _super.prototype.setVerticesData.call(this, kind, data, false);
  25946. };
  25947. // to override
  25948. // protected
  25949. _Primitive.prototype._regenerateVertexData = function () {
  25950. throw new Error("Abstract method");
  25951. };
  25952. _Primitive.prototype.copy = function (id) {
  25953. throw new Error("Must be overriden in sub-classes.");
  25954. };
  25955. return _Primitive;
  25956. })(Geometry);
  25957. Primitives._Primitive = _Primitive;
  25958. var Ribbon = (function (_super) {
  25959. __extends(Ribbon, _super);
  25960. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25961. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25962. this.pathArray = pathArray;
  25963. this.closeArray = closeArray;
  25964. this.closePath = closePath;
  25965. this.offset = offset;
  25966. this.side = side;
  25967. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25968. }
  25969. Ribbon.prototype._regenerateVertexData = function () {
  25970. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25971. };
  25972. Ribbon.prototype.copy = function (id) {
  25973. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25974. };
  25975. return Ribbon;
  25976. })(_Primitive);
  25977. Primitives.Ribbon = Ribbon;
  25978. var Box = (function (_super) {
  25979. __extends(Box, _super);
  25980. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25981. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25982. this.size = size;
  25983. this.side = side;
  25984. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25985. }
  25986. Box.prototype._regenerateVertexData = function () {
  25987. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25988. };
  25989. Box.prototype.copy = function (id) {
  25990. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25991. };
  25992. return Box;
  25993. })(_Primitive);
  25994. Primitives.Box = Box;
  25995. var Sphere = (function (_super) {
  25996. __extends(Sphere, _super);
  25997. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25998. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25999. this.segments = segments;
  26000. this.diameter = diameter;
  26001. this.side = side;
  26002. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26003. }
  26004. Sphere.prototype._regenerateVertexData = function () {
  26005. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  26006. };
  26007. Sphere.prototype.copy = function (id) {
  26008. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26009. };
  26010. return Sphere;
  26011. })(_Primitive);
  26012. Primitives.Sphere = Sphere;
  26013. var Cylinder = (function (_super) {
  26014. __extends(Cylinder, _super);
  26015. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26016. if (subdivisions === void 0) { subdivisions = 1; }
  26017. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26018. this.height = height;
  26019. this.diameterTop = diameterTop;
  26020. this.diameterBottom = diameterBottom;
  26021. this.tessellation = tessellation;
  26022. this.subdivisions = subdivisions;
  26023. this.side = side;
  26024. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26025. }
  26026. Cylinder.prototype._regenerateVertexData = function () {
  26027. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  26028. };
  26029. Cylinder.prototype.copy = function (id) {
  26030. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26031. };
  26032. return Cylinder;
  26033. })(_Primitive);
  26034. Primitives.Cylinder = Cylinder;
  26035. var Torus = (function (_super) {
  26036. __extends(Torus, _super);
  26037. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26038. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26039. this.diameter = diameter;
  26040. this.thickness = thickness;
  26041. this.tessellation = tessellation;
  26042. this.side = side;
  26043. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26044. }
  26045. Torus.prototype._regenerateVertexData = function () {
  26046. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  26047. };
  26048. Torus.prototype.copy = function (id) {
  26049. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26050. };
  26051. return Torus;
  26052. })(_Primitive);
  26053. Primitives.Torus = Torus;
  26054. var Ground = (function (_super) {
  26055. __extends(Ground, _super);
  26056. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26057. this.width = width;
  26058. this.height = height;
  26059. this.subdivisions = subdivisions;
  26060. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26061. }
  26062. Ground.prototype._regenerateVertexData = function () {
  26063. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  26064. };
  26065. Ground.prototype.copy = function (id) {
  26066. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26067. };
  26068. return Ground;
  26069. })(_Primitive);
  26070. Primitives.Ground = Ground;
  26071. var TiledGround = (function (_super) {
  26072. __extends(TiledGround, _super);
  26073. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26074. this.xmin = xmin;
  26075. this.zmin = zmin;
  26076. this.xmax = xmax;
  26077. this.zmax = zmax;
  26078. this.subdivisions = subdivisions;
  26079. this.precision = precision;
  26080. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26081. }
  26082. TiledGround.prototype._regenerateVertexData = function () {
  26083. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  26084. };
  26085. TiledGround.prototype.copy = function (id) {
  26086. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26087. };
  26088. return TiledGround;
  26089. })(_Primitive);
  26090. Primitives.TiledGround = TiledGround;
  26091. var Plane = (function (_super) {
  26092. __extends(Plane, _super);
  26093. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26094. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26095. this.size = size;
  26096. this.side = side;
  26097. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26098. }
  26099. Plane.prototype._regenerateVertexData = function () {
  26100. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  26101. };
  26102. Plane.prototype.copy = function (id) {
  26103. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26104. };
  26105. return Plane;
  26106. })(_Primitive);
  26107. Primitives.Plane = Plane;
  26108. var TorusKnot = (function (_super) {
  26109. __extends(TorusKnot, _super);
  26110. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26111. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26112. this.radius = radius;
  26113. this.tube = tube;
  26114. this.radialSegments = radialSegments;
  26115. this.tubularSegments = tubularSegments;
  26116. this.p = p;
  26117. this.q = q;
  26118. this.side = side;
  26119. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26120. }
  26121. TorusKnot.prototype._regenerateVertexData = function () {
  26122. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  26123. };
  26124. TorusKnot.prototype.copy = function (id) {
  26125. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26126. };
  26127. return TorusKnot;
  26128. })(_Primitive);
  26129. Primitives.TorusKnot = TorusKnot;
  26130. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26131. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26132. })(BABYLON || (BABYLON = {}));
  26133. //# sourceMappingURL=babylon.geometry.js.map
  26134. var BABYLON;
  26135. (function (BABYLON) {
  26136. var Gamepads = (function () {
  26137. function Gamepads(ongamedpadconnected) {
  26138. var _this = this;
  26139. this.babylonGamepads = [];
  26140. this.oneGamepadConnected = false;
  26141. this.isMonitoring = false;
  26142. this.gamepadEventSupported = 'GamepadEvent' in window;
  26143. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  26144. 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=";
  26145. this._callbackGamepadConnected = ongamedpadconnected;
  26146. if (this.gamepadSupportAvailable) {
  26147. // Checking if the gamepad connected event is supported (like in Firefox)
  26148. if (this.gamepadEventSupported) {
  26149. window.addEventListener('gamepadconnected', function (evt) {
  26150. _this._onGamepadConnected(evt);
  26151. }, false);
  26152. window.addEventListener('gamepaddisconnected', function (evt) {
  26153. _this._onGamepadDisconnected(evt);
  26154. }, false);
  26155. }
  26156. else {
  26157. this._startMonitoringGamepads();
  26158. }
  26159. if (!this.oneGamepadConnected) {
  26160. this._insertGamepadDOMInstructions();
  26161. }
  26162. }
  26163. else {
  26164. this._insertGamepadDOMNotSupported();
  26165. }
  26166. }
  26167. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  26168. Gamepads.gamepadDOMInfo = document.createElement("div");
  26169. var buttonAImage = document.createElement("img");
  26170. buttonAImage.src = this.buttonADataURL;
  26171. var spanMessage = document.createElement("span");
  26172. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  26173. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  26174. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26175. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26176. Gamepads.gamepadDOMInfo.style.width = "100%";
  26177. Gamepads.gamepadDOMInfo.style.height = "48px";
  26178. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26179. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26180. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26181. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26182. buttonAImage.style.position = "relative";
  26183. buttonAImage.style.bottom = "8px";
  26184. spanMessage.style.position = "relative";
  26185. spanMessage.style.fontSize = "32px";
  26186. spanMessage.style.bottom = "32px";
  26187. spanMessage.style.color = "green";
  26188. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26189. };
  26190. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  26191. Gamepads.gamepadDOMInfo = document.createElement("div");
  26192. var spanMessage = document.createElement("span");
  26193. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  26194. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26195. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26196. Gamepads.gamepadDOMInfo.style.width = "100%";
  26197. Gamepads.gamepadDOMInfo.style.height = "40px";
  26198. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26199. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26200. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26201. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26202. spanMessage.style.position = "relative";
  26203. spanMessage.style.fontSize = "32px";
  26204. spanMessage.style.color = "red";
  26205. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26206. };
  26207. Gamepads.prototype.dispose = function () {
  26208. if (Gamepads.gamepadDOMInfo) {
  26209. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26210. }
  26211. };
  26212. Gamepads.prototype._onGamepadConnected = function (evt) {
  26213. var newGamepad = this._addNewGamepad(evt.gamepad);
  26214. if (this._callbackGamepadConnected)
  26215. this._callbackGamepadConnected(newGamepad);
  26216. this._startMonitoringGamepads();
  26217. };
  26218. Gamepads.prototype._addNewGamepad = function (gamepad) {
  26219. if (!this.oneGamepadConnected) {
  26220. this.oneGamepadConnected = true;
  26221. if (Gamepads.gamepadDOMInfo) {
  26222. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26223. Gamepads.gamepadDOMInfo = null;
  26224. }
  26225. }
  26226. var newGamepad;
  26227. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  26228. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  26229. }
  26230. else {
  26231. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  26232. }
  26233. this.babylonGamepads.push(newGamepad);
  26234. return newGamepad;
  26235. };
  26236. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  26237. for (var i in this.babylonGamepads) {
  26238. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  26239. this.babylonGamepads.splice(i, 1);
  26240. break;
  26241. }
  26242. }
  26243. // If no gamepads are left, stop the polling loop.
  26244. if (this.babylonGamepads.length == 0) {
  26245. this._stopMonitoringGamepads();
  26246. }
  26247. };
  26248. Gamepads.prototype._startMonitoringGamepads = function () {
  26249. if (!this.isMonitoring) {
  26250. this.isMonitoring = true;
  26251. this._checkGamepadsStatus();
  26252. }
  26253. };
  26254. Gamepads.prototype._stopMonitoringGamepads = function () {
  26255. this.isMonitoring = false;
  26256. };
  26257. Gamepads.prototype._checkGamepadsStatus = function () {
  26258. var _this = this;
  26259. // updating gamepad objects
  26260. this._updateGamepadObjects();
  26261. for (var i in this.babylonGamepads) {
  26262. this.babylonGamepads[i].update();
  26263. }
  26264. if (this.isMonitoring) {
  26265. if (window.requestAnimationFrame) {
  26266. window.requestAnimationFrame(function () {
  26267. _this._checkGamepadsStatus();
  26268. });
  26269. }
  26270. else if (window.mozRequestAnimationFrame) {
  26271. window.mozRequestAnimationFrame(function () {
  26272. _this._checkGamepadsStatus();
  26273. });
  26274. }
  26275. else if (window.webkitRequestAnimationFrame) {
  26276. window.webkitRequestAnimationFrame(function () {
  26277. _this._checkGamepadsStatus();
  26278. });
  26279. }
  26280. }
  26281. };
  26282. // This function is called only on Chrome, which does not yet support
  26283. // connection/disconnection events, but requires you to monitor
  26284. // an array for changes.
  26285. Gamepads.prototype._updateGamepadObjects = function () {
  26286. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  26287. for (var i = 0; i < gamepads.length; i++) {
  26288. if (gamepads[i]) {
  26289. if (!(gamepads[i].index in this.babylonGamepads)) {
  26290. var newGamepad = this._addNewGamepad(gamepads[i]);
  26291. if (this._callbackGamepadConnected) {
  26292. this._callbackGamepadConnected(newGamepad);
  26293. }
  26294. }
  26295. else {
  26296. this.babylonGamepads[i].browserGamepad = gamepads[i];
  26297. }
  26298. }
  26299. }
  26300. };
  26301. return Gamepads;
  26302. })();
  26303. BABYLON.Gamepads = Gamepads;
  26304. var StickValues = (function () {
  26305. function StickValues(x, y) {
  26306. this.x = x;
  26307. this.y = y;
  26308. }
  26309. return StickValues;
  26310. })();
  26311. BABYLON.StickValues = StickValues;
  26312. var Gamepad = (function () {
  26313. function Gamepad(id, index, browserGamepad) {
  26314. this.id = id;
  26315. this.index = index;
  26316. this.browserGamepad = browserGamepad;
  26317. if (this.browserGamepad.axes.length >= 2) {
  26318. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26319. }
  26320. if (this.browserGamepad.axes.length >= 4) {
  26321. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26322. }
  26323. }
  26324. Gamepad.prototype.onleftstickchanged = function (callback) {
  26325. this._onleftstickchanged = callback;
  26326. };
  26327. Gamepad.prototype.onrightstickchanged = function (callback) {
  26328. this._onrightstickchanged = callback;
  26329. };
  26330. Object.defineProperty(Gamepad.prototype, "leftStick", {
  26331. get: function () {
  26332. return this._leftStick;
  26333. },
  26334. set: function (newValues) {
  26335. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26336. this._onleftstickchanged(newValues);
  26337. }
  26338. this._leftStick = newValues;
  26339. },
  26340. enumerable: true,
  26341. configurable: true
  26342. });
  26343. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26344. get: function () {
  26345. return this._rightStick;
  26346. },
  26347. set: function (newValues) {
  26348. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26349. this._onrightstickchanged(newValues);
  26350. }
  26351. this._rightStick = newValues;
  26352. },
  26353. enumerable: true,
  26354. configurable: true
  26355. });
  26356. Gamepad.prototype.update = function () {
  26357. if (this._leftStick) {
  26358. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26359. }
  26360. if (this._rightStick) {
  26361. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26362. }
  26363. };
  26364. return Gamepad;
  26365. })();
  26366. BABYLON.Gamepad = Gamepad;
  26367. var GenericPad = (function (_super) {
  26368. __extends(GenericPad, _super);
  26369. function GenericPad(id, index, gamepad) {
  26370. _super.call(this, id, index, gamepad);
  26371. this.id = id;
  26372. this.index = index;
  26373. this.gamepad = gamepad;
  26374. this._buttons = new Array(gamepad.buttons.length);
  26375. }
  26376. GenericPad.prototype.onbuttondown = function (callback) {
  26377. this._onbuttondown = callback;
  26378. };
  26379. GenericPad.prototype.onbuttonup = function (callback) {
  26380. this._onbuttonup = callback;
  26381. };
  26382. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26383. if (newValue !== currentValue) {
  26384. if (this._onbuttondown && newValue === 1) {
  26385. this._onbuttondown(buttonIndex);
  26386. }
  26387. if (this._onbuttonup && newValue === 0) {
  26388. this._onbuttonup(buttonIndex);
  26389. }
  26390. }
  26391. return newValue;
  26392. };
  26393. GenericPad.prototype.update = function () {
  26394. _super.prototype.update.call(this);
  26395. for (var index = 0; index < this._buttons.length; index++) {
  26396. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26397. }
  26398. };
  26399. return GenericPad;
  26400. })(Gamepad);
  26401. BABYLON.GenericPad = GenericPad;
  26402. (function (Xbox360Button) {
  26403. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26404. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26405. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26406. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26407. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26408. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26409. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26410. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26411. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26412. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26413. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26414. var Xbox360Button = BABYLON.Xbox360Button;
  26415. (function (Xbox360Dpad) {
  26416. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26417. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26418. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26419. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26420. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26421. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26422. var Xbox360Pad = (function (_super) {
  26423. __extends(Xbox360Pad, _super);
  26424. function Xbox360Pad() {
  26425. _super.apply(this, arguments);
  26426. this._leftTrigger = 0;
  26427. this._rightTrigger = 0;
  26428. this._buttonA = 0;
  26429. this._buttonB = 0;
  26430. this._buttonX = 0;
  26431. this._buttonY = 0;
  26432. this._buttonBack = 0;
  26433. this._buttonStart = 0;
  26434. this._buttonLB = 0;
  26435. this._buttonRB = 0;
  26436. this._buttonLeftStick = 0;
  26437. this._buttonRightStick = 0;
  26438. this._dPadUp = 0;
  26439. this._dPadDown = 0;
  26440. this._dPadLeft = 0;
  26441. this._dPadRight = 0;
  26442. }
  26443. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26444. this._onlefttriggerchanged = callback;
  26445. };
  26446. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26447. this._onrighttriggerchanged = callback;
  26448. };
  26449. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26450. get: function () {
  26451. return this._leftTrigger;
  26452. },
  26453. set: function (newValue) {
  26454. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26455. this._onlefttriggerchanged(newValue);
  26456. }
  26457. this._leftTrigger = newValue;
  26458. },
  26459. enumerable: true,
  26460. configurable: true
  26461. });
  26462. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26463. get: function () {
  26464. return this._rightTrigger;
  26465. },
  26466. set: function (newValue) {
  26467. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26468. this._onrighttriggerchanged(newValue);
  26469. }
  26470. this._rightTrigger = newValue;
  26471. },
  26472. enumerable: true,
  26473. configurable: true
  26474. });
  26475. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26476. this._onbuttondown = callback;
  26477. };
  26478. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26479. this._onbuttonup = callback;
  26480. };
  26481. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26482. this._ondpaddown = callback;
  26483. };
  26484. Xbox360Pad.prototype.ondpadup = function (callback) {
  26485. this._ondpadup = callback;
  26486. };
  26487. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26488. if (newValue !== currentValue) {
  26489. if (this._onbuttondown && newValue === 1) {
  26490. this._onbuttondown(buttonType);
  26491. }
  26492. if (this._onbuttonup && newValue === 0) {
  26493. this._onbuttonup(buttonType);
  26494. }
  26495. }
  26496. return newValue;
  26497. };
  26498. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26499. if (newValue !== currentValue) {
  26500. if (this._ondpaddown && newValue === 1) {
  26501. this._ondpaddown(buttonType);
  26502. }
  26503. if (this._ondpadup && newValue === 0) {
  26504. this._ondpadup(buttonType);
  26505. }
  26506. }
  26507. return newValue;
  26508. };
  26509. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26510. get: function () {
  26511. return this._buttonA;
  26512. },
  26513. set: function (value) {
  26514. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26515. },
  26516. enumerable: true,
  26517. configurable: true
  26518. });
  26519. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26520. get: function () {
  26521. return this._buttonB;
  26522. },
  26523. set: function (value) {
  26524. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26525. },
  26526. enumerable: true,
  26527. configurable: true
  26528. });
  26529. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26530. get: function () {
  26531. return this._buttonX;
  26532. },
  26533. set: function (value) {
  26534. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26535. },
  26536. enumerable: true,
  26537. configurable: true
  26538. });
  26539. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26540. get: function () {
  26541. return this._buttonY;
  26542. },
  26543. set: function (value) {
  26544. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26545. },
  26546. enumerable: true,
  26547. configurable: true
  26548. });
  26549. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26550. get: function () {
  26551. return this._buttonStart;
  26552. },
  26553. set: function (value) {
  26554. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26555. },
  26556. enumerable: true,
  26557. configurable: true
  26558. });
  26559. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26560. get: function () {
  26561. return this._buttonBack;
  26562. },
  26563. set: function (value) {
  26564. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26565. },
  26566. enumerable: true,
  26567. configurable: true
  26568. });
  26569. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26570. get: function () {
  26571. return this._buttonLB;
  26572. },
  26573. set: function (value) {
  26574. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26575. },
  26576. enumerable: true,
  26577. configurable: true
  26578. });
  26579. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26580. get: function () {
  26581. return this._buttonRB;
  26582. },
  26583. set: function (value) {
  26584. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26585. },
  26586. enumerable: true,
  26587. configurable: true
  26588. });
  26589. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26590. get: function () {
  26591. return this._buttonLeftStick;
  26592. },
  26593. set: function (value) {
  26594. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26595. },
  26596. enumerable: true,
  26597. configurable: true
  26598. });
  26599. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26600. get: function () {
  26601. return this._buttonRightStick;
  26602. },
  26603. set: function (value) {
  26604. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26605. },
  26606. enumerable: true,
  26607. configurable: true
  26608. });
  26609. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26610. get: function () {
  26611. return this._dPadUp;
  26612. },
  26613. set: function (value) {
  26614. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26615. },
  26616. enumerable: true,
  26617. configurable: true
  26618. });
  26619. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26620. get: function () {
  26621. return this._dPadDown;
  26622. },
  26623. set: function (value) {
  26624. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26625. },
  26626. enumerable: true,
  26627. configurable: true
  26628. });
  26629. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26630. get: function () {
  26631. return this._dPadLeft;
  26632. },
  26633. set: function (value) {
  26634. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26635. },
  26636. enumerable: true,
  26637. configurable: true
  26638. });
  26639. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26640. get: function () {
  26641. return this._dPadRight;
  26642. },
  26643. set: function (value) {
  26644. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26645. },
  26646. enumerable: true,
  26647. configurable: true
  26648. });
  26649. Xbox360Pad.prototype.update = function () {
  26650. _super.prototype.update.call(this);
  26651. this.buttonA = this.browserGamepad.buttons[0].value;
  26652. this.buttonB = this.browserGamepad.buttons[1].value;
  26653. this.buttonX = this.browserGamepad.buttons[2].value;
  26654. this.buttonY = this.browserGamepad.buttons[3].value;
  26655. this.buttonLB = this.browserGamepad.buttons[4].value;
  26656. this.buttonRB = this.browserGamepad.buttons[5].value;
  26657. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26658. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26659. this.buttonBack = this.browserGamepad.buttons[8].value;
  26660. this.buttonStart = this.browserGamepad.buttons[9].value;
  26661. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26662. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26663. this.dPadUp = this.browserGamepad.buttons[12].value;
  26664. this.dPadDown = this.browserGamepad.buttons[13].value;
  26665. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26666. this.dPadRight = this.browserGamepad.buttons[15].value;
  26667. };
  26668. return Xbox360Pad;
  26669. })(Gamepad);
  26670. BABYLON.Xbox360Pad = Xbox360Pad;
  26671. })(BABYLON || (BABYLON = {}));
  26672. //# sourceMappingURL=babylon.gamepads.js.map
  26673. var BABYLON;
  26674. (function (BABYLON) {
  26675. // We're mainly based on the logic defined into the FreeCamera code
  26676. var GamepadCamera = (function (_super) {
  26677. __extends(GamepadCamera, _super);
  26678. function GamepadCamera(name, position, scene) {
  26679. var _this = this;
  26680. _super.call(this, name, position, scene);
  26681. this.angularSensibility = 200;
  26682. this.moveSensibility = 75;
  26683. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26684. _this._onNewGameConnected(gamepad);
  26685. });
  26686. }
  26687. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26688. // Only the first gamepad can control the camera
  26689. if (gamepad.index === 0) {
  26690. this._gamepad = gamepad;
  26691. }
  26692. };
  26693. GamepadCamera.prototype._checkInputs = function () {
  26694. if (!this._gamepad) {
  26695. return;
  26696. }
  26697. var LSValues = this._gamepad.leftStick;
  26698. var normalizedLX = LSValues.x / this.moveSensibility;
  26699. var normalizedLY = LSValues.y / this.moveSensibility;
  26700. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26701. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26702. var RSValues = this._gamepad.rightStick;
  26703. var normalizedRX = RSValues.x / this.angularSensibility;
  26704. var normalizedRY = RSValues.y / this.angularSensibility;
  26705. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26706. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26707. ;
  26708. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26709. var speed = this._computeLocalCameraSpeed() * 50.0;
  26710. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26711. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26712. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26713. };
  26714. GamepadCamera.prototype.dispose = function () {
  26715. this._gamepads.dispose();
  26716. _super.prototype.dispose.call(this);
  26717. };
  26718. return GamepadCamera;
  26719. })(BABYLON.FreeCamera);
  26720. BABYLON.GamepadCamera = GamepadCamera;
  26721. })(BABYLON || (BABYLON = {}));
  26722. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26723. var BABYLON;
  26724. (function (BABYLON) {
  26725. var LinesMesh = (function (_super) {
  26726. __extends(LinesMesh, _super);
  26727. function LinesMesh(name, scene, updatable) {
  26728. if (updatable === void 0) { updatable = false; }
  26729. _super.call(this, name, scene);
  26730. this.color = new BABYLON.Color3(1, 1, 1);
  26731. this.alpha = 1;
  26732. this._indices = new Array();
  26733. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26734. attributes: ["position"],
  26735. uniforms: ["worldViewProjection", "color"],
  26736. needAlphaBlending: true
  26737. });
  26738. }
  26739. Object.defineProperty(LinesMesh.prototype, "material", {
  26740. get: function () {
  26741. return this._colorShader;
  26742. },
  26743. enumerable: true,
  26744. configurable: true
  26745. });
  26746. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26747. get: function () {
  26748. return false;
  26749. },
  26750. enumerable: true,
  26751. configurable: true
  26752. });
  26753. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26754. get: function () {
  26755. return false;
  26756. },
  26757. enumerable: true,
  26758. configurable: true
  26759. });
  26760. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26761. var engine = this.getScene().getEngine();
  26762. var indexToBind = this._geometry.getIndexBuffer();
  26763. // VBOs
  26764. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26765. // Color
  26766. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26767. };
  26768. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26769. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26770. return;
  26771. }
  26772. var engine = this.getScene().getEngine();
  26773. // Draw order
  26774. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26775. };
  26776. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26777. return null;
  26778. };
  26779. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26780. this._colorShader.dispose();
  26781. _super.prototype.dispose.call(this, doNotRecurse);
  26782. };
  26783. return LinesMesh;
  26784. })(BABYLON.Mesh);
  26785. BABYLON.LinesMesh = LinesMesh;
  26786. })(BABYLON || (BABYLON = {}));
  26787. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26788. (function (BABYLON) {
  26789. var OutlineRenderer = (function () {
  26790. function OutlineRenderer(scene) {
  26791. this._scene = scene;
  26792. }
  26793. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26794. var _this = this;
  26795. if (useOverlay === void 0) { useOverlay = false; }
  26796. var scene = this._scene;
  26797. var engine = this._scene.getEngine();
  26798. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26799. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26800. return;
  26801. }
  26802. var mesh = subMesh.getRenderingMesh();
  26803. var material = subMesh.getMaterial();
  26804. engine.enableEffect(this._effect);
  26805. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26806. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26807. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26808. // Bones
  26809. if (mesh.useBones) {
  26810. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26811. }
  26812. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26813. // Alpha test
  26814. if (material && material.needAlphaTesting()) {
  26815. var alphaTexture = material.getAlphaTestTexture();
  26816. this._effect.setTexture("diffuseSampler", alphaTexture);
  26817. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26818. }
  26819. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26820. _this._effect.setMatrix("world", world);
  26821. });
  26822. };
  26823. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26824. var defines = [];
  26825. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26826. var mesh = subMesh.getMesh();
  26827. var material = subMesh.getMaterial();
  26828. // Alpha test
  26829. if (material && material.needAlphaTesting()) {
  26830. defines.push("#define ALPHATEST");
  26831. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26832. attribs.push(BABYLON.VertexBuffer.UVKind);
  26833. defines.push("#define UV1");
  26834. }
  26835. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26836. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26837. defines.push("#define UV2");
  26838. }
  26839. }
  26840. // Bones
  26841. if (mesh.useBones) {
  26842. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26843. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26844. defines.push("#define BONES");
  26845. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26846. }
  26847. // Instances
  26848. if (useInstances) {
  26849. defines.push("#define INSTANCES");
  26850. attribs.push("world0");
  26851. attribs.push("world1");
  26852. attribs.push("world2");
  26853. attribs.push("world3");
  26854. }
  26855. // Get correct effect
  26856. var join = defines.join("\n");
  26857. if (this._cachedDefines !== join) {
  26858. this._cachedDefines = join;
  26859. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26860. }
  26861. return this._effect.isReady();
  26862. };
  26863. return OutlineRenderer;
  26864. })();
  26865. BABYLON.OutlineRenderer = OutlineRenderer;
  26866. })(BABYLON || (BABYLON = {}));
  26867. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26868. (function (BABYLON) {
  26869. var MeshAssetTask = (function () {
  26870. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26871. this.name = name;
  26872. this.meshesNames = meshesNames;
  26873. this.rootUrl = rootUrl;
  26874. this.sceneFilename = sceneFilename;
  26875. this.isCompleted = false;
  26876. }
  26877. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26878. var _this = this;
  26879. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26880. _this.loadedMeshes = meshes;
  26881. _this.loadedParticleSystems = particleSystems;
  26882. _this.loadedSkeletons = skeletons;
  26883. _this.isCompleted = true;
  26884. if (_this.onSuccess) {
  26885. _this.onSuccess(_this);
  26886. }
  26887. onSuccess();
  26888. }, null, function () {
  26889. if (_this.onError) {
  26890. _this.onError(_this);
  26891. }
  26892. onError();
  26893. });
  26894. };
  26895. return MeshAssetTask;
  26896. })();
  26897. BABYLON.MeshAssetTask = MeshAssetTask;
  26898. var TextFileAssetTask = (function () {
  26899. function TextFileAssetTask(name, url) {
  26900. this.name = name;
  26901. this.url = url;
  26902. this.isCompleted = false;
  26903. }
  26904. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26905. var _this = this;
  26906. BABYLON.Tools.LoadFile(this.url, function (data) {
  26907. _this.text = data;
  26908. _this.isCompleted = true;
  26909. if (_this.onSuccess) {
  26910. _this.onSuccess(_this);
  26911. }
  26912. onSuccess();
  26913. }, null, scene.database, false, function () {
  26914. if (_this.onError) {
  26915. _this.onError(_this);
  26916. }
  26917. onError();
  26918. });
  26919. };
  26920. return TextFileAssetTask;
  26921. })();
  26922. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26923. var BinaryFileAssetTask = (function () {
  26924. function BinaryFileAssetTask(name, url) {
  26925. this.name = name;
  26926. this.url = url;
  26927. this.isCompleted = false;
  26928. }
  26929. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26930. var _this = this;
  26931. BABYLON.Tools.LoadFile(this.url, function (data) {
  26932. _this.data = data;
  26933. _this.isCompleted = true;
  26934. if (_this.onSuccess) {
  26935. _this.onSuccess(_this);
  26936. }
  26937. onSuccess();
  26938. }, null, scene.database, true, function () {
  26939. if (_this.onError) {
  26940. _this.onError(_this);
  26941. }
  26942. onError();
  26943. });
  26944. };
  26945. return BinaryFileAssetTask;
  26946. })();
  26947. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26948. var ImageAssetTask = (function () {
  26949. function ImageAssetTask(name, url) {
  26950. this.name = name;
  26951. this.url = url;
  26952. this.isCompleted = false;
  26953. }
  26954. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26955. var _this = this;
  26956. var img = new Image();
  26957. img.onload = function () {
  26958. _this.image = img;
  26959. _this.isCompleted = true;
  26960. if (_this.onSuccess) {
  26961. _this.onSuccess(_this);
  26962. }
  26963. onSuccess();
  26964. };
  26965. img.onerror = function () {
  26966. if (_this.onError) {
  26967. _this.onError(_this);
  26968. }
  26969. onError();
  26970. };
  26971. img.src = this.url;
  26972. };
  26973. return ImageAssetTask;
  26974. })();
  26975. BABYLON.ImageAssetTask = ImageAssetTask;
  26976. var TextureAssetTask = (function () {
  26977. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26978. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26979. this.name = name;
  26980. this.url = url;
  26981. this.noMipmap = noMipmap;
  26982. this.invertY = invertY;
  26983. this.samplingMode = samplingMode;
  26984. this.isCompleted = false;
  26985. }
  26986. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26987. var _this = this;
  26988. var onload = function () {
  26989. _this.isCompleted = true;
  26990. if (_this.onSuccess) {
  26991. _this.onSuccess(_this);
  26992. }
  26993. onSuccess();
  26994. };
  26995. var onerror = function () {
  26996. if (_this.onError) {
  26997. _this.onError(_this);
  26998. }
  26999. onError();
  27000. };
  27001. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  27002. };
  27003. return TextureAssetTask;
  27004. })();
  27005. BABYLON.TextureAssetTask = TextureAssetTask;
  27006. var AssetsManager = (function () {
  27007. function AssetsManager(scene) {
  27008. this._tasks = new Array();
  27009. this._waitingTasksCount = 0;
  27010. this.useDefaultLoadingScreen = true;
  27011. this._scene = scene;
  27012. }
  27013. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  27014. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  27015. this._tasks.push(task);
  27016. return task;
  27017. };
  27018. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  27019. var task = new TextFileAssetTask(taskName, url);
  27020. this._tasks.push(task);
  27021. return task;
  27022. };
  27023. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  27024. var task = new BinaryFileAssetTask(taskName, url);
  27025. this._tasks.push(task);
  27026. return task;
  27027. };
  27028. AssetsManager.prototype.addImageTask = function (taskName, url) {
  27029. var task = new ImageAssetTask(taskName, url);
  27030. this._tasks.push(task);
  27031. return task;
  27032. };
  27033. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  27034. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27035. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  27036. this._tasks.push(task);
  27037. return task;
  27038. };
  27039. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  27040. this._waitingTasksCount--;
  27041. if (this._waitingTasksCount === 0) {
  27042. if (this.onFinish) {
  27043. this.onFinish(this._tasks);
  27044. }
  27045. this._scene.getEngine().hideLoadingUI();
  27046. }
  27047. };
  27048. AssetsManager.prototype._runTask = function (task) {
  27049. var _this = this;
  27050. task.run(this._scene, function () {
  27051. if (_this.onTaskSuccess) {
  27052. _this.onTaskSuccess(task);
  27053. }
  27054. _this._decreaseWaitingTasksCount();
  27055. }, function () {
  27056. if (_this.onTaskError) {
  27057. _this.onTaskError(task);
  27058. }
  27059. _this._decreaseWaitingTasksCount();
  27060. });
  27061. };
  27062. AssetsManager.prototype.reset = function () {
  27063. this._tasks = new Array();
  27064. return this;
  27065. };
  27066. AssetsManager.prototype.load = function () {
  27067. this._waitingTasksCount = this._tasks.length;
  27068. if (this._waitingTasksCount === 0) {
  27069. if (this.onFinish) {
  27070. this.onFinish(this._tasks);
  27071. }
  27072. return this;
  27073. }
  27074. if (this.useDefaultLoadingScreen) {
  27075. this._scene.getEngine().displayLoadingUI();
  27076. }
  27077. for (var index = 0; index < this._tasks.length; index++) {
  27078. var task = this._tasks[index];
  27079. this._runTask(task);
  27080. }
  27081. return this;
  27082. };
  27083. return AssetsManager;
  27084. })();
  27085. BABYLON.AssetsManager = AssetsManager;
  27086. })(BABYLON || (BABYLON = {}));
  27087. //# sourceMappingURL=babylon.assetsManager.js.map
  27088. var BABYLON;
  27089. (function (BABYLON) {
  27090. var VRDeviceOrientationCamera = (function (_super) {
  27091. __extends(VRDeviceOrientationCamera, _super);
  27092. function VRDeviceOrientationCamera(name, position, scene) {
  27093. _super.call(this, name, position, scene);
  27094. this._alpha = 0;
  27095. this._beta = 0;
  27096. this._gamma = 0;
  27097. }
  27098. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  27099. this._alpha = +evt.alpha | 0;
  27100. this._beta = +evt.beta | 0;
  27101. this._gamma = +evt.gamma | 0;
  27102. if (this._gamma < 0) {
  27103. this._gamma = 90 + this._gamma;
  27104. }
  27105. else {
  27106. // Incline it in the correct angle.
  27107. this._gamma = 270 - this._gamma;
  27108. }
  27109. this.rotation.x = this._gamma / 180.0 * Math.PI;
  27110. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  27111. this.rotation.z = this._beta / 180.0 * Math.PI;
  27112. };
  27113. return VRDeviceOrientationCamera;
  27114. })(BABYLON.OculusCamera);
  27115. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  27116. })(BABYLON || (BABYLON = {}));
  27117. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  27118. var BABYLON;
  27119. (function (BABYLON) {
  27120. var WebVRCamera = (function (_super) {
  27121. __extends(WebVRCamera, _super);
  27122. function WebVRCamera(name, position, scene) {
  27123. _super.call(this, name, position, scene);
  27124. this._hmdDevice = null;
  27125. this._sensorDevice = null;
  27126. this._cacheState = null;
  27127. this._cacheQuaternion = new BABYLON.Quaternion();
  27128. this._cacheRotation = BABYLON.Vector3.Zero();
  27129. this._vrEnabled = false;
  27130. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  27131. }
  27132. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  27133. var size = devices.length;
  27134. var i = 0;
  27135. // Reset devices.
  27136. this._sensorDevice = null;
  27137. this._hmdDevice = null;
  27138. while (i < size && this._hmdDevice === null) {
  27139. if (devices[i] instanceof HMDVRDevice) {
  27140. this._hmdDevice = devices[i];
  27141. }
  27142. i++;
  27143. }
  27144. i = 0;
  27145. while (i < size && this._sensorDevice === null) {
  27146. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  27147. this._sensorDevice = devices[i];
  27148. }
  27149. i++;
  27150. }
  27151. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  27152. };
  27153. WebVRCamera.prototype._update = function () {
  27154. if (this._vrEnabled) {
  27155. this._cacheState = this._sensorDevice.getState();
  27156. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  27157. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  27158. this.rotation.x = -this._cacheRotation.z;
  27159. this.rotation.y = -this._cacheRotation.y;
  27160. this.rotation.z = this._cacheRotation.x;
  27161. }
  27162. _super.prototype._update.call(this);
  27163. };
  27164. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  27165. _super.prototype.attachControl.call(this, element, noPreventDefault);
  27166. if (navigator.getVRDevices) {
  27167. navigator.getVRDevices().then(this._getWebVRDevices);
  27168. }
  27169. else if (navigator.mozGetVRDevices) {
  27170. navigator.mozGetVRDevices(this._getWebVRDevices);
  27171. }
  27172. };
  27173. WebVRCamera.prototype.detachControl = function (element) {
  27174. _super.prototype.detachControl.call(this, element);
  27175. this._vrEnabled = false;
  27176. };
  27177. return WebVRCamera;
  27178. })(BABYLON.OculusCamera);
  27179. BABYLON.WebVRCamera = WebVRCamera;
  27180. })(BABYLON || (BABYLON = {}));
  27181. //# sourceMappingURL=babylon.webVRCamera.js.map
  27182. var BABYLON;
  27183. (function (BABYLON) {
  27184. // Standard optimizations
  27185. var SceneOptimization = (function () {
  27186. function SceneOptimization(priority) {
  27187. if (priority === void 0) { priority = 0; }
  27188. this.priority = priority;
  27189. this.apply = function (scene) {
  27190. return true; // Return true if everything that can be done was applied
  27191. };
  27192. }
  27193. return SceneOptimization;
  27194. })();
  27195. BABYLON.SceneOptimization = SceneOptimization;
  27196. var TextureOptimization = (function (_super) {
  27197. __extends(TextureOptimization, _super);
  27198. function TextureOptimization(priority, maximumSize) {
  27199. var _this = this;
  27200. if (priority === void 0) { priority = 0; }
  27201. if (maximumSize === void 0) { maximumSize = 1024; }
  27202. _super.call(this, priority);
  27203. this.priority = priority;
  27204. this.maximumSize = maximumSize;
  27205. this.apply = function (scene) {
  27206. var allDone = true;
  27207. for (var index = 0; index < scene.textures.length; index++) {
  27208. var texture = scene.textures[index];
  27209. if (!texture.canRescale) {
  27210. continue;
  27211. }
  27212. var currentSize = texture.getSize();
  27213. var maxDimension = Math.max(currentSize.width, currentSize.height);
  27214. if (maxDimension > _this.maximumSize) {
  27215. texture.scale(0.5);
  27216. allDone = false;
  27217. }
  27218. }
  27219. return allDone;
  27220. };
  27221. }
  27222. return TextureOptimization;
  27223. })(SceneOptimization);
  27224. BABYLON.TextureOptimization = TextureOptimization;
  27225. var HardwareScalingOptimization = (function (_super) {
  27226. __extends(HardwareScalingOptimization, _super);
  27227. function HardwareScalingOptimization(priority, maximumScale) {
  27228. var _this = this;
  27229. if (priority === void 0) { priority = 0; }
  27230. if (maximumScale === void 0) { maximumScale = 2; }
  27231. _super.call(this, priority);
  27232. this.priority = priority;
  27233. this.maximumScale = maximumScale;
  27234. this._currentScale = 1;
  27235. this.apply = function (scene) {
  27236. _this._currentScale++;
  27237. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  27238. return _this._currentScale >= _this.maximumScale;
  27239. };
  27240. }
  27241. return HardwareScalingOptimization;
  27242. })(SceneOptimization);
  27243. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  27244. var ShadowsOptimization = (function (_super) {
  27245. __extends(ShadowsOptimization, _super);
  27246. function ShadowsOptimization() {
  27247. _super.apply(this, arguments);
  27248. this.apply = function (scene) {
  27249. scene.shadowsEnabled = false;
  27250. return true;
  27251. };
  27252. }
  27253. return ShadowsOptimization;
  27254. })(SceneOptimization);
  27255. BABYLON.ShadowsOptimization = ShadowsOptimization;
  27256. var PostProcessesOptimization = (function (_super) {
  27257. __extends(PostProcessesOptimization, _super);
  27258. function PostProcessesOptimization() {
  27259. _super.apply(this, arguments);
  27260. this.apply = function (scene) {
  27261. scene.postProcessesEnabled = false;
  27262. return true;
  27263. };
  27264. }
  27265. return PostProcessesOptimization;
  27266. })(SceneOptimization);
  27267. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  27268. var LensFlaresOptimization = (function (_super) {
  27269. __extends(LensFlaresOptimization, _super);
  27270. function LensFlaresOptimization() {
  27271. _super.apply(this, arguments);
  27272. this.apply = function (scene) {
  27273. scene.lensFlaresEnabled = false;
  27274. return true;
  27275. };
  27276. }
  27277. return LensFlaresOptimization;
  27278. })(SceneOptimization);
  27279. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  27280. var ParticlesOptimization = (function (_super) {
  27281. __extends(ParticlesOptimization, _super);
  27282. function ParticlesOptimization() {
  27283. _super.apply(this, arguments);
  27284. this.apply = function (scene) {
  27285. scene.particlesEnabled = false;
  27286. return true;
  27287. };
  27288. }
  27289. return ParticlesOptimization;
  27290. })(SceneOptimization);
  27291. BABYLON.ParticlesOptimization = ParticlesOptimization;
  27292. var RenderTargetsOptimization = (function (_super) {
  27293. __extends(RenderTargetsOptimization, _super);
  27294. function RenderTargetsOptimization() {
  27295. _super.apply(this, arguments);
  27296. this.apply = function (scene) {
  27297. scene.renderTargetsEnabled = false;
  27298. return true;
  27299. };
  27300. }
  27301. return RenderTargetsOptimization;
  27302. })(SceneOptimization);
  27303. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  27304. var MergeMeshesOptimization = (function (_super) {
  27305. __extends(MergeMeshesOptimization, _super);
  27306. function MergeMeshesOptimization() {
  27307. var _this = this;
  27308. _super.apply(this, arguments);
  27309. this._canBeMerged = function (abstractMesh) {
  27310. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  27311. return false;
  27312. }
  27313. var mesh = abstractMesh;
  27314. if (!mesh.isVisible || !mesh.isEnabled()) {
  27315. return false;
  27316. }
  27317. if (mesh.instances.length > 0) {
  27318. return false;
  27319. }
  27320. if (mesh.skeleton || mesh.hasLODLevels) {
  27321. return false;
  27322. }
  27323. return true;
  27324. };
  27325. this.apply = function (scene) {
  27326. var globalPool = scene.meshes.slice(0);
  27327. var globalLength = globalPool.length;
  27328. for (var index = 0; index < globalLength; index++) {
  27329. var currentPool = new Array();
  27330. var current = globalPool[index];
  27331. // Checks
  27332. if (!_this._canBeMerged(current)) {
  27333. continue;
  27334. }
  27335. currentPool.push(current);
  27336. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27337. var otherMesh = globalPool[subIndex];
  27338. if (!_this._canBeMerged(otherMesh)) {
  27339. continue;
  27340. }
  27341. if (otherMesh.material !== current.material) {
  27342. continue;
  27343. }
  27344. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27345. continue;
  27346. }
  27347. currentPool.push(otherMesh);
  27348. globalLength--;
  27349. globalPool.splice(subIndex, 1);
  27350. subIndex--;
  27351. }
  27352. if (currentPool.length < 2) {
  27353. continue;
  27354. }
  27355. // Merge meshes
  27356. BABYLON.Mesh.MergeMeshes(currentPool);
  27357. }
  27358. return true;
  27359. };
  27360. }
  27361. return MergeMeshesOptimization;
  27362. })(SceneOptimization);
  27363. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27364. // Options
  27365. var SceneOptimizerOptions = (function () {
  27366. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27367. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27368. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27369. this.targetFrameRate = targetFrameRate;
  27370. this.trackerDuration = trackerDuration;
  27371. this.optimizations = new Array();
  27372. }
  27373. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27374. var result = new SceneOptimizerOptions(targetFrameRate);
  27375. var priority = 0;
  27376. result.optimizations.push(new MergeMeshesOptimization(priority));
  27377. result.optimizations.push(new ShadowsOptimization(priority));
  27378. result.optimizations.push(new LensFlaresOptimization(priority));
  27379. // Next priority
  27380. priority++;
  27381. result.optimizations.push(new PostProcessesOptimization(priority));
  27382. result.optimizations.push(new ParticlesOptimization(priority));
  27383. // Next priority
  27384. priority++;
  27385. result.optimizations.push(new TextureOptimization(priority, 1024));
  27386. return result;
  27387. };
  27388. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27389. var result = new SceneOptimizerOptions(targetFrameRate);
  27390. var priority = 0;
  27391. result.optimizations.push(new MergeMeshesOptimization(priority));
  27392. result.optimizations.push(new ShadowsOptimization(priority));
  27393. result.optimizations.push(new LensFlaresOptimization(priority));
  27394. // Next priority
  27395. priority++;
  27396. result.optimizations.push(new PostProcessesOptimization(priority));
  27397. result.optimizations.push(new ParticlesOptimization(priority));
  27398. // Next priority
  27399. priority++;
  27400. result.optimizations.push(new TextureOptimization(priority, 512));
  27401. // Next priority
  27402. priority++;
  27403. result.optimizations.push(new RenderTargetsOptimization(priority));
  27404. // Next priority
  27405. priority++;
  27406. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27407. return result;
  27408. };
  27409. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27410. var result = new SceneOptimizerOptions(targetFrameRate);
  27411. var priority = 0;
  27412. result.optimizations.push(new MergeMeshesOptimization(priority));
  27413. result.optimizations.push(new ShadowsOptimization(priority));
  27414. result.optimizations.push(new LensFlaresOptimization(priority));
  27415. // Next priority
  27416. priority++;
  27417. result.optimizations.push(new PostProcessesOptimization(priority));
  27418. result.optimizations.push(new ParticlesOptimization(priority));
  27419. // Next priority
  27420. priority++;
  27421. result.optimizations.push(new TextureOptimization(priority, 256));
  27422. // Next priority
  27423. priority++;
  27424. result.optimizations.push(new RenderTargetsOptimization(priority));
  27425. // Next priority
  27426. priority++;
  27427. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27428. return result;
  27429. };
  27430. return SceneOptimizerOptions;
  27431. })();
  27432. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27433. // Scene optimizer tool
  27434. var SceneOptimizer = (function () {
  27435. function SceneOptimizer() {
  27436. }
  27437. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27438. // TODO: add an epsilon
  27439. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27440. if (onSuccess) {
  27441. onSuccess();
  27442. }
  27443. return;
  27444. }
  27445. // Apply current level of optimizations
  27446. var allDone = true;
  27447. var noOptimizationApplied = true;
  27448. for (var index = 0; index < options.optimizations.length; index++) {
  27449. var optimization = options.optimizations[index];
  27450. if (optimization.priority === currentPriorityLevel) {
  27451. noOptimizationApplied = false;
  27452. allDone = allDone && optimization.apply(scene);
  27453. }
  27454. }
  27455. // If no optimization was applied, this is a failure :(
  27456. if (noOptimizationApplied) {
  27457. if (onFailure) {
  27458. onFailure();
  27459. }
  27460. return;
  27461. }
  27462. // If all optimizations were done, move to next level
  27463. if (allDone) {
  27464. currentPriorityLevel++;
  27465. }
  27466. // Let's the system running for a specific amount of time before checking FPS
  27467. scene.executeWhenReady(function () {
  27468. setTimeout(function () {
  27469. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27470. }, options.trackerDuration);
  27471. });
  27472. };
  27473. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27474. if (!options) {
  27475. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27476. }
  27477. // Let's the system running for a specific amount of time before checking FPS
  27478. scene.executeWhenReady(function () {
  27479. setTimeout(function () {
  27480. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27481. }, options.trackerDuration);
  27482. });
  27483. };
  27484. return SceneOptimizer;
  27485. })();
  27486. BABYLON.SceneOptimizer = SceneOptimizer;
  27487. })(BABYLON || (BABYLON = {}));
  27488. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27489. (function (BABYLON) {
  27490. var Internals;
  27491. (function (Internals) {
  27492. var MeshLODLevel = (function () {
  27493. function MeshLODLevel(distance, mesh) {
  27494. this.distance = distance;
  27495. this.mesh = mesh;
  27496. }
  27497. return MeshLODLevel;
  27498. })();
  27499. Internals.MeshLODLevel = MeshLODLevel;
  27500. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27501. })(BABYLON || (BABYLON = {}));
  27502. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27503. (function (BABYLON) {
  27504. var AudioEngine = (function () {
  27505. function AudioEngine() {
  27506. this._audioContext = null;
  27507. this._audioContextInitialized = false;
  27508. this.canUseWebAudio = false;
  27509. this.WarnedWebAudioUnsupported = false;
  27510. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  27511. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  27512. this.canUseWebAudio = true;
  27513. }
  27514. }
  27515. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  27516. get: function () {
  27517. if (!this._audioContextInitialized) {
  27518. this._initializeAudioContext();
  27519. }
  27520. return this._audioContext;
  27521. },
  27522. enumerable: true,
  27523. configurable: true
  27524. });
  27525. AudioEngine.prototype._initializeAudioContext = function () {
  27526. try {
  27527. if (this.canUseWebAudio) {
  27528. this._audioContext = new AudioContext();
  27529. // create a global volume gain node
  27530. this.masterGain = this._audioContext.createGain();
  27531. this.masterGain.gain.value = 1;
  27532. this.masterGain.connect(this._audioContext.destination);
  27533. this._audioContextInitialized = true;
  27534. }
  27535. }
  27536. catch (e) {
  27537. this.canUseWebAudio = false;
  27538. BABYLON.Tools.Error("Web Audio: " + e.message);
  27539. }
  27540. };
  27541. AudioEngine.prototype.dispose = function () {
  27542. if (this.canUseWebAudio && this._audioContextInitialized) {
  27543. if (this._connectedAnalyser) {
  27544. this._connectedAnalyser.stopDebugCanvas();
  27545. this._connectedAnalyser.dispose();
  27546. this.masterGain.disconnect();
  27547. this.masterGain.connect(this._audioContext.destination);
  27548. this._connectedAnalyser = null;
  27549. }
  27550. this.masterGain.gain.value = 1;
  27551. }
  27552. this.WarnedWebAudioUnsupported = false;
  27553. };
  27554. AudioEngine.prototype.getGlobalVolume = function () {
  27555. if (this.canUseWebAudio && this._audioContextInitialized) {
  27556. return this.masterGain.gain.value;
  27557. }
  27558. else {
  27559. return -1;
  27560. }
  27561. };
  27562. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27563. if (this.canUseWebAudio && this._audioContextInitialized) {
  27564. this.masterGain.gain.value = newVolume;
  27565. }
  27566. };
  27567. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27568. if (this._connectedAnalyser) {
  27569. this._connectedAnalyser.stopDebugCanvas();
  27570. }
  27571. if (this.canUseWebAudio && this._audioContextInitialized) {
  27572. this._connectedAnalyser = analyser;
  27573. this.masterGain.disconnect();
  27574. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  27575. }
  27576. };
  27577. return AudioEngine;
  27578. })();
  27579. BABYLON.AudioEngine = AudioEngine;
  27580. })(BABYLON || (BABYLON = {}));
  27581. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27582. (function (BABYLON) {
  27583. var Sound = (function () {
  27584. /**
  27585. * Create a sound and attach it to a scene
  27586. * @param name Name of your sound
  27587. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27588. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27589. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27590. */
  27591. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27592. var _this = this;
  27593. this.autoplay = false;
  27594. this.loop = false;
  27595. this.useCustomAttenuation = false;
  27596. this.spatialSound = false;
  27597. this.refDistance = 1;
  27598. this.rolloffFactor = 1;
  27599. this.maxDistance = 100;
  27600. this.distanceModel = "linear";
  27601. this._panningModel = "equalpower";
  27602. this._playbackRate = 1;
  27603. this._startTime = 0;
  27604. this._startOffset = 0;
  27605. this._position = BABYLON.Vector3.Zero();
  27606. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27607. this._volume = 1;
  27608. this._isLoaded = false;
  27609. this._isReadyToPlay = false;
  27610. this.isPlaying = false;
  27611. this.isPaused = false;
  27612. this._isDirectional = false;
  27613. // Used if you'd like to create a directional sound.
  27614. // If not set, the sound will be omnidirectional
  27615. this._coneInnerAngle = 360;
  27616. this._coneOuterAngle = 360;
  27617. this._coneOuterGain = 0;
  27618. this.name = name;
  27619. this._scene = scene;
  27620. this._readyToPlayCallback = readyToPlayCallback;
  27621. // Default custom attenuation function is a linear attenuation
  27622. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27623. if (currentDistance < maxDistance) {
  27624. return currentVolume * (1 - currentDistance / maxDistance);
  27625. }
  27626. else {
  27627. return 0;
  27628. }
  27629. };
  27630. if (options) {
  27631. this.autoplay = options.autoplay || false;
  27632. this.loop = options.loop || false;
  27633. // if volume === 0, we need another way to check this option
  27634. if (options.volume !== undefined) {
  27635. this._volume = options.volume;
  27636. }
  27637. this.spatialSound = options.spatialSound || false;
  27638. this.maxDistance = options.maxDistance || 100;
  27639. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27640. this.rolloffFactor = options.rolloffFactor || 1;
  27641. this.refDistance = options.refDistance || 1;
  27642. this.distanceModel = options.distanceModel || "linear";
  27643. this._playbackRate = options.playbackRate || 1;
  27644. }
  27645. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27646. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27647. this._soundGain.gain.value = this._volume;
  27648. this._inputAudioNode = this._soundGain;
  27649. this._ouputAudioNode = this._soundGain;
  27650. if (this.spatialSound) {
  27651. this._createSpatialParameters();
  27652. }
  27653. this._scene.mainSoundTrack.AddSound(this);
  27654. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27655. if (urlOrArrayBuffer) {
  27656. // If it's an URL
  27657. if (typeof (urlOrArrayBuffer) === "string") {
  27658. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27659. _this._soundLoaded(data);
  27660. }, null, null, true);
  27661. }
  27662. else {
  27663. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27664. this._soundLoaded(urlOrArrayBuffer);
  27665. }
  27666. else {
  27667. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27668. }
  27669. }
  27670. }
  27671. }
  27672. else {
  27673. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27674. this._scene.mainSoundTrack.AddSound(this);
  27675. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27676. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27677. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27678. }
  27679. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27680. if (this._readyToPlayCallback) {
  27681. window.setTimeout(function () {
  27682. _this._readyToPlayCallback();
  27683. }, 1000);
  27684. }
  27685. }
  27686. }
  27687. Sound.prototype.dispose = function () {
  27688. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27689. if (this.isPlaying) {
  27690. this.stop();
  27691. }
  27692. this._isReadyToPlay = false;
  27693. if (this.soundTrackId === -1) {
  27694. this._scene.mainSoundTrack.RemoveSound(this);
  27695. }
  27696. else {
  27697. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27698. }
  27699. if (this._soundGain) {
  27700. this._soundGain.disconnect();
  27701. this._soundGain = null;
  27702. }
  27703. if (this._soundPanner) {
  27704. this._soundPanner.disconnect();
  27705. this._soundPanner = null;
  27706. }
  27707. if (this._soundSource) {
  27708. this._soundSource.disconnect();
  27709. this._soundSource = null;
  27710. }
  27711. this._audioBuffer = null;
  27712. if (this._connectedMesh) {
  27713. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27714. this._connectedMesh = null;
  27715. }
  27716. }
  27717. };
  27718. Sound.prototype._soundLoaded = function (audioData) {
  27719. var _this = this;
  27720. this._isLoaded = true;
  27721. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27722. _this._audioBuffer = buffer;
  27723. _this._isReadyToPlay = true;
  27724. if (_this.autoplay) {
  27725. _this.play();
  27726. }
  27727. if (_this._readyToPlayCallback) {
  27728. _this._readyToPlayCallback();
  27729. }
  27730. }, function (error) {
  27731. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27732. });
  27733. };
  27734. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27735. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27736. this._audioBuffer = audioBuffer;
  27737. this._isReadyToPlay = true;
  27738. }
  27739. };
  27740. Sound.prototype.updateOptions = function (options) {
  27741. if (options) {
  27742. this.loop = options.loop || this.loop;
  27743. this.maxDistance = options.maxDistance || this.maxDistance;
  27744. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27745. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27746. this.refDistance = options.refDistance || this.refDistance;
  27747. this.distanceModel = options.distanceModel || this.distanceModel;
  27748. this._playbackRate = options.playbackRate || this._playbackRate;
  27749. }
  27750. };
  27751. Sound.prototype._createSpatialParameters = function () {
  27752. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27753. if (this._scene.headphone) {
  27754. this._panningModel = "HRTF";
  27755. }
  27756. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27757. if (this.useCustomAttenuation) {
  27758. // Tricks to disable in a way embedded Web Audio attenuation
  27759. this._soundPanner.distanceModel = "linear";
  27760. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27761. this._soundPanner.refDistance = 1;
  27762. this._soundPanner.rolloffFactor = 1;
  27763. this._soundPanner.panningModel = this._panningModel;
  27764. }
  27765. else {
  27766. this._soundPanner.distanceModel = this.distanceModel;
  27767. this._soundPanner.maxDistance = this.maxDistance;
  27768. this._soundPanner.refDistance = this.refDistance;
  27769. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27770. this._soundPanner.panningModel = this._panningModel;
  27771. }
  27772. this._soundPanner.connect(this._ouputAudioNode);
  27773. this._inputAudioNode = this._soundPanner;
  27774. }
  27775. };
  27776. Sound.prototype.switchPanningModelToHRTF = function () {
  27777. this._panningModel = "HRTF";
  27778. this._switchPanningModel();
  27779. };
  27780. Sound.prototype.switchPanningModelToEqualPower = function () {
  27781. this._panningModel = "equalpower";
  27782. this._switchPanningModel();
  27783. };
  27784. Sound.prototype._switchPanningModel = function () {
  27785. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27786. this._soundPanner.panningModel = this._panningModel;
  27787. }
  27788. };
  27789. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27790. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27791. this._ouputAudioNode.disconnect();
  27792. this._ouputAudioNode.connect(soundTrackAudioNode);
  27793. }
  27794. };
  27795. /**
  27796. * Transform this sound into a directional source
  27797. * @param coneInnerAngle Size of the inner cone in degree
  27798. * @param coneOuterAngle Size of the outer cone in degree
  27799. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27800. */
  27801. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27802. if (coneOuterAngle < coneInnerAngle) {
  27803. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27804. return;
  27805. }
  27806. this._coneInnerAngle = coneInnerAngle;
  27807. this._coneOuterAngle = coneOuterAngle;
  27808. this._coneOuterGain = coneOuterGain;
  27809. this._isDirectional = true;
  27810. if (this.isPlaying && this.loop) {
  27811. this.stop();
  27812. this.play();
  27813. }
  27814. };
  27815. Sound.prototype.setPosition = function (newPosition) {
  27816. this._position = newPosition;
  27817. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27818. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27819. }
  27820. };
  27821. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27822. this._localDirection = newLocalDirection;
  27823. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27824. this._updateDirection();
  27825. }
  27826. };
  27827. Sound.prototype._updateDirection = function () {
  27828. var mat = this._connectedMesh.getWorldMatrix();
  27829. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27830. direction.normalize();
  27831. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27832. };
  27833. Sound.prototype.updateDistanceFromListener = function () {
  27834. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27835. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27836. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27837. }
  27838. };
  27839. Sound.prototype.setAttenuationFunction = function (callback) {
  27840. this._customAttenuationFunction = callback;
  27841. };
  27842. /**
  27843. * Play the sound
  27844. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27845. */
  27846. Sound.prototype.play = function (time) {
  27847. var _this = this;
  27848. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27849. try {
  27850. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27851. if (!this._soundSource) {
  27852. if (this.spatialSound) {
  27853. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27854. if (this._isDirectional) {
  27855. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27856. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27857. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27858. if (this._connectedMesh) {
  27859. this._updateDirection();
  27860. }
  27861. else {
  27862. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27863. }
  27864. }
  27865. }
  27866. }
  27867. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27868. this._soundSource.buffer = this._audioBuffer;
  27869. this._soundSource.connect(this._inputAudioNode);
  27870. this._soundSource.loop = this.loop;
  27871. this._soundSource.playbackRate.value = this._playbackRate;
  27872. this._startTime = startTime;
  27873. this._soundSource.onended = function () {
  27874. _this._onended();
  27875. };
  27876. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27877. this.isPlaying = true;
  27878. this.isPaused = false;
  27879. }
  27880. catch (ex) {
  27881. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27882. }
  27883. }
  27884. };
  27885. Sound.prototype._onended = function () {
  27886. this.isPlaying = false;
  27887. if (this.onended) {
  27888. this.onended();
  27889. }
  27890. };
  27891. /**
  27892. * Stop the sound
  27893. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27894. */
  27895. Sound.prototype.stop = function (time) {
  27896. if (this.isPlaying) {
  27897. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27898. this._soundSource.stop(stopTime);
  27899. this.isPlaying = false;
  27900. }
  27901. };
  27902. Sound.prototype.pause = function () {
  27903. if (this.isPlaying) {
  27904. this.stop(0);
  27905. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27906. this.isPaused = true;
  27907. }
  27908. };
  27909. Sound.prototype.setVolume = function (newVolume, time) {
  27910. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27911. if (time) {
  27912. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27913. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27914. }
  27915. else {
  27916. this._soundGain.gain.value = newVolume;
  27917. }
  27918. }
  27919. this._volume = newVolume;
  27920. };
  27921. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27922. this._playbackRate = newPlaybackRate;
  27923. if (this.isPlaying) {
  27924. this._soundSource.playbackRate.value = this._playbackRate;
  27925. }
  27926. };
  27927. Sound.prototype.getVolume = function () {
  27928. return this._volume;
  27929. };
  27930. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27931. var _this = this;
  27932. this._connectedMesh = meshToConnectTo;
  27933. if (!this.spatialSound) {
  27934. this._createSpatialParameters();
  27935. this.spatialSound = true;
  27936. if (this.isPlaying && this.loop) {
  27937. this.stop();
  27938. this.play();
  27939. }
  27940. }
  27941. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27942. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27943. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27944. };
  27945. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27946. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27947. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27948. this._updateDirection();
  27949. }
  27950. };
  27951. return Sound;
  27952. })();
  27953. BABYLON.Sound = Sound;
  27954. })(BABYLON || (BABYLON = {}));
  27955. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27956. (function (BABYLON) {
  27957. var SoundTrack = (function () {
  27958. function SoundTrack(scene, options) {
  27959. this.id = -1;
  27960. this._isMainTrack = false;
  27961. this._scene = scene;
  27962. this._audioEngine = BABYLON.Engine.audioEngine;
  27963. this.soundCollection = new Array();
  27964. if (this._audioEngine.canUseWebAudio) {
  27965. this._trackGain = this._audioEngine.audioContext.createGain();
  27966. this._trackGain.connect(this._audioEngine.masterGain);
  27967. if (options) {
  27968. if (options.volume) {
  27969. this._trackGain.gain.value = options.volume;
  27970. }
  27971. if (options.mainTrack) {
  27972. this._isMainTrack = options.mainTrack;
  27973. }
  27974. }
  27975. }
  27976. if (!this._isMainTrack) {
  27977. this._scene.soundTracks.push(this);
  27978. this.id = this._scene.soundTracks.length - 1;
  27979. }
  27980. }
  27981. SoundTrack.prototype.dispose = function () {
  27982. if (this._audioEngine.canUseWebAudio) {
  27983. if (this._connectedAnalyser) {
  27984. this._connectedAnalyser.stopDebugCanvas();
  27985. }
  27986. while (this.soundCollection.length) {
  27987. this.soundCollection[0].dispose();
  27988. }
  27989. this._trackGain.disconnect();
  27990. this._trackGain = null;
  27991. }
  27992. };
  27993. SoundTrack.prototype.AddSound = function (sound) {
  27994. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27995. sound.connectToSoundTrackAudioNode(this._trackGain);
  27996. }
  27997. if (sound.soundTrackId) {
  27998. if (sound.soundTrackId === -1) {
  27999. this._scene.mainSoundTrack.RemoveSound(sound);
  28000. }
  28001. else {
  28002. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  28003. }
  28004. }
  28005. this.soundCollection.push(sound);
  28006. sound.soundTrackId = this.id;
  28007. };
  28008. SoundTrack.prototype.RemoveSound = function (sound) {
  28009. var index = this.soundCollection.indexOf(sound);
  28010. if (index !== -1) {
  28011. this.soundCollection.splice(index, 1);
  28012. }
  28013. };
  28014. SoundTrack.prototype.setVolume = function (newVolume) {
  28015. if (this._audioEngine.canUseWebAudio) {
  28016. this._trackGain.gain.value = newVolume;
  28017. }
  28018. };
  28019. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  28020. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28021. for (var i = 0; i < this.soundCollection.length; i++) {
  28022. this.soundCollection[i].switchPanningModelToHRTF();
  28023. }
  28024. }
  28025. };
  28026. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  28027. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28028. for (var i = 0; i < this.soundCollection.length; i++) {
  28029. this.soundCollection[i].switchPanningModelToEqualPower();
  28030. }
  28031. }
  28032. };
  28033. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  28034. if (this._connectedAnalyser) {
  28035. this._connectedAnalyser.stopDebugCanvas();
  28036. }
  28037. this._connectedAnalyser = analyser;
  28038. if (this._audioEngine.canUseWebAudio) {
  28039. this._trackGain.disconnect();
  28040. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  28041. }
  28042. };
  28043. return SoundTrack;
  28044. })();
  28045. BABYLON.SoundTrack = SoundTrack;
  28046. })(BABYLON || (BABYLON = {}));
  28047. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  28048. (function (BABYLON) {
  28049. var DebugLayer = (function () {
  28050. function DebugLayer(scene) {
  28051. var _this = this;
  28052. this._transformationMatrix = BABYLON.Matrix.Identity();
  28053. this._enabled = false;
  28054. this._labelsEnabled = false;
  28055. this._displayStatistics = true;
  28056. this._displayTree = false;
  28057. this._displayLogs = false;
  28058. this._identityMatrix = BABYLON.Matrix.Identity();
  28059. this.axisRatio = 0.02;
  28060. this.accentColor = "orange";
  28061. this._scene = scene;
  28062. this._syncPositions = function () {
  28063. var engine = _this._scene.getEngine();
  28064. var canvasRect = engine.getRenderingCanvasClientRect();
  28065. if (_this._showUI) {
  28066. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28067. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28068. _this._statsDiv.style.width = "400px";
  28069. _this._statsDiv.style.height = "auto";
  28070. _this._statsSubsetDiv.style.maxHeight = "240px";
  28071. _this._optionsDiv.style.left = "0px";
  28072. _this._optionsDiv.style.top = "10px";
  28073. _this._optionsDiv.style.width = "200px";
  28074. _this._optionsDiv.style.height = "auto";
  28075. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28076. _this._logDiv.style.left = "0px";
  28077. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28078. _this._logDiv.style.width = "600px";
  28079. _this._logDiv.style.height = "160px";
  28080. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28081. _this._treeDiv.style.top = "10px";
  28082. _this._treeDiv.style.width = "300px";
  28083. _this._treeDiv.style.height = "auto";
  28084. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28085. }
  28086. _this._globalDiv.style.left = canvasRect.left + "px";
  28087. _this._globalDiv.style.top = canvasRect.top + "px";
  28088. _this._drawingCanvas.style.left = "0px";
  28089. _this._drawingCanvas.style.top = "0px";
  28090. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28091. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28092. var devicePixelRatio = window.devicePixelRatio || 1;
  28093. var context = _this._drawingContext;
  28094. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  28095. _this._ratio = devicePixelRatio / backingStoreRatio;
  28096. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28097. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28098. };
  28099. this._onCanvasClick = function (evt) {
  28100. _this._clickPosition = {
  28101. x: evt.clientX * _this._ratio,
  28102. y: evt.clientY * _this._ratio
  28103. };
  28104. };
  28105. this._syncUI = function () {
  28106. if (_this._showUI) {
  28107. if (_this._displayStatistics) {
  28108. _this._displayStats();
  28109. _this._statsDiv.style.display = "";
  28110. }
  28111. else {
  28112. _this._statsDiv.style.display = "none";
  28113. }
  28114. if (_this._displayLogs) {
  28115. _this._logDiv.style.display = "";
  28116. }
  28117. else {
  28118. _this._logDiv.style.display = "none";
  28119. }
  28120. if (_this._displayTree) {
  28121. _this._treeDiv.style.display = "";
  28122. if (_this._needToRefreshMeshesTree) {
  28123. _this._needToRefreshMeshesTree = false;
  28124. _this._refreshMeshesTreeContent();
  28125. }
  28126. }
  28127. else {
  28128. _this._treeDiv.style.display = "none";
  28129. }
  28130. }
  28131. };
  28132. this._syncData = function () {
  28133. if (_this._labelsEnabled || !_this._showUI) {
  28134. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28135. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28136. var engine = _this._scene.getEngine();
  28137. var viewport = _this._camera.viewport;
  28138. var globalViewport = viewport.toGlobal(engine);
  28139. // Meshes
  28140. var meshes = _this._camera.getActiveMeshes();
  28141. for (var index = 0; index < meshes.length; index++) {
  28142. var mesh = meshes.data[index];
  28143. var position = mesh.getBoundingInfo().boundingSphere.center;
  28144. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28145. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28146. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28147. }
  28148. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28149. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  28150. mesh.renderOverlay = !mesh.renderOverlay;
  28151. }, function () {
  28152. return mesh.renderOverlay ? 'red' : 'black';
  28153. });
  28154. }
  28155. }
  28156. // Cameras
  28157. var cameras = _this._scene.cameras;
  28158. for (index = 0; index < cameras.length; index++) {
  28159. var camera = cameras[index];
  28160. if (camera === _this._camera) {
  28161. continue;
  28162. }
  28163. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28164. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28165. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28166. _this._camera.detachControl(engine.getRenderingCanvas());
  28167. _this._camera = camera;
  28168. _this._camera.attachControl(engine.getRenderingCanvas());
  28169. }, function () {
  28170. return "purple";
  28171. });
  28172. }
  28173. }
  28174. // Lights
  28175. var lights = _this._scene.lights;
  28176. for (index = 0; index < lights.length; index++) {
  28177. var light = lights[index];
  28178. if (light.position) {
  28179. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28180. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28181. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28182. light.setEnabled(!light.isEnabled());
  28183. }, function () {
  28184. return light.isEnabled() ? "orange" : "gray";
  28185. });
  28186. }
  28187. }
  28188. }
  28189. }
  28190. _this._clickPosition = undefined;
  28191. };
  28192. }
  28193. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28194. while (this._treeSubsetDiv.hasChildNodes()) {
  28195. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28196. }
  28197. // Add meshes
  28198. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28199. sortedArray.sort(function (a, b) {
  28200. if (a.name === b.name) {
  28201. return 0;
  28202. }
  28203. return (a.name > b.name) ? 1 : -1;
  28204. });
  28205. for (var index = 0; index < sortedArray.length; index++) {
  28206. var mesh = sortedArray[index];
  28207. if (!mesh.isEnabled()) {
  28208. continue;
  28209. }
  28210. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28211. m.isVisible = element.checked;
  28212. }, mesh);
  28213. }
  28214. };
  28215. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28216. this._drawingContext.beginPath();
  28217. this._drawingContext.moveTo(zero.x, zero.y);
  28218. this._drawingContext.lineTo(unit.x, unit.y);
  28219. this._drawingContext.strokeStyle = color;
  28220. this._drawingContext.lineWidth = 4;
  28221. this._drawingContext.stroke();
  28222. this._drawingContext.font = "normal 14px Segoe UI";
  28223. this._drawingContext.fillStyle = color;
  28224. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28225. };
  28226. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28227. var position = mesh.getBoundingInfo().boundingSphere.center;
  28228. var worldMatrix = mesh.getWorldMatrix();
  28229. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28230. var unit = (unprojectedVector.subtract(position)).length();
  28231. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28232. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28233. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28234. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28235. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28236. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28237. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28238. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28239. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28240. };
  28241. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28242. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28243. this._drawingContext.font = "normal 12px Segoe UI";
  28244. var textMetrics = this._drawingContext.measureText(text);
  28245. var centerX = projectedPosition.x - textMetrics.width / 2;
  28246. var centerY = projectedPosition.y;
  28247. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28248. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28249. onClick();
  28250. }
  28251. this._drawingContext.beginPath();
  28252. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28253. this._drawingContext.fillStyle = getFillStyle();
  28254. this._drawingContext.globalAlpha = 0.5;
  28255. this._drawingContext.fill();
  28256. this._drawingContext.globalAlpha = 1.0;
  28257. this._drawingContext.strokeStyle = '#FFFFFF';
  28258. this._drawingContext.lineWidth = 1;
  28259. this._drawingContext.stroke();
  28260. this._drawingContext.fillStyle = "#FFFFFF";
  28261. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28262. this._drawingContext.beginPath();
  28263. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28264. this._drawingContext.fill();
  28265. }
  28266. };
  28267. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28268. if (!this._clickPosition) {
  28269. return false;
  28270. }
  28271. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28272. return false;
  28273. }
  28274. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28275. return false;
  28276. }
  28277. return true;
  28278. };
  28279. DebugLayer.prototype.isVisible = function () {
  28280. return this._enabled;
  28281. };
  28282. DebugLayer.prototype.hide = function () {
  28283. if (!this._enabled) {
  28284. return;
  28285. }
  28286. this._enabled = false;
  28287. var engine = this._scene.getEngine();
  28288. this._scene.unregisterBeforeRender(this._syncData);
  28289. this._scene.unregisterAfterRender(this._syncUI);
  28290. document.body.removeChild(this._globalDiv);
  28291. window.removeEventListener("resize", this._syncPositions);
  28292. this._scene.forceShowBoundingBoxes = false;
  28293. this._scene.forceWireframe = false;
  28294. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28295. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28296. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28297. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28298. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28299. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28300. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28301. this._scene.shadowsEnabled = true;
  28302. this._scene.particlesEnabled = true;
  28303. this._scene.postProcessesEnabled = true;
  28304. this._scene.collisionsEnabled = true;
  28305. this._scene.lightsEnabled = true;
  28306. this._scene.texturesEnabled = true;
  28307. this._scene.lensFlaresEnabled = true;
  28308. this._scene.proceduralTexturesEnabled = true;
  28309. this._scene.renderTargetsEnabled = true;
  28310. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28311. };
  28312. DebugLayer.prototype.show = function (showUI, camera) {
  28313. if (showUI === void 0) { showUI = true; }
  28314. if (camera === void 0) { camera = null; }
  28315. if (this._enabled) {
  28316. return;
  28317. }
  28318. this._enabled = true;
  28319. if (camera) {
  28320. this._camera = camera;
  28321. }
  28322. else {
  28323. this._camera = this._scene.activeCamera;
  28324. }
  28325. this._showUI = showUI;
  28326. var engine = this._scene.getEngine();
  28327. this._globalDiv = document.createElement("div");
  28328. document.body.appendChild(this._globalDiv);
  28329. this._generateDOMelements();
  28330. window.addEventListener("resize", this._syncPositions);
  28331. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28332. this._syncPositions();
  28333. this._scene.registerBeforeRender(this._syncData);
  28334. this._scene.registerAfterRender(this._syncUI);
  28335. };
  28336. DebugLayer.prototype._clearLabels = function () {
  28337. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28338. for (var index = 0; index < this._scene.meshes.length; index++) {
  28339. var mesh = this._scene.meshes[index];
  28340. mesh.renderOverlay = false;
  28341. }
  28342. };
  28343. DebugLayer.prototype._generateheader = function (root, text) {
  28344. var header = document.createElement("div");
  28345. header.innerHTML = text + "&nbsp;";
  28346. header.style.textAlign = "right";
  28347. header.style.width = "100%";
  28348. header.style.color = "white";
  28349. header.style.backgroundColor = "Black";
  28350. header.style.padding = "5px 5px 4px 0px";
  28351. header.style.marginLeft = "-5px";
  28352. header.style.fontWeight = "bold";
  28353. root.appendChild(header);
  28354. };
  28355. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28356. var label = document.createElement("label");
  28357. label.innerHTML = title;
  28358. label.style.color = color;
  28359. root.appendChild(label);
  28360. root.appendChild(document.createElement("br"));
  28361. };
  28362. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28363. if (tag === void 0) { tag = null; }
  28364. var label = document.createElement("label");
  28365. var boundingBoxesCheckbox = document.createElement("input");
  28366. boundingBoxesCheckbox.type = "checkbox";
  28367. boundingBoxesCheckbox.checked = initialState;
  28368. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28369. task(evt.target, tag);
  28370. });
  28371. label.appendChild(boundingBoxesCheckbox);
  28372. var container = document.createElement("span");
  28373. var leftPart = document.createElement("span");
  28374. var rightPart = document.createElement("span");
  28375. rightPart.style.cssFloat = "right";
  28376. leftPart.innerHTML = leftTitle;
  28377. rightPart.innerHTML = rightTitle;
  28378. rightPart.style.fontSize = "12px";
  28379. rightPart.style.maxWidth = "200px";
  28380. container.appendChild(leftPart);
  28381. container.appendChild(rightPart);
  28382. label.appendChild(container);
  28383. root.appendChild(label);
  28384. root.appendChild(document.createElement("br"));
  28385. };
  28386. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28387. if (tag === void 0) { tag = null; }
  28388. var label = document.createElement("label");
  28389. var checkBox = document.createElement("input");
  28390. checkBox.type = "checkbox";
  28391. checkBox.checked = initialState;
  28392. checkBox.addEventListener("change", function (evt) {
  28393. task(evt.target, tag);
  28394. });
  28395. label.appendChild(checkBox);
  28396. label.appendChild(document.createTextNode(title));
  28397. root.appendChild(label);
  28398. root.appendChild(document.createElement("br"));
  28399. };
  28400. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28401. if (tag === void 0) { tag = null; }
  28402. var button = document.createElement("button");
  28403. button.innerHTML = title;
  28404. button.style.height = "24px";
  28405. button.style.color = "#444444";
  28406. button.style.border = "1px solid white";
  28407. button.className = "debugLayerButton";
  28408. button.addEventListener("click", function (evt) {
  28409. task(evt.target, tag);
  28410. });
  28411. root.appendChild(button);
  28412. root.appendChild(document.createElement("br"));
  28413. };
  28414. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28415. if (tag === void 0) { tag = null; }
  28416. var label = document.createElement("label");
  28417. var boundingBoxesRadio = document.createElement("input");
  28418. boundingBoxesRadio.type = "radio";
  28419. boundingBoxesRadio.name = name;
  28420. boundingBoxesRadio.checked = initialState;
  28421. boundingBoxesRadio.addEventListener("change", function (evt) {
  28422. task(evt.target, tag);
  28423. });
  28424. label.appendChild(boundingBoxesRadio);
  28425. label.appendChild(document.createTextNode(title));
  28426. root.appendChild(label);
  28427. root.appendChild(document.createElement("br"));
  28428. };
  28429. DebugLayer.prototype._generateDOMelements = function () {
  28430. var _this = this;
  28431. this._globalDiv.id = "DebugLayer";
  28432. this._globalDiv.style.position = "absolute";
  28433. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28434. this._globalDiv.style.fontSize = "14px";
  28435. this._globalDiv.style.color = "white";
  28436. // Drawing canvas
  28437. this._drawingCanvas = document.createElement("canvas");
  28438. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28439. this._drawingCanvas.style.position = "absolute";
  28440. this._drawingCanvas.style.pointerEvents = "none";
  28441. this._drawingContext = this._drawingCanvas.getContext("2d");
  28442. this._globalDiv.appendChild(this._drawingCanvas);
  28443. if (this._showUI) {
  28444. var background = "rgba(128, 128, 128, 0.4)";
  28445. var border = "rgb(180, 180, 180) solid 1px";
  28446. // Stats
  28447. this._statsDiv = document.createElement("div");
  28448. this._statsDiv.id = "DebugLayerStats";
  28449. this._statsDiv.style.border = border;
  28450. this._statsDiv.style.position = "absolute";
  28451. this._statsDiv.style.background = background;
  28452. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28453. this._generateheader(this._statsDiv, "STATISTICS");
  28454. this._statsSubsetDiv = document.createElement("div");
  28455. this._statsSubsetDiv.style.paddingTop = "5px";
  28456. this._statsSubsetDiv.style.paddingBottom = "5px";
  28457. this._statsSubsetDiv.style.overflowY = "auto";
  28458. this._statsDiv.appendChild(this._statsSubsetDiv);
  28459. // Tree
  28460. this._treeDiv = document.createElement("div");
  28461. this._treeDiv.id = "DebugLayerTree";
  28462. this._treeDiv.style.border = border;
  28463. this._treeDiv.style.position = "absolute";
  28464. this._treeDiv.style.background = background;
  28465. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28466. this._treeDiv.style.display = "none";
  28467. this._generateheader(this._treeDiv, "MESHES TREE");
  28468. this._treeSubsetDiv = document.createElement("div");
  28469. this._treeSubsetDiv.style.paddingTop = "5px";
  28470. this._treeSubsetDiv.style.paddingRight = "5px";
  28471. this._treeSubsetDiv.style.overflowY = "auto";
  28472. this._treeSubsetDiv.style.maxHeight = "300px";
  28473. this._treeDiv.appendChild(this._treeSubsetDiv);
  28474. this._needToRefreshMeshesTree = true;
  28475. // Logs
  28476. this._logDiv = document.createElement("div");
  28477. this._logDiv.style.border = border;
  28478. this._logDiv.id = "DebugLayerLogs";
  28479. this._logDiv.style.position = "absolute";
  28480. this._logDiv.style.background = background;
  28481. this._logDiv.style.padding = "0px 0px 0px 5px";
  28482. this._logDiv.style.display = "none";
  28483. this._generateheader(this._logDiv, "LOGS");
  28484. this._logSubsetDiv = document.createElement("div");
  28485. this._logSubsetDiv.style.height = "127px";
  28486. this._logSubsetDiv.style.paddingTop = "5px";
  28487. this._logSubsetDiv.style.overflowY = "auto";
  28488. this._logSubsetDiv.style.fontSize = "12px";
  28489. this._logSubsetDiv.style.fontFamily = "consolas";
  28490. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28491. this._logDiv.appendChild(this._logSubsetDiv);
  28492. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28493. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28494. };
  28495. // Options
  28496. this._optionsDiv = document.createElement("div");
  28497. this._optionsDiv.id = "DebugLayerOptions";
  28498. this._optionsDiv.style.border = border;
  28499. this._optionsDiv.style.position = "absolute";
  28500. this._optionsDiv.style.background = background;
  28501. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28502. this._optionsDiv.style.overflowY = "auto";
  28503. this._generateheader(this._optionsDiv, "OPTIONS");
  28504. this._optionsSubsetDiv = document.createElement("div");
  28505. this._optionsSubsetDiv.style.paddingTop = "5px";
  28506. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28507. this._optionsSubsetDiv.style.overflowY = "auto";
  28508. this._optionsSubsetDiv.style.maxHeight = "200px";
  28509. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28510. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28511. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28512. _this._displayStatistics = element.checked;
  28513. });
  28514. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28515. _this._displayLogs = element.checked;
  28516. });
  28517. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28518. _this._displayTree = element.checked;
  28519. _this._needToRefreshMeshesTree = true;
  28520. });
  28521. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28522. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28523. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28524. _this._scene.forceShowBoundingBoxes = element.checked;
  28525. });
  28526. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28527. _this._labelsEnabled = element.checked;
  28528. if (!_this._labelsEnabled) {
  28529. _this._clearLabels();
  28530. }
  28531. });
  28532. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28533. if (element.checked) {
  28534. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28535. }
  28536. else {
  28537. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28538. }
  28539. });
  28540. ;
  28541. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28542. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28543. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28544. if (element.checked) {
  28545. _this._scene.forceWireframe = false;
  28546. _this._scene.forcePointsCloud = false;
  28547. }
  28548. });
  28549. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28550. if (element.checked) {
  28551. _this._scene.forceWireframe = true;
  28552. _this._scene.forcePointsCloud = false;
  28553. }
  28554. });
  28555. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28556. if (element.checked) {
  28557. _this._scene.forceWireframe = false;
  28558. _this._scene.forcePointsCloud = true;
  28559. }
  28560. });
  28561. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28562. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28563. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28564. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28565. });
  28566. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28567. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28568. });
  28569. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28570. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28571. });
  28572. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28573. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28574. });
  28575. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28576. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28577. });
  28578. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28579. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28580. });
  28581. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28582. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28583. });
  28584. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28585. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28586. });
  28587. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28588. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28589. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28590. _this._scene.animationsEnabled = element.checked;
  28591. });
  28592. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28593. _this._scene.collisionsEnabled = element.checked;
  28594. });
  28595. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28596. _this._scene.fogEnabled = element.checked;
  28597. });
  28598. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28599. _this._scene.lensFlaresEnabled = element.checked;
  28600. });
  28601. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28602. _this._scene.lightsEnabled = element.checked;
  28603. });
  28604. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28605. _this._scene.particlesEnabled = element.checked;
  28606. });
  28607. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28608. _this._scene.postProcessesEnabled = element.checked;
  28609. });
  28610. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28611. _this._scene.proceduralTexturesEnabled = element.checked;
  28612. });
  28613. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28614. _this._scene.renderTargetsEnabled = element.checked;
  28615. });
  28616. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28617. _this._scene.shadowsEnabled = element.checked;
  28618. });
  28619. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28620. _this._scene.skeletonsEnabled = element.checked;
  28621. });
  28622. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28623. _this._scene.spritesEnabled = element.checked;
  28624. });
  28625. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28626. _this._scene.texturesEnabled = element.checked;
  28627. });
  28628. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28629. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28630. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28631. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28632. if (element.checked) {
  28633. _this._scene.headphone = true;
  28634. }
  28635. });
  28636. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28637. if (element.checked) {
  28638. _this._scene.headphone = false;
  28639. }
  28640. });
  28641. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28642. _this._scene.audioEnabled = !element.checked;
  28643. });
  28644. }
  28645. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28646. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28647. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28648. _this._scene.dumpNextRenderTargets = true;
  28649. });
  28650. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28651. this._globalDiv.appendChild(this._statsDiv);
  28652. this._globalDiv.appendChild(this._logDiv);
  28653. this._globalDiv.appendChild(this._optionsDiv);
  28654. this._globalDiv.appendChild(this._treeDiv);
  28655. }
  28656. };
  28657. DebugLayer.prototype._displayStats = function () {
  28658. var scene = this._scene;
  28659. var engine = scene.getEngine();
  28660. var glInfo = engine.getGlInfo();
  28661. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active indices: " + scene.getActiveIndices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  28662. if (this.customStatsFunction) {
  28663. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28664. }
  28665. };
  28666. return DebugLayer;
  28667. })();
  28668. BABYLON.DebugLayer = DebugLayer;
  28669. })(BABYLON || (BABYLON = {}));
  28670. //# sourceMappingURL=babylon.debugLayer.js.map
  28671. var BABYLON;
  28672. (function (BABYLON) {
  28673. var RawTexture = (function (_super) {
  28674. __extends(RawTexture, _super);
  28675. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28676. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28677. if (invertY === void 0) { invertY = false; }
  28678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28679. _super.call(this, null, scene, !generateMipMaps, invertY);
  28680. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28681. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28682. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28683. }
  28684. // Statics
  28685. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28686. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28687. if (invertY === void 0) { invertY = false; }
  28688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28689. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28690. };
  28691. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28692. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28693. if (invertY === void 0) { invertY = false; }
  28694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28695. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28696. };
  28697. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28698. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28699. if (invertY === void 0) { invertY = false; }
  28700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28701. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28702. };
  28703. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28704. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28705. if (invertY === void 0) { invertY = false; }
  28706. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28707. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28708. };
  28709. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28710. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28711. if (invertY === void 0) { invertY = false; }
  28712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28713. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28714. };
  28715. return RawTexture;
  28716. })(BABYLON.Texture);
  28717. BABYLON.RawTexture = RawTexture;
  28718. })(BABYLON || (BABYLON = {}));
  28719. //# sourceMappingURL=babylon.rawTexture.js.map
  28720. var BABYLON;
  28721. (function (BABYLON) {
  28722. var IndexedVector2 = (function (_super) {
  28723. __extends(IndexedVector2, _super);
  28724. function IndexedVector2(original, index) {
  28725. _super.call(this, original.x, original.y);
  28726. this.index = index;
  28727. }
  28728. return IndexedVector2;
  28729. })(BABYLON.Vector2);
  28730. var PolygonPoints = (function () {
  28731. function PolygonPoints() {
  28732. this.elements = new Array();
  28733. }
  28734. PolygonPoints.prototype.add = function (originalPoints) {
  28735. var _this = this;
  28736. var result = new Array();
  28737. originalPoints.forEach(function (point) {
  28738. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28739. var newPoint = new IndexedVector2(point, _this.elements.length);
  28740. result.push(newPoint);
  28741. _this.elements.push(newPoint);
  28742. }
  28743. });
  28744. return result;
  28745. };
  28746. PolygonPoints.prototype.computeBounds = function () {
  28747. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28748. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28749. this.elements.forEach(function (point) {
  28750. // x
  28751. if (point.x < lmin.x) {
  28752. lmin.x = point.x;
  28753. }
  28754. else if (point.x > lmax.x) {
  28755. lmax.x = point.x;
  28756. }
  28757. // y
  28758. if (point.y < lmin.y) {
  28759. lmin.y = point.y;
  28760. }
  28761. else if (point.y > lmax.y) {
  28762. lmax.y = point.y;
  28763. }
  28764. });
  28765. return {
  28766. min: lmin,
  28767. max: lmax,
  28768. width: lmax.x - lmin.x,
  28769. height: lmax.y - lmin.y
  28770. };
  28771. };
  28772. return PolygonPoints;
  28773. })();
  28774. var Polygon = (function () {
  28775. function Polygon() {
  28776. }
  28777. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28778. return [
  28779. new BABYLON.Vector2(xmin, ymin),
  28780. new BABYLON.Vector2(xmax, ymin),
  28781. new BABYLON.Vector2(xmax, ymax),
  28782. new BABYLON.Vector2(xmin, ymax)
  28783. ];
  28784. };
  28785. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28786. if (cx === void 0) { cx = 0; }
  28787. if (cy === void 0) { cy = 0; }
  28788. if (numberOfSides === void 0) { numberOfSides = 32; }
  28789. var result = new Array();
  28790. var angle = 0;
  28791. var increment = (Math.PI * 2) / numberOfSides;
  28792. for (var i = 0; i < numberOfSides; i++) {
  28793. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28794. angle -= increment;
  28795. }
  28796. return result;
  28797. };
  28798. Polygon.Parse = function (input) {
  28799. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28800. var i, result = [];
  28801. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28802. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28803. }
  28804. return result;
  28805. };
  28806. Polygon.StartingAt = function (x, y) {
  28807. return BABYLON.Path2.StartingAt(x, y);
  28808. };
  28809. return Polygon;
  28810. })();
  28811. BABYLON.Polygon = Polygon;
  28812. var PolygonMeshBuilder = (function () {
  28813. function PolygonMeshBuilder(name, contours, scene) {
  28814. this._points = new PolygonPoints();
  28815. if (!("poly2tri" in window)) {
  28816. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28817. }
  28818. this._name = name;
  28819. this._scene = scene;
  28820. var points;
  28821. if (contours instanceof BABYLON.Path2) {
  28822. points = contours.getPoints();
  28823. }
  28824. else {
  28825. points = contours;
  28826. }
  28827. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28828. }
  28829. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28830. this._swctx.addHole(this._points.add(hole));
  28831. return this;
  28832. };
  28833. PolygonMeshBuilder.prototype.build = function (updatable) {
  28834. if (updatable === void 0) { updatable = false; }
  28835. var result = new BABYLON.Mesh(this._name, this._scene);
  28836. var normals = [];
  28837. var positions = [];
  28838. var uvs = [];
  28839. var bounds = this._points.computeBounds();
  28840. this._points.elements.forEach(function (p) {
  28841. normals.push(0, 1.0, 0);
  28842. positions.push(p.x, 0, p.y);
  28843. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28844. });
  28845. var indices = [];
  28846. this._swctx.triangulate();
  28847. this._swctx.getTriangles().forEach(function (triangle) {
  28848. triangle.getPoints().forEach(function (point) {
  28849. indices.push(point.index);
  28850. });
  28851. });
  28852. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  28853. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  28854. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  28855. result.setIndices(indices);
  28856. return result;
  28857. };
  28858. return PolygonMeshBuilder;
  28859. })();
  28860. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28861. })(BABYLON || (BABYLON = {}));
  28862. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28863. (function (BABYLON) {
  28864. var SimplificationSettings = (function () {
  28865. function SimplificationSettings(quality, distance, optimizeMesh) {
  28866. this.quality = quality;
  28867. this.distance = distance;
  28868. this.optimizeMesh = optimizeMesh;
  28869. }
  28870. return SimplificationSettings;
  28871. })();
  28872. BABYLON.SimplificationSettings = SimplificationSettings;
  28873. var SimplificationQueue = (function () {
  28874. function SimplificationQueue() {
  28875. this.running = false;
  28876. this._simplificationArray = [];
  28877. }
  28878. SimplificationQueue.prototype.addTask = function (task) {
  28879. this._simplificationArray.push(task);
  28880. };
  28881. SimplificationQueue.prototype.executeNext = function () {
  28882. var task = this._simplificationArray.pop();
  28883. if (task) {
  28884. this.running = true;
  28885. this.runSimplification(task);
  28886. }
  28887. else {
  28888. this.running = false;
  28889. }
  28890. };
  28891. SimplificationQueue.prototype.runSimplification = function (task) {
  28892. var _this = this;
  28893. if (task.parallelProcessing) {
  28894. //parallel simplifier
  28895. task.settings.forEach(function (setting) {
  28896. var simplifier = _this.getSimplifier(task);
  28897. simplifier.simplify(setting, function (newMesh) {
  28898. task.mesh.addLODLevel(setting.distance, newMesh);
  28899. newMesh.isVisible = true;
  28900. //check if it is the last
  28901. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28902. //all done, run the success callback.
  28903. task.successCallback();
  28904. }
  28905. _this.executeNext();
  28906. });
  28907. });
  28908. }
  28909. else {
  28910. //single simplifier.
  28911. var simplifier = this.getSimplifier(task);
  28912. var runDecimation = function (setting, callback) {
  28913. simplifier.simplify(setting, function (newMesh) {
  28914. task.mesh.addLODLevel(setting.distance, newMesh);
  28915. newMesh.isVisible = true;
  28916. //run the next quality level
  28917. callback();
  28918. });
  28919. };
  28920. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28921. runDecimation(task.settings[loop.index], function () {
  28922. loop.executeNext();
  28923. });
  28924. }, function () {
  28925. //execution ended, run the success callback.
  28926. if (task.successCallback) {
  28927. task.successCallback();
  28928. }
  28929. _this.executeNext();
  28930. });
  28931. }
  28932. };
  28933. SimplificationQueue.prototype.getSimplifier = function (task) {
  28934. switch (task.simplificationType) {
  28935. case 0 /* QUADRATIC */:
  28936. default:
  28937. return new QuadraticErrorSimplification(task.mesh);
  28938. }
  28939. };
  28940. return SimplificationQueue;
  28941. })();
  28942. BABYLON.SimplificationQueue = SimplificationQueue;
  28943. /**
  28944. * The implemented types of simplification.
  28945. * At the moment only Quadratic Error Decimation is implemented.
  28946. */
  28947. (function (SimplificationType) {
  28948. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28949. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28950. var SimplificationType = BABYLON.SimplificationType;
  28951. var DecimationTriangle = (function () {
  28952. function DecimationTriangle(vertices) {
  28953. this.vertices = vertices;
  28954. this.error = new Array(4);
  28955. this.deleted = false;
  28956. this.isDirty = false;
  28957. this.deletePending = false;
  28958. this.borderFactor = 0;
  28959. }
  28960. return DecimationTriangle;
  28961. })();
  28962. BABYLON.DecimationTriangle = DecimationTriangle;
  28963. var DecimationVertex = (function () {
  28964. function DecimationVertex(position, id) {
  28965. this.position = position;
  28966. this.id = id;
  28967. this.isBorder = true;
  28968. this.q = new QuadraticMatrix();
  28969. this.triangleCount = 0;
  28970. this.triangleStart = 0;
  28971. this.originalOffsets = [];
  28972. }
  28973. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28974. this.position.copyFrom(newPosition);
  28975. };
  28976. return DecimationVertex;
  28977. })();
  28978. BABYLON.DecimationVertex = DecimationVertex;
  28979. var QuadraticMatrix = (function () {
  28980. function QuadraticMatrix(data) {
  28981. this.data = new Array(10);
  28982. for (var i = 0; i < 10; ++i) {
  28983. if (data && data[i]) {
  28984. this.data[i] = data[i];
  28985. }
  28986. else {
  28987. this.data[i] = 0;
  28988. }
  28989. }
  28990. }
  28991. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28992. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28993. return det;
  28994. };
  28995. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28996. for (var i = 0; i < 10; ++i) {
  28997. this.data[i] += matrix.data[i];
  28998. }
  28999. };
  29000. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29001. for (var i = 0; i < 10; ++i) {
  29002. this.data[i] += data[i];
  29003. }
  29004. };
  29005. QuadraticMatrix.prototype.add = function (matrix) {
  29006. var m = new QuadraticMatrix();
  29007. for (var i = 0; i < 10; ++i) {
  29008. m.data[i] = this.data[i] + matrix.data[i];
  29009. }
  29010. return m;
  29011. };
  29012. QuadraticMatrix.FromData = function (a, b, c, d) {
  29013. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29014. };
  29015. //returning an array to avoid garbage collection
  29016. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29017. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29018. };
  29019. return QuadraticMatrix;
  29020. })();
  29021. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29022. var Reference = (function () {
  29023. function Reference(vertexId, triangleId) {
  29024. this.vertexId = vertexId;
  29025. this.triangleId = triangleId;
  29026. }
  29027. return Reference;
  29028. })();
  29029. BABYLON.Reference = Reference;
  29030. /**
  29031. * An implementation of the Quadratic Error simplification algorithm.
  29032. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29033. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29034. * @author RaananW
  29035. */
  29036. var QuadraticErrorSimplification = (function () {
  29037. function QuadraticErrorSimplification(_mesh) {
  29038. this._mesh = _mesh;
  29039. this.initialized = false;
  29040. this.syncIterations = 5000;
  29041. this.aggressiveness = 7;
  29042. this.decimationIterations = 100;
  29043. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29044. }
  29045. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29046. var _this = this;
  29047. this.initDecimatedMesh();
  29048. //iterating through the submeshes array, one after the other.
  29049. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29050. _this.initWithMesh(loop.index, function () {
  29051. _this.runDecimation(settings, loop.index, function () {
  29052. loop.executeNext();
  29053. });
  29054. }, settings.optimizeMesh);
  29055. }, function () {
  29056. setTimeout(function () {
  29057. successCallback(_this._reconstructedMesh);
  29058. }, 0);
  29059. });
  29060. };
  29061. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29062. var _this = this;
  29063. var gCount = 0;
  29064. triangle.vertices.forEach(function (vertex) {
  29065. var count = 0;
  29066. var vPos = vertex.position;
  29067. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29068. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29069. ++count;
  29070. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  29071. ++count;
  29072. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  29073. ++count;
  29074. if (count > 1) {
  29075. ++gCount;
  29076. }
  29077. ;
  29078. });
  29079. if (gCount > 1) {
  29080. console.log(triangle, gCount);
  29081. }
  29082. return gCount > 1;
  29083. };
  29084. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29085. var _this = this;
  29086. var targetCount = ~~(this.triangles.length * settings.quality);
  29087. var deletedTriangles = 0;
  29088. var triangleCount = this.triangles.length;
  29089. var iterationFunction = function (iteration, callback) {
  29090. setTimeout(function () {
  29091. if (iteration % 5 === 0) {
  29092. _this.updateMesh(iteration === 0);
  29093. }
  29094. for (var i = 0; i < _this.triangles.length; ++i) {
  29095. _this.triangles[i].isDirty = false;
  29096. }
  29097. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29098. var trianglesIterator = function (i) {
  29099. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29100. var t = _this.triangles[tIdx];
  29101. if (!t)
  29102. return;
  29103. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29104. return;
  29105. }
  29106. for (var j = 0; j < 3; ++j) {
  29107. if (t.error[j] < threshold) {
  29108. var deleted0 = [];
  29109. var deleted1 = [];
  29110. var v0 = t.vertices[j];
  29111. var v1 = t.vertices[(j + 1) % 3];
  29112. if (v0.isBorder !== v1.isBorder)
  29113. continue;
  29114. var p = BABYLON.Vector3.Zero();
  29115. var n = BABYLON.Vector3.Zero();
  29116. var uv = BABYLON.Vector2.Zero();
  29117. var color = new BABYLON.Color4(0, 0, 0, 1);
  29118. _this.calculateError(v0, v1, p, n, uv, color);
  29119. var delTr = [];
  29120. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29121. continue;
  29122. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29123. continue;
  29124. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29125. continue;
  29126. var uniqueArray = [];
  29127. delTr.forEach(function (deletedT) {
  29128. if (uniqueArray.indexOf(deletedT) === -1) {
  29129. deletedT.deletePending = true;
  29130. uniqueArray.push(deletedT);
  29131. }
  29132. });
  29133. if (uniqueArray.length % 2 != 0) {
  29134. continue;
  29135. }
  29136. v0.q = v1.q.add(v0.q);
  29137. v0.updatePosition(p);
  29138. var tStart = _this.references.length;
  29139. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29140. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29141. var tCount = _this.references.length - tStart;
  29142. if (tCount <= v0.triangleCount) {
  29143. if (tCount) {
  29144. for (var c = 0; c < tCount; c++) {
  29145. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29146. }
  29147. }
  29148. }
  29149. else {
  29150. v0.triangleStart = tStart;
  29151. }
  29152. v0.triangleCount = tCount;
  29153. break;
  29154. }
  29155. }
  29156. };
  29157. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  29158. return (triangleCount - deletedTriangles <= targetCount);
  29159. });
  29160. }, 0);
  29161. };
  29162. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29163. if (triangleCount - deletedTriangles <= targetCount)
  29164. loop.breakLoop();
  29165. else {
  29166. iterationFunction(loop.index, function () {
  29167. loop.executeNext();
  29168. });
  29169. }
  29170. }, function () {
  29171. setTimeout(function () {
  29172. //reconstruct this part of the mesh
  29173. _this.reconstructMesh(submeshIndex);
  29174. successCallback();
  29175. }, 0);
  29176. });
  29177. };
  29178. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29179. var _this = this;
  29180. this.vertices = [];
  29181. this.triangles = [];
  29182. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29183. var indices = this._mesh.getIndices();
  29184. var submesh = this._mesh.subMeshes[submeshIndex];
  29185. var findInVertices = function (positionToSearch) {
  29186. if (optimizeMesh) {
  29187. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29188. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29189. return _this.vertices[ii];
  29190. }
  29191. }
  29192. }
  29193. return null;
  29194. };
  29195. var vertexReferences = [];
  29196. var vertexInit = function (i) {
  29197. var offset = i + submesh.verticesStart;
  29198. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29199. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29200. vertex.originalOffsets.push(offset);
  29201. if (vertex.id == _this.vertices.length) {
  29202. _this.vertices.push(vertex);
  29203. }
  29204. vertexReferences.push(vertex.id);
  29205. };
  29206. //var totalVertices = mesh.getTotalVertices();
  29207. var totalVertices = submesh.verticesCount;
  29208. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29209. var indicesInit = function (i) {
  29210. var offset = (submesh.indexStart / 3) + i;
  29211. var pos = (offset * 3);
  29212. var i0 = indices[pos + 0];
  29213. var i1 = indices[pos + 1];
  29214. var i2 = indices[pos + 2];
  29215. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29216. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29217. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29218. var triangle = new DecimationTriangle([v0, v1, v2]);
  29219. triangle.originalOffset = pos;
  29220. _this.triangles.push(triangle);
  29221. };
  29222. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29223. _this.init(callback);
  29224. });
  29225. });
  29226. };
  29227. QuadraticErrorSimplification.prototype.init = function (callback) {
  29228. var _this = this;
  29229. var triangleInit1 = function (i) {
  29230. var t = _this.triangles[i];
  29231. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29232. for (var j = 0; j < 3; j++) {
  29233. 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))));
  29234. }
  29235. };
  29236. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29237. var triangleInit2 = function (i) {
  29238. var t = _this.triangles[i];
  29239. for (var j = 0; j < 3; ++j) {
  29240. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29241. }
  29242. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29243. };
  29244. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29245. _this.initialized = true;
  29246. callback();
  29247. });
  29248. });
  29249. };
  29250. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29251. var newTriangles = [];
  29252. var i;
  29253. for (i = 0; i < this.vertices.length; ++i) {
  29254. this.vertices[i].triangleCount = 0;
  29255. }
  29256. var t;
  29257. var j;
  29258. for (i = 0; i < this.triangles.length; ++i) {
  29259. if (!this.triangles[i].deleted) {
  29260. t = this.triangles[i];
  29261. for (j = 0; j < 3; ++j) {
  29262. t.vertices[j].triangleCount = 1;
  29263. }
  29264. newTriangles.push(t);
  29265. }
  29266. }
  29267. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  29268. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  29269. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  29270. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  29271. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29272. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29273. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29274. var vertexCount = 0;
  29275. for (i = 0; i < this.vertices.length; ++i) {
  29276. var vertex = this.vertices[i];
  29277. vertex.id = vertexCount;
  29278. if (vertex.triangleCount) {
  29279. vertex.originalOffsets.forEach(function (originalOffset) {
  29280. newPositionData.push(vertex.position.x);
  29281. newPositionData.push(vertex.position.y);
  29282. newPositionData.push(vertex.position.z);
  29283. newNormalData.push(normalData[originalOffset * 3]);
  29284. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29285. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29286. if (uvs && uvs.length) {
  29287. newUVsData.push(uvs[(originalOffset * 2)]);
  29288. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29289. }
  29290. else if (colorsData && colorsData.length) {
  29291. newColorsData.push(colorsData[(originalOffset * 4)]);
  29292. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29293. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29294. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29295. }
  29296. ++vertexCount;
  29297. });
  29298. }
  29299. }
  29300. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29301. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29302. var submeshesArray = this._reconstructedMesh.subMeshes;
  29303. this._reconstructedMesh.subMeshes = [];
  29304. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29305. var originalIndices = this._mesh.getIndices();
  29306. for (i = 0; i < newTriangles.length; ++i) {
  29307. var t = newTriangles[i];
  29308. //now get the new referencing point for each vertex
  29309. [0, 1, 2].forEach(function (idx) {
  29310. var id = originalIndices[t.originalOffset + idx];
  29311. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29312. if (offset < 0)
  29313. offset = 0;
  29314. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29315. });
  29316. }
  29317. //overwriting the old vertex buffers and indices.
  29318. this._reconstructedMesh.setIndices(newIndicesArray);
  29319. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29320. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29321. if (newUVsData.length > 0)
  29322. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29323. if (newColorsData.length > 0)
  29324. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29325. //create submesh
  29326. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29327. if (submeshIndex > 0) {
  29328. this._reconstructedMesh.subMeshes = [];
  29329. submeshesArray.forEach(function (submesh) {
  29330. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29331. });
  29332. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29333. }
  29334. };
  29335. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29336. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29337. this._reconstructedMesh.material = this._mesh.material;
  29338. this._reconstructedMesh.parent = this._mesh.parent;
  29339. this._reconstructedMesh.isVisible = false;
  29340. };
  29341. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29342. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29343. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29344. if (t.deleted)
  29345. continue;
  29346. var s = this.references[vertex1.triangleStart + i].vertexId;
  29347. var v1 = t.vertices[(s + 1) % 3];
  29348. var v2 = t.vertices[(s + 2) % 3];
  29349. if ((v1 === vertex2 || v2 === vertex2)) {
  29350. deletedArray[i] = true;
  29351. delTr.push(t);
  29352. continue;
  29353. }
  29354. var d1 = v1.position.subtract(point);
  29355. d1 = d1.normalize();
  29356. var d2 = v2.position.subtract(point);
  29357. d2 = d2.normalize();
  29358. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29359. return true;
  29360. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29361. deletedArray[i] = false;
  29362. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29363. return true;
  29364. }
  29365. return false;
  29366. };
  29367. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29368. var newDeleted = deletedTriangles;
  29369. for (var i = 0; i < vertex.triangleCount; ++i) {
  29370. var ref = this.references[vertex.triangleStart + i];
  29371. var t = this.triangles[ref.triangleId];
  29372. if (t.deleted)
  29373. continue;
  29374. if (deletedArray[i] && t.deletePending) {
  29375. t.deleted = true;
  29376. newDeleted++;
  29377. continue;
  29378. }
  29379. t.vertices[ref.vertexId] = origVertex;
  29380. t.isDirty = true;
  29381. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29382. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29383. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29384. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29385. this.references.push(ref);
  29386. }
  29387. return newDeleted;
  29388. };
  29389. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29390. for (var i = 0; i < this.vertices.length; ++i) {
  29391. var vCount = [];
  29392. var vId = [];
  29393. var v = this.vertices[i];
  29394. var j;
  29395. for (j = 0; j < v.triangleCount; ++j) {
  29396. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29397. for (var ii = 0; ii < 3; ii++) {
  29398. var ofs = 0;
  29399. var vv = triangle.vertices[ii];
  29400. while (ofs < vCount.length) {
  29401. if (vId[ofs] === vv.id)
  29402. break;
  29403. ++ofs;
  29404. }
  29405. if (ofs === vCount.length) {
  29406. vCount.push(1);
  29407. vId.push(vv.id);
  29408. }
  29409. else {
  29410. vCount[ofs]++;
  29411. }
  29412. }
  29413. }
  29414. for (j = 0; j < vCount.length; ++j) {
  29415. if (vCount[j] === 1) {
  29416. this.vertices[vId[j]].isBorder = true;
  29417. }
  29418. else {
  29419. this.vertices[vId[j]].isBorder = false;
  29420. }
  29421. }
  29422. }
  29423. };
  29424. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29425. if (identifyBorders === void 0) { identifyBorders = false; }
  29426. var i;
  29427. if (!identifyBorders) {
  29428. var newTrianglesVector = [];
  29429. for (i = 0; i < this.triangles.length; ++i) {
  29430. if (!this.triangles[i].deleted) {
  29431. newTrianglesVector.push(this.triangles[i]);
  29432. }
  29433. }
  29434. this.triangles = newTrianglesVector;
  29435. }
  29436. for (i = 0; i < this.vertices.length; ++i) {
  29437. this.vertices[i].triangleCount = 0;
  29438. this.vertices[i].triangleStart = 0;
  29439. }
  29440. var t;
  29441. var j;
  29442. var v;
  29443. for (i = 0; i < this.triangles.length; ++i) {
  29444. t = this.triangles[i];
  29445. for (j = 0; j < 3; ++j) {
  29446. v = t.vertices[j];
  29447. v.triangleCount++;
  29448. }
  29449. }
  29450. var tStart = 0;
  29451. for (i = 0; i < this.vertices.length; ++i) {
  29452. this.vertices[i].triangleStart = tStart;
  29453. tStart += this.vertices[i].triangleCount;
  29454. this.vertices[i].triangleCount = 0;
  29455. }
  29456. var newReferences = new Array(this.triangles.length * 3);
  29457. for (i = 0; i < this.triangles.length; ++i) {
  29458. t = this.triangles[i];
  29459. for (j = 0; j < 3; ++j) {
  29460. v = t.vertices[j];
  29461. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29462. v.triangleCount++;
  29463. }
  29464. }
  29465. this.references = newReferences;
  29466. if (identifyBorders) {
  29467. this.identifyBorder();
  29468. }
  29469. };
  29470. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29471. var x = point.x;
  29472. var y = point.y;
  29473. var z = point.z;
  29474. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29475. };
  29476. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29477. var q = vertex1.q.add(vertex2.q);
  29478. var border = vertex1.isBorder && vertex2.isBorder;
  29479. var error = 0;
  29480. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29481. if (qDet !== 0 && !border) {
  29482. if (!pointResult) {
  29483. pointResult = BABYLON.Vector3.Zero();
  29484. }
  29485. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29486. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29487. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29488. error = this.vertexError(q, pointResult);
  29489. }
  29490. else {
  29491. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29492. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29493. var error1 = this.vertexError(q, vertex1.position);
  29494. var error2 = this.vertexError(q, vertex2.position);
  29495. var error3 = this.vertexError(q, p3);
  29496. error = Math.min(error1, error2, error3);
  29497. if (error === error1) {
  29498. if (pointResult) {
  29499. pointResult.copyFrom(vertex1.position);
  29500. }
  29501. }
  29502. else if (error === error2) {
  29503. if (pointResult) {
  29504. pointResult.copyFrom(vertex2.position);
  29505. }
  29506. }
  29507. else {
  29508. if (pointResult) {
  29509. pointResult.copyFrom(p3);
  29510. }
  29511. }
  29512. }
  29513. return error;
  29514. };
  29515. return QuadraticErrorSimplification;
  29516. })();
  29517. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29518. })(BABYLON || (BABYLON = {}));
  29519. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29520. (function (BABYLON) {
  29521. var Analyser = (function () {
  29522. function Analyser(scene) {
  29523. this.SMOOTHING = 0.75;
  29524. this.FFT_SIZE = 512;
  29525. this.BARGRAPHAMPLITUDE = 256;
  29526. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29527. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29528. this._scene = scene;
  29529. this._audioEngine = BABYLON.Engine.audioEngine;
  29530. if (this._audioEngine.canUseWebAudio) {
  29531. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29532. this._webAudioAnalyser.minDecibels = -140;
  29533. this._webAudioAnalyser.maxDecibels = 0;
  29534. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29535. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29536. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29537. }
  29538. }
  29539. Analyser.prototype.getFrequencyBinCount = function () {
  29540. if (this._audioEngine.canUseWebAudio) {
  29541. return this._webAudioAnalyser.frequencyBinCount;
  29542. }
  29543. else {
  29544. return 0;
  29545. }
  29546. };
  29547. Analyser.prototype.getByteFrequencyData = function () {
  29548. if (this._audioEngine.canUseWebAudio) {
  29549. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29550. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29551. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29552. }
  29553. return this._byteFreqs;
  29554. };
  29555. Analyser.prototype.getByteTimeDomainData = function () {
  29556. if (this._audioEngine.canUseWebAudio) {
  29557. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29558. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29559. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29560. }
  29561. return this._byteTime;
  29562. };
  29563. Analyser.prototype.getFloatFrequencyData = function () {
  29564. if (this._audioEngine.canUseWebAudio) {
  29565. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29566. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29567. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29568. }
  29569. return this._floatFreqs;
  29570. };
  29571. Analyser.prototype.drawDebugCanvas = function () {
  29572. var _this = this;
  29573. if (this._audioEngine.canUseWebAudio) {
  29574. if (!this._debugCanvas) {
  29575. this._debugCanvas = document.createElement("canvas");
  29576. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29577. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29578. this._debugCanvas.style.position = "absolute";
  29579. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29580. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29581. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29582. document.body.appendChild(this._debugCanvas);
  29583. this._registerFunc = function () {
  29584. _this.drawDebugCanvas();
  29585. };
  29586. this._scene.registerBeforeRender(this._registerFunc);
  29587. }
  29588. if (this._registerFunc) {
  29589. var workingArray = this.getByteFrequencyData();
  29590. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29591. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29592. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29593. var value = workingArray[i];
  29594. var percent = value / this.BARGRAPHAMPLITUDE;
  29595. var height = this.DEBUGCANVASSIZE.height * percent;
  29596. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29597. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29598. var hue = i / this.getFrequencyBinCount() * 360;
  29599. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29600. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29601. }
  29602. }
  29603. }
  29604. };
  29605. Analyser.prototype.stopDebugCanvas = function () {
  29606. if (this._debugCanvas) {
  29607. this._scene.unregisterBeforeRender(this._registerFunc);
  29608. this._registerFunc = null;
  29609. document.body.removeChild(this._debugCanvas);
  29610. this._debugCanvas = null;
  29611. this._debugCanvasContext = null;
  29612. }
  29613. };
  29614. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29615. if (this._audioEngine.canUseWebAudio) {
  29616. inputAudioNode.connect(this._webAudioAnalyser);
  29617. this._webAudioAnalyser.connect(outputAudioNode);
  29618. }
  29619. };
  29620. Analyser.prototype.dispose = function () {
  29621. if (this._audioEngine.canUseWebAudio) {
  29622. this._webAudioAnalyser.disconnect();
  29623. }
  29624. };
  29625. return Analyser;
  29626. })();
  29627. BABYLON.Analyser = Analyser;
  29628. })(BABYLON || (BABYLON = {}));
  29629. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29630. (function (BABYLON) {
  29631. var DepthRenderer = (function () {
  29632. function DepthRenderer(scene, type) {
  29633. var _this = this;
  29634. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29635. this._viewMatrix = BABYLON.Matrix.Zero();
  29636. this._projectionMatrix = BABYLON.Matrix.Zero();
  29637. this._transformMatrix = BABYLON.Matrix.Zero();
  29638. this._worldViewProjection = BABYLON.Matrix.Zero();
  29639. this._scene = scene;
  29640. var engine = scene.getEngine();
  29641. // Render target
  29642. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29643. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29644. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29645. this._depthMap.refreshRate = 1;
  29646. this._depthMap.renderParticles = false;
  29647. this._depthMap.renderList = null;
  29648. // set default depth value to 1.0 (far away)
  29649. this._depthMap.onClear = function (engine) {
  29650. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  29651. };
  29652. // Custom render function
  29653. var renderSubMesh = function (subMesh) {
  29654. var mesh = subMesh.getRenderingMesh();
  29655. var scene = _this._scene;
  29656. var engine = scene.getEngine();
  29657. // Culling
  29658. engine.setState(subMesh.getMaterial().backFaceCulling);
  29659. // Managing instances
  29660. var batch = mesh._getInstancesRenderList(subMesh._id);
  29661. if (batch.mustReturn) {
  29662. return;
  29663. }
  29664. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29665. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29666. engine.enableEffect(_this._effect);
  29667. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29668. var material = subMesh.getMaterial();
  29669. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29670. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29671. // Alpha test
  29672. if (material && material.needAlphaTesting()) {
  29673. var alphaTexture = material.getAlphaTestTexture();
  29674. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29675. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29676. }
  29677. // Bones
  29678. if (mesh.useBones) {
  29679. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29680. }
  29681. // Draw
  29682. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29683. }
  29684. };
  29685. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29686. var index;
  29687. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29688. renderSubMesh(opaqueSubMeshes.data[index]);
  29689. }
  29690. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29691. renderSubMesh(alphaTestSubMeshes.data[index]);
  29692. }
  29693. };
  29694. }
  29695. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29696. var defines = [];
  29697. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29698. var mesh = subMesh.getMesh();
  29699. var scene = mesh.getScene();
  29700. var material = subMesh.getMaterial();
  29701. // Alpha test
  29702. if (material && material.needAlphaTesting()) {
  29703. defines.push("#define ALPHATEST");
  29704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29705. attribs.push(BABYLON.VertexBuffer.UVKind);
  29706. defines.push("#define UV1");
  29707. }
  29708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29709. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29710. defines.push("#define UV2");
  29711. }
  29712. }
  29713. // Bones
  29714. if (mesh.useBones) {
  29715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29717. defines.push("#define BONES");
  29718. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29719. }
  29720. // Instances
  29721. if (useInstances) {
  29722. defines.push("#define INSTANCES");
  29723. attribs.push("world0");
  29724. attribs.push("world1");
  29725. attribs.push("world2");
  29726. attribs.push("world3");
  29727. }
  29728. // Get correct effect
  29729. var join = defines.join("\n");
  29730. if (this._cachedDefines !== join) {
  29731. this._cachedDefines = join;
  29732. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29733. }
  29734. return this._effect.isReady();
  29735. };
  29736. DepthRenderer.prototype.getDepthMap = function () {
  29737. return this._depthMap;
  29738. };
  29739. // Methods
  29740. DepthRenderer.prototype.dispose = function () {
  29741. this._depthMap.dispose();
  29742. };
  29743. return DepthRenderer;
  29744. })();
  29745. BABYLON.DepthRenderer = DepthRenderer;
  29746. })(BABYLON || (BABYLON = {}));
  29747. //# sourceMappingURL=babylon.depthRenderer.js.map
  29748. var BABYLON;
  29749. (function (BABYLON) {
  29750. var SSAORenderingPipeline = (function (_super) {
  29751. __extends(SSAORenderingPipeline, _super);
  29752. /**
  29753. * @constructor
  29754. * @param {string} name - The rendering pipeline name
  29755. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29756. * @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 }
  29757. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29758. */
  29759. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29760. var _this = this;
  29761. _super.call(this, scene.getEngine(), name);
  29762. // Members
  29763. /**
  29764. * The PassPostProcess id in the pipeline that contains the original scene color
  29765. * @type {string}
  29766. */
  29767. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29768. /**
  29769. * The SSAO PostProcess id in the pipeline
  29770. * @type {string}
  29771. */
  29772. this.SSAORenderEffect = "SSAORenderEffect";
  29773. /**
  29774. * The horizontal blur PostProcess id in the pipeline
  29775. * @type {string}
  29776. */
  29777. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29778. /**
  29779. * The vertical blur PostProcess id in the pipeline
  29780. * @type {string}
  29781. */
  29782. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29783. /**
  29784. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29785. * @type {string}
  29786. */
  29787. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29788. /**
  29789. * The output strength of the SSAO post-process. Default value is 1.0.
  29790. * @type {number}
  29791. */
  29792. this.totalStrength = 1.0;
  29793. /**
  29794. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29795. * @type {number}
  29796. */
  29797. this.radius = 0.0002;
  29798. /**
  29799. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29800. * Must not be equal to fallOff and superior to fallOff.
  29801. * Default value is 0.0075
  29802. * @type {number}
  29803. */
  29804. this.area = 0.0075;
  29805. /**
  29806. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29807. * Must not be equal to area and inferior to area.
  29808. * Default value is 0.0002
  29809. * @type {number}
  29810. */
  29811. this.fallOff = 0.0002;
  29812. this._firstUpdate = true;
  29813. this._scene = scene;
  29814. // Set up assets
  29815. this._createRandomTexture();
  29816. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29817. var ssaoRatio = ratio.ssaoRatio || ratio;
  29818. var combineRatio = ratio.combineRatio || ratio;
  29819. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29820. this._createSSAOPostProcess(ssaoRatio);
  29821. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29822. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29823. this._createSSAOCombinePostProcess(combineRatio);
  29824. // Set up pipeline
  29825. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29826. return _this._originalColorPostProcess;
  29827. }, true));
  29828. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29829. return _this._ssaoPostProcess;
  29830. }, true));
  29831. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29832. return _this._blurHPostProcess;
  29833. }, true));
  29834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29835. return _this._blurVPostProcess;
  29836. }, true));
  29837. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29838. return _this._ssaoCombinePostProcess;
  29839. }, true));
  29840. // Finish
  29841. scene.postProcessRenderPipelineManager.addPipeline(this);
  29842. if (cameras)
  29843. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29844. }
  29845. // Public Methods
  29846. /**
  29847. * Returns the horizontal blur PostProcess
  29848. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29849. */
  29850. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29851. return this._blurHPostProcess;
  29852. };
  29853. /**
  29854. * Returns the vertical blur PostProcess
  29855. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29856. */
  29857. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29858. return this._blurVPostProcess;
  29859. };
  29860. /**
  29861. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29862. */
  29863. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29864. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29865. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29866. this._originalColorPostProcess = undefined;
  29867. this._ssaoPostProcess = undefined;
  29868. this._blurHPostProcess = undefined;
  29869. this._blurVPostProcess = undefined;
  29870. this._ssaoCombinePostProcess = undefined;
  29871. this._randomTexture.dispose();
  29872. if (disableDepthRender)
  29873. this._scene.disableDepthRenderer();
  29874. };
  29875. // Private Methods
  29876. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29877. var _this = this;
  29878. var sampleSphere = [
  29879. 0.5381,
  29880. 0.1856,
  29881. -0.4319,
  29882. 0.1379,
  29883. 0.2486,
  29884. 0.4430,
  29885. 0.3371,
  29886. 0.5679,
  29887. -0.0057,
  29888. -0.6999,
  29889. -0.0451,
  29890. -0.0019,
  29891. 0.0689,
  29892. -0.1598,
  29893. -0.8547,
  29894. 0.0560,
  29895. 0.0069,
  29896. -0.1843,
  29897. -0.0146,
  29898. 0.1402,
  29899. 0.0762,
  29900. 0.0100,
  29901. -0.1924,
  29902. -0.0344,
  29903. -0.3577,
  29904. -0.5301,
  29905. -0.4358,
  29906. -0.3169,
  29907. 0.1063,
  29908. 0.0158,
  29909. 0.0103,
  29910. -0.5869,
  29911. 0.0046,
  29912. -0.0897,
  29913. -0.4940,
  29914. 0.3287,
  29915. 0.7119,
  29916. -0.0154,
  29917. -0.0918,
  29918. -0.0533,
  29919. 0.0596,
  29920. -0.5411,
  29921. 0.0352,
  29922. -0.0631,
  29923. 0.5460,
  29924. -0.4776,
  29925. 0.2847,
  29926. -0.0271
  29927. ];
  29928. var samplesFactor = 1.0 / 16.0;
  29929. 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);
  29930. this._ssaoPostProcess.onApply = function (effect) {
  29931. if (_this._firstUpdate) {
  29932. effect.setArray3("sampleSphere", sampleSphere);
  29933. effect.setFloat("samplesFactor", samplesFactor);
  29934. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29935. _this._firstUpdate = false;
  29936. }
  29937. effect.setFloat("totalStrength", _this.totalStrength);
  29938. effect.setFloat("radius", _this.radius);
  29939. effect.setFloat("area", _this.area);
  29940. effect.setFloat("fallOff", _this.fallOff);
  29941. effect.setTexture("textureSampler", _this._depthTexture);
  29942. effect.setTexture("randomSampler", _this._randomTexture);
  29943. };
  29944. };
  29945. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29946. var _this = this;
  29947. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29948. this._ssaoCombinePostProcess.onApply = function (effect) {
  29949. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29950. };
  29951. };
  29952. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29953. var size = 512;
  29954. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29955. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29956. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29957. var context = this._randomTexture.getContext();
  29958. var rand = function (min, max) {
  29959. return Math.random() * (max - min) + min;
  29960. };
  29961. for (var x = 0; x < size; x++) {
  29962. for (var y = 0; y < size; y++) {
  29963. var randVector = BABYLON.Vector3.Zero();
  29964. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29965. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29966. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29967. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29968. context.fillRect(x, y, 1, 1);
  29969. }
  29970. }
  29971. this._randomTexture.update(false);
  29972. };
  29973. return SSAORenderingPipeline;
  29974. })(BABYLON.PostProcessRenderPipeline);
  29975. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29976. })(BABYLON || (BABYLON = {}));
  29977. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29978. var BABYLON;
  29979. (function (BABYLON) {
  29980. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29981. var VolumetricLightScatteringPostProcess = (function (_super) {
  29982. __extends(VolumetricLightScatteringPostProcess, _super);
  29983. /**
  29984. * @constructor
  29985. * @param {string} name - The post-process name
  29986. * @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)
  29987. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29988. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29989. * @param {number} samples - The post-process quality, default 100
  29990. * @param {number} samplingMode - The post-process filtering mode
  29991. * @param {BABYLON.Engine} engine - The babylon engine
  29992. * @param {boolean} reusable - If the post-process is reusable
  29993. */
  29994. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29995. var _this = this;
  29996. if (samples === void 0) { samples = 100; }
  29997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29998. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29999. this._screenCoordinates = BABYLON.Vector2.Zero();
  30000. /**
  30001. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  30002. * @type {boolean}
  30003. */
  30004. this.useCustomMeshPosition = false;
  30005. /**
  30006. * If the post-process should inverse the light scattering direction
  30007. * @type {boolean}
  30008. */
  30009. this.invert = true;
  30010. /**
  30011. * Array containing the excluded meshes not rendered in the internal pass
  30012. */
  30013. this.excludedMeshes = new Array();
  30014. this.exposure = 0.3;
  30015. this.decay = 0.96815;
  30016. this.weight = 0.58767;
  30017. this.density = 0.926;
  30018. var scene = camera.getScene();
  30019. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  30020. // Configure mesh
  30021. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  30022. // Configure
  30023. this._createPass(scene, ratio.passRatio || ratio);
  30024. this.onApply = function (effect) {
  30025. _this._updateMeshScreenCoordinates(scene);
  30026. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  30027. effect.setFloat("exposure", _this.exposure);
  30028. effect.setFloat("decay", _this.decay);
  30029. effect.setFloat("weight", _this.weight);
  30030. effect.setFloat("density", _this.density);
  30031. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  30032. };
  30033. }
  30034. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  30035. var mesh = subMesh.getMesh();
  30036. var defines = [];
  30037. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30038. var material = subMesh.getMaterial();
  30039. var needUV = false;
  30040. // Render this.mesh as default
  30041. if (mesh === this.mesh) {
  30042. defines.push("#define BASIC_RENDER");
  30043. defines.push("#define NEED_UV");
  30044. needUV = true;
  30045. }
  30046. // Alpha test
  30047. if (material) {
  30048. if (material.needAlphaTesting() || mesh === this.mesh)
  30049. defines.push("#define ALPHATEST");
  30050. if (material.opacityTexture !== undefined) {
  30051. defines.push("#define OPACITY");
  30052. if (material.opacityTexture.getAlphaFromRGB)
  30053. defines.push("#define OPACITYRGB");
  30054. if (!needUV)
  30055. defines.push("#define NEED_UV");
  30056. }
  30057. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30058. attribs.push(BABYLON.VertexBuffer.UVKind);
  30059. defines.push("#define UV1");
  30060. }
  30061. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30062. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30063. defines.push("#define UV2");
  30064. }
  30065. }
  30066. // Bones
  30067. if (mesh.useBones) {
  30068. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30069. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30070. defines.push("#define BONES");
  30071. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30072. }
  30073. // Instances
  30074. if (useInstances) {
  30075. defines.push("#define INSTANCES");
  30076. attribs.push("world0");
  30077. attribs.push("world1");
  30078. attribs.push("world2");
  30079. attribs.push("world3");
  30080. }
  30081. // Get correct effect
  30082. var join = defines.join("\n");
  30083. if (this._cachedDefines !== join) {
  30084. this._cachedDefines = join;
  30085. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  30086. }
  30087. return this._volumetricLightScatteringPass.isReady();
  30088. };
  30089. /**
  30090. * Sets the new light position for light scattering effect
  30091. * @param {BABYLON.Vector3} The new custom light position
  30092. */
  30093. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  30094. this._customMeshPosition = position;
  30095. };
  30096. /**
  30097. * Returns the light position for light scattering effect
  30098. * @return {BABYLON.Vector3} The custom light position
  30099. */
  30100. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  30101. return this._customMeshPosition;
  30102. };
  30103. /**
  30104. * Disposes the internal assets and detaches the post-process from the camera
  30105. */
  30106. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  30107. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  30108. if (rttIndex !== -1) {
  30109. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  30110. }
  30111. this._volumetricLightScatteringRTT.dispose();
  30112. _super.prototype.dispose.call(this, camera);
  30113. };
  30114. /**
  30115. * Returns the render target texture used by the post-process
  30116. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  30117. */
  30118. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  30119. return this._volumetricLightScatteringRTT;
  30120. };
  30121. // Private methods
  30122. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  30123. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  30124. return true;
  30125. }
  30126. return false;
  30127. };
  30128. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  30129. var _this = this;
  30130. var engine = scene.getEngine();
  30131. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  30132. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30133. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30134. this._volumetricLightScatteringRTT.renderList = null;
  30135. this._volumetricLightScatteringRTT.renderParticles = false;
  30136. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  30137. // Custom render function for submeshes
  30138. var renderSubMesh = function (subMesh) {
  30139. var mesh = subMesh.getRenderingMesh();
  30140. if (_this._meshExcluded(mesh)) {
  30141. return;
  30142. }
  30143. var scene = mesh.getScene();
  30144. var engine = scene.getEngine();
  30145. // Culling
  30146. engine.setState(subMesh.getMaterial().backFaceCulling);
  30147. // Managing instances
  30148. var batch = mesh._getInstancesRenderList(subMesh._id);
  30149. if (batch.mustReturn) {
  30150. return;
  30151. }
  30152. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30153. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30154. engine.enableEffect(_this._volumetricLightScatteringPass);
  30155. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  30156. var material = subMesh.getMaterial();
  30157. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  30158. // Alpha test
  30159. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  30160. var alphaTexture = material.getAlphaTestTexture();
  30161. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  30162. if (alphaTexture) {
  30163. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30164. }
  30165. if (material.opacityTexture !== undefined) {
  30166. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  30167. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  30168. }
  30169. }
  30170. // Bones
  30171. if (mesh.useBones) {
  30172. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30173. }
  30174. // Draw
  30175. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  30176. }
  30177. };
  30178. // Render target texture callbacks
  30179. var savedSceneClearColor;
  30180. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  30181. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  30182. savedSceneClearColor = scene.clearColor;
  30183. scene.clearColor = sceneClearColor;
  30184. };
  30185. this._volumetricLightScatteringRTT.onAfterRender = function () {
  30186. scene.clearColor = savedSceneClearColor;
  30187. };
  30188. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  30189. var engine = scene.getEngine();
  30190. var index;
  30191. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30192. renderSubMesh(opaqueSubMeshes.data[index]);
  30193. }
  30194. engine.setAlphaTesting(true);
  30195. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30196. renderSubMesh(alphaTestSubMeshes.data[index]);
  30197. }
  30198. engine.setAlphaTesting(false);
  30199. if (transparentSubMeshes.length) {
  30200. for (index = 0; index < transparentSubMeshes.length; index++) {
  30201. var submesh = transparentSubMeshes.data[index];
  30202. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  30203. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  30204. }
  30205. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  30206. sortedArray.sort(function (a, b) {
  30207. // Alpha index first
  30208. if (a._alphaIndex > b._alphaIndex) {
  30209. return 1;
  30210. }
  30211. if (a._alphaIndex < b._alphaIndex) {
  30212. return -1;
  30213. }
  30214. // Then distance to camera
  30215. if (a._distanceToCamera < b._distanceToCamera) {
  30216. return 1;
  30217. }
  30218. if (a._distanceToCamera > b._distanceToCamera) {
  30219. return -1;
  30220. }
  30221. return 0;
  30222. });
  30223. // Render sub meshes
  30224. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  30225. for (index = 0; index < sortedArray.length; index++) {
  30226. renderSubMesh(sortedArray[index]);
  30227. }
  30228. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30229. }
  30230. };
  30231. };
  30232. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  30233. var transform = scene.getTransformMatrix();
  30234. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  30235. this._screenCoordinates.x = pos.x / this._viewPort.width;
  30236. this._screenCoordinates.y = pos.y / this._viewPort.height;
  30237. if (this.invert)
  30238. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  30239. };
  30240. // Static methods
  30241. /**
  30242. * Creates a default mesh for the Volumeric Light Scattering post-process
  30243. * @param {string} The mesh name
  30244. * @param {BABYLON.Scene} The scene where to create the mesh
  30245. * @return {BABYLON.Mesh} the default mesh
  30246. */
  30247. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  30248. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  30249. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  30250. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  30251. return mesh;
  30252. };
  30253. return VolumetricLightScatteringPostProcess;
  30254. })(BABYLON.PostProcess);
  30255. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  30256. })(BABYLON || (BABYLON = {}));
  30257. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  30258. var BABYLON;
  30259. (function (BABYLON) {
  30260. var LensRenderingPipeline = (function (_super) {
  30261. __extends(LensRenderingPipeline, _super);
  30262. /**
  30263. * @constructor
  30264. *
  30265. * Effect parameters are as follow:
  30266. * {
  30267. * chromatic_aberration: number; // from 0 to x (1 for realism)
  30268. * edge_blur: number; // from 0 to x (1 for realism)
  30269. * distortion: number; // from 0 to x (1 for realism)
  30270. * grain_amount: number; // from 0 to 1
  30271. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  30272. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  30273. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  30274. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  30275. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  30276. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  30277. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  30278. * }
  30279. * Note: if an effect parameter is unset, effect is disabled
  30280. *
  30281. * @param {string} name - The rendering pipeline name
  30282. * @param {object} parameters - An object containing all parameters (see above)
  30283. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30284. * @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)
  30285. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30286. */
  30287. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  30288. var _this = this;
  30289. if (ratio === void 0) { ratio = 1.0; }
  30290. _super.call(this, scene.getEngine(), name);
  30291. // Lens effects can be of the following:
  30292. // - chromatic aberration (slight shift of RGB colors)
  30293. // - blur on the edge of the lens
  30294. // - lens distortion
  30295. // - depth-of-field blur & highlights enhancing
  30296. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  30297. // - grain effect (noise or custom texture)
  30298. // Two additional texture samplers are needed:
  30299. // - depth map (for depth-of-field)
  30300. // - grain texture
  30301. /**
  30302. * The chromatic aberration PostProcess id in the pipeline
  30303. * @type {string}
  30304. */
  30305. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  30306. /**
  30307. * The highlights enhancing PostProcess id in the pipeline
  30308. * @type {string}
  30309. */
  30310. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  30311. /**
  30312. * The depth-of-field PostProcess id in the pipeline
  30313. * @type {string}
  30314. */
  30315. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  30316. this._scene = scene;
  30317. // Fetch texture samplers
  30318. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30319. if (parameters.grain_texture) {
  30320. this._grainTexture = parameters.grain_texture;
  30321. }
  30322. else {
  30323. this._createGrainTexture();
  30324. }
  30325. // save parameters
  30326. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  30327. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  30328. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  30329. this._distortion = parameters.distortion ? parameters.distortion : 0;
  30330. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  30331. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  30332. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  30333. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  30334. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  30335. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  30336. // Create effects
  30337. this._createChromaticAberrationPostProcess(ratio);
  30338. this._createHighlightsPostProcess(ratio);
  30339. this._createDepthOfFieldPostProcess(ratio);
  30340. // Set up pipeline
  30341. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  30342. return _this._chromaticAberrationPostProcess;
  30343. }, true));
  30344. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  30345. return _this._highlightsPostProcess;
  30346. }, true));
  30347. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  30348. return _this._depthOfFieldPostProcess;
  30349. }, true));
  30350. if (this._highlightsGain == -1) {
  30351. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30352. }
  30353. // Finish
  30354. scene.postProcessRenderPipelineManager.addPipeline(this);
  30355. if (cameras) {
  30356. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30357. }
  30358. }
  30359. // public methods (self explanatory)
  30360. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30361. this._edgeBlur = amount;
  30362. };
  30363. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30364. this._edgeBlur = 0;
  30365. };
  30366. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30367. this._grainAmount = amount;
  30368. };
  30369. LensRenderingPipeline.prototype.disableGrain = function () {
  30370. this._grainAmount = 0;
  30371. };
  30372. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30373. this._chromaticAberration = amount;
  30374. };
  30375. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30376. this._chromaticAberration = 0;
  30377. };
  30378. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30379. this._distortion = amount;
  30380. };
  30381. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30382. this._distortion = 0;
  30383. };
  30384. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30385. this._dofDepth = amount;
  30386. };
  30387. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30388. this._dofDepth = -1;
  30389. };
  30390. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30391. this._dofAperture = amount;
  30392. };
  30393. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30394. this._dofPentagon = true;
  30395. };
  30396. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30397. this._dofPentagon = false;
  30398. };
  30399. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30400. this._blurNoise = true;
  30401. };
  30402. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30403. this._blurNoise = false;
  30404. };
  30405. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30406. this._highlightsGain = amount;
  30407. };
  30408. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30409. if (this._highlightsGain == -1) {
  30410. this._highlightsGain = 1.0;
  30411. }
  30412. this._highlightsThreshold = amount;
  30413. };
  30414. LensRenderingPipeline.prototype.disableHighlights = function () {
  30415. this._highlightsGain = -1;
  30416. };
  30417. /**
  30418. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30419. */
  30420. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30421. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30422. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30423. this._chromaticAberrationPostProcess = undefined;
  30424. this._highlightsPostProcess = undefined;
  30425. this._depthOfFieldPostProcess = undefined;
  30426. this._grainTexture.dispose();
  30427. if (disableDepthRender)
  30428. this._scene.disableDepthRenderer();
  30429. };
  30430. // colors shifting and distortion
  30431. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30432. var _this = this;
  30433. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30434. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30435. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30436. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30437. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30438. };
  30439. };
  30440. // highlights enhancing
  30441. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30442. var _this = this;
  30443. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30444. this._highlightsPostProcess.onApply = function (effect) {
  30445. effect.setFloat('gain', _this._highlightsGain);
  30446. effect.setFloat('threshold', _this._highlightsThreshold);
  30447. effect.setBool('pentagon', _this._dofPentagon);
  30448. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30449. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30450. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30451. };
  30452. };
  30453. // colors shifting and distortion
  30454. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30455. var _this = this;
  30456. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30457. "focus_depth",
  30458. "aperture",
  30459. "pentagon",
  30460. "maxZ",
  30461. "edge_blur",
  30462. "chromatic_aberration",
  30463. "distortion",
  30464. "blur_noise",
  30465. "grain_amount",
  30466. "screen_width",
  30467. "screen_height",
  30468. "highlights"
  30469. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30470. this._depthOfFieldPostProcess.onApply = function (effect) {
  30471. effect.setBool('blur_noise', _this._blurNoise);
  30472. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30473. effect.setFloat('grain_amount', _this._grainAmount);
  30474. effect.setTexture("depthSampler", _this._depthTexture);
  30475. effect.setTexture("grainSampler", _this._grainTexture);
  30476. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30477. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30478. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30479. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30480. effect.setFloat('distortion', _this._distortion);
  30481. effect.setFloat('focus_depth', _this._dofDepth);
  30482. effect.setFloat('aperture', _this._dofAperture);
  30483. effect.setFloat('edge_blur', _this._edgeBlur);
  30484. effect.setBool('highlights', (_this._highlightsGain != -1));
  30485. };
  30486. };
  30487. // creates a black and white random noise texture, 512x512
  30488. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30489. var size = 512;
  30490. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30491. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30492. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30493. var context = this._grainTexture.getContext();
  30494. var rand = function (min, max) {
  30495. return Math.random() * (max - min) + min;
  30496. };
  30497. var value;
  30498. for (var x = 0; x < size; x++) {
  30499. for (var y = 0; y < size; y++) {
  30500. value = Math.floor(rand(0.42, 0.58) * 255);
  30501. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30502. context.fillRect(x, y, 1, 1);
  30503. }
  30504. }
  30505. this._grainTexture.update(false);
  30506. };
  30507. return LensRenderingPipeline;
  30508. })(BABYLON.PostProcessRenderPipeline);
  30509. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30510. })(BABYLON || (BABYLON = {}));
  30511. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30512. // This post-process allows the modification of rendered colors by using
  30513. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30514. //
  30515. // The object needs to be provided an url to a texture containing the color
  30516. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30517. // Use an image editing software to tweak the LUT to match your needs.
  30518. //
  30519. // For an example of a color LUT, see here:
  30520. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30521. // For explanations on color grading, see here:
  30522. // http://udn.epicgames.com/Three/ColorGrading.html
  30523. //
  30524. var BABYLON;
  30525. (function (BABYLON) {
  30526. var ColorCorrectionPostProcess = (function (_super) {
  30527. __extends(ColorCorrectionPostProcess, _super);
  30528. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30529. var _this = this;
  30530. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30531. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30532. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30533. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30534. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30535. this.onApply = function (effect) {
  30536. effect.setTexture("colorTable", _this._colorTableTexture);
  30537. };
  30538. }
  30539. return ColorCorrectionPostProcess;
  30540. })(BABYLON.PostProcess);
  30541. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30542. })(BABYLON || (BABYLON = {}));
  30543. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30544. (function (BABYLON) {
  30545. var SmartCollection = (function () {
  30546. function SmartCollection(capacity) {
  30547. if (capacity === void 0) { capacity = 10; }
  30548. this.count = 0;
  30549. this._initialCapacity = capacity;
  30550. this.items = {};
  30551. this._keys = new Array(this._initialCapacity);
  30552. }
  30553. SmartCollection.prototype.add = function (key, item) {
  30554. if (this.items[key] != undefined) {
  30555. return -1;
  30556. }
  30557. this.items[key] = item;
  30558. //literal keys are always strings, but we keep source type of key in _keys array
  30559. this._keys[this.count++] = key;
  30560. if (this.count > this._keys.length) {
  30561. this._keys.length *= 2;
  30562. }
  30563. return this.count;
  30564. };
  30565. SmartCollection.prototype.remove = function (key) {
  30566. if (this.items[key] == undefined) {
  30567. return -1;
  30568. }
  30569. return this.removeItemOfIndex(this.indexOf(key));
  30570. };
  30571. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30572. if (index < this.count && index > -1) {
  30573. delete this.items[this._keys[index]];
  30574. while (index < this.count) {
  30575. this._keys[index] = this._keys[index + 1];
  30576. index++;
  30577. }
  30578. }
  30579. else {
  30580. return -1;
  30581. }
  30582. return --this.count;
  30583. };
  30584. SmartCollection.prototype.indexOf = function (key) {
  30585. for (var i = 0; i !== this.count; i++) {
  30586. if (this._keys[i] === key) {
  30587. return i;
  30588. }
  30589. }
  30590. return -1;
  30591. };
  30592. SmartCollection.prototype.item = function (key) {
  30593. return this.items[key];
  30594. };
  30595. SmartCollection.prototype.getAllKeys = function () {
  30596. if (this.count > 0) {
  30597. var keys = new Array(this.count);
  30598. for (var i = 0; i < this.count; i++) {
  30599. keys[i] = this._keys[i];
  30600. }
  30601. return keys;
  30602. }
  30603. else {
  30604. return undefined;
  30605. }
  30606. };
  30607. SmartCollection.prototype.getKeyByIndex = function (index) {
  30608. if (index < this.count && index > -1) {
  30609. return this._keys[index];
  30610. }
  30611. else {
  30612. return undefined;
  30613. }
  30614. };
  30615. SmartCollection.prototype.getItemByIndex = function (index) {
  30616. if (index < this.count && index > -1) {
  30617. return this.items[this._keys[index]];
  30618. }
  30619. else {
  30620. return undefined;
  30621. }
  30622. };
  30623. SmartCollection.prototype.empty = function () {
  30624. if (this.count > 0) {
  30625. this.count = 0;
  30626. this.items = {};
  30627. this._keys = new Array(this._initialCapacity);
  30628. }
  30629. };
  30630. SmartCollection.prototype.forEach = function (block) {
  30631. var key;
  30632. for (key in this.items) {
  30633. if (this.items.hasOwnProperty(key)) {
  30634. block(this.items[key]);
  30635. }
  30636. }
  30637. };
  30638. return SmartCollection;
  30639. })();
  30640. BABYLON.SmartCollection = SmartCollection;
  30641. })(BABYLON || (BABYLON = {}));
  30642. //# sourceMappingURL=babylon.smartCollection.js.map