babylon.2.1-beta.debug.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579
  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 step = 1 / nbPoints;
  2717. var equation = function (t, val0, val1, val2) {
  2718. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2719. return res;
  2720. };
  2721. for (var i = 0; i <= 1; i += step) {
  2722. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2723. }
  2724. return new Curve3(bez);
  2725. };
  2726. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2727. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2728. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2729. var bez = new Array();
  2730. var step = 1 / nbPoints;
  2731. var equation = function (t, val0, val1, val2, val3) {
  2732. 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;
  2733. return res;
  2734. };
  2735. for (var i = 0; i <= 1; i += step) {
  2736. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2737. }
  2738. return new Curve3(bez);
  2739. };
  2740. Curve3.prototype.getPoints = function () {
  2741. return this._points;
  2742. };
  2743. Curve3.prototype.continue = function (curve) {
  2744. var lastPoint = this._points[this._points.length - 1];
  2745. var continuedPoints = this._points.slice();
  2746. var curvePoints = curve.getPoints();
  2747. for (var i = 1; i < curvePoints.length; i++) {
  2748. continuedPoints.push(curvePoints[i].add(lastPoint));
  2749. }
  2750. return new Curve3(continuedPoints);
  2751. };
  2752. return Curve3;
  2753. })();
  2754. BABYLON.Curve3 = Curve3;
  2755. // Vertex formats
  2756. var PositionNormalVertex = (function () {
  2757. function PositionNormalVertex(position, normal) {
  2758. if (position === void 0) { position = Vector3.Zero(); }
  2759. if (normal === void 0) { normal = Vector3.Up(); }
  2760. this.position = position;
  2761. this.normal = normal;
  2762. }
  2763. PositionNormalVertex.prototype.clone = function () {
  2764. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2765. };
  2766. return PositionNormalVertex;
  2767. })();
  2768. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2769. var PositionNormalTextureVertex = (function () {
  2770. function PositionNormalTextureVertex(position, normal, uv) {
  2771. if (position === void 0) { position = Vector3.Zero(); }
  2772. if (normal === void 0) { normal = Vector3.Up(); }
  2773. if (uv === void 0) { uv = Vector2.Zero(); }
  2774. this.position = position;
  2775. this.normal = normal;
  2776. this.uv = uv;
  2777. }
  2778. PositionNormalTextureVertex.prototype.clone = function () {
  2779. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2780. };
  2781. return PositionNormalTextureVertex;
  2782. })();
  2783. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2784. // SIMD
  2785. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2786. var previousInvertToRef = Matrix.prototype.invertToRef;
  2787. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2788. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2789. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2790. var SIMDHelper = (function () {
  2791. function SIMDHelper() {
  2792. }
  2793. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2794. get: function () {
  2795. return SIMDHelper._isEnabled;
  2796. },
  2797. enumerable: true,
  2798. configurable: true
  2799. });
  2800. SIMDHelper.DisableSIMD = function () {
  2801. // Replace functions
  2802. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2803. Matrix.prototype.invertToRef = previousInvertToRef;
  2804. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2805. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2806. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2807. SIMDHelper._isEnabled = false;
  2808. };
  2809. SIMDHelper.EnableSIMD = function () {
  2810. if (window.SIMD === undefined) {
  2811. return;
  2812. }
  2813. // Replace functions
  2814. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2815. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2816. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2817. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2818. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2819. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2820. get: function () {
  2821. return this._data[0];
  2822. },
  2823. set: function (value) {
  2824. if (!this._data) {
  2825. this._data = new Float32Array(3);
  2826. }
  2827. this._data[0] = value;
  2828. }
  2829. });
  2830. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2831. get: function () {
  2832. return this._data[1];
  2833. },
  2834. set: function (value) {
  2835. this._data[1] = value;
  2836. }
  2837. });
  2838. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2839. get: function () {
  2840. return this._data[2];
  2841. },
  2842. set: function (value) {
  2843. this._data[2] = value;
  2844. }
  2845. });
  2846. SIMDHelper._isEnabled = true;
  2847. };
  2848. SIMDHelper._isEnabled = false;
  2849. return SIMDHelper;
  2850. })();
  2851. BABYLON.SIMDHelper = SIMDHelper;
  2852. if (window.SIMD !== undefined) {
  2853. SIMDHelper.EnableSIMD();
  2854. }
  2855. })(BABYLON || (BABYLON = {}));
  2856. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2857. (function (BABYLON) {
  2858. // Screenshots
  2859. var screenshotCanvas;
  2860. var cloneValue = function (source, destinationObject) {
  2861. if (!source)
  2862. return null;
  2863. if (source instanceof BABYLON.Mesh) {
  2864. return null;
  2865. }
  2866. if (source instanceof BABYLON.SubMesh) {
  2867. return source.clone(destinationObject);
  2868. }
  2869. else if (source.clone) {
  2870. return source.clone();
  2871. }
  2872. return null;
  2873. };
  2874. var Tools = (function () {
  2875. function Tools() {
  2876. }
  2877. Tools.GetFilename = function (path) {
  2878. var index = path.lastIndexOf("/");
  2879. if (index < 0)
  2880. return path;
  2881. return path.substring(index + 1);
  2882. };
  2883. Tools.GetDOMTextContent = function (element) {
  2884. var result = "";
  2885. var child = element.firstChild;
  2886. while (child) {
  2887. if (child.nodeType === 3) {
  2888. result += child.textContent;
  2889. }
  2890. child = child.nextSibling;
  2891. }
  2892. return result;
  2893. };
  2894. Tools.ToDegrees = function (angle) {
  2895. return angle * 180 / Math.PI;
  2896. };
  2897. Tools.ToRadians = function (angle) {
  2898. return angle * Math.PI / 180;
  2899. };
  2900. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2901. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2902. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2903. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2904. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2907. }
  2908. return {
  2909. minimum: minimum,
  2910. maximum: maximum
  2911. };
  2912. };
  2913. Tools.ExtractMinAndMax = function (positions, start, count) {
  2914. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2915. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2916. for (var index = start; index < start + count; index++) {
  2917. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2918. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2919. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2920. }
  2921. return {
  2922. minimum: minimum,
  2923. maximum: maximum
  2924. };
  2925. };
  2926. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2927. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2928. return undefined;
  2929. return Array.isArray(obj) ? obj : [obj];
  2930. };
  2931. // Misc.
  2932. Tools.GetPointerPrefix = function () {
  2933. var eventPrefix = "pointer";
  2934. // Check if hand.js is referenced or if the browser natively supports pointer events
  2935. if (!navigator.pointerEnabled) {
  2936. eventPrefix = "mouse";
  2937. }
  2938. return eventPrefix;
  2939. };
  2940. Tools.QueueNewFrame = function (func) {
  2941. if (window.requestAnimationFrame)
  2942. window.requestAnimationFrame(func);
  2943. else if (window.msRequestAnimationFrame)
  2944. window.msRequestAnimationFrame(func);
  2945. else if (window.webkitRequestAnimationFrame)
  2946. window.webkitRequestAnimationFrame(func);
  2947. else if (window.mozRequestAnimationFrame)
  2948. window.mozRequestAnimationFrame(func);
  2949. else if (window.oRequestAnimationFrame)
  2950. window.oRequestAnimationFrame(func);
  2951. else {
  2952. window.setTimeout(func, 16);
  2953. }
  2954. };
  2955. Tools.RequestFullscreen = function (element) {
  2956. if (element.requestFullscreen)
  2957. element.requestFullscreen();
  2958. else if (element.msRequestFullscreen)
  2959. element.msRequestFullscreen();
  2960. else if (element.webkitRequestFullscreen)
  2961. element.webkitRequestFullscreen();
  2962. else if (element.mozRequestFullScreen)
  2963. element.mozRequestFullScreen();
  2964. };
  2965. Tools.ExitFullscreen = function () {
  2966. if (document.exitFullscreen) {
  2967. document.exitFullscreen();
  2968. }
  2969. else if (document.mozCancelFullScreen) {
  2970. document.mozCancelFullScreen();
  2971. }
  2972. else if (document.webkitCancelFullScreen) {
  2973. document.webkitCancelFullScreen();
  2974. }
  2975. else if (document.msCancelFullScreen) {
  2976. document.msCancelFullScreen();
  2977. }
  2978. };
  2979. // External files
  2980. Tools.CleanUrl = function (url) {
  2981. url = url.replace(/#/mg, "%23");
  2982. return url;
  2983. };
  2984. Tools.LoadImage = function (url, onload, onerror, database) {
  2985. url = Tools.CleanUrl(url);
  2986. var img = new Image();
  2987. if (url.substr(0, 5) !== "data:")
  2988. img.crossOrigin = 'anonymous';
  2989. img.onload = function () {
  2990. onload(img);
  2991. };
  2992. img.onerror = function (err) {
  2993. onerror(img, err);
  2994. };
  2995. var noIndexedDB = function () {
  2996. img.src = url;
  2997. };
  2998. var loadFromIndexedDB = function () {
  2999. database.loadImageFromDB(url, img);
  3000. };
  3001. //ANY database to do!
  3002. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  3003. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3004. }
  3005. else {
  3006. if (url.indexOf("file:") === -1) {
  3007. noIndexedDB();
  3008. }
  3009. else {
  3010. try {
  3011. var textureName = url.substring(5);
  3012. var blobURL;
  3013. try {
  3014. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  3015. }
  3016. catch (ex) {
  3017. // Chrome doesn't support oneTimeOnly parameter
  3018. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  3019. }
  3020. img.src = blobURL;
  3021. }
  3022. catch (e) {
  3023. Tools.Log("Error while trying to load texture: " + textureName);
  3024. img.src = null;
  3025. }
  3026. }
  3027. }
  3028. return img;
  3029. };
  3030. //ANY
  3031. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3032. url = Tools.CleanUrl(url);
  3033. var noIndexedDB = function () {
  3034. var request = new XMLHttpRequest();
  3035. var loadUrl = Tools.BaseUrl + url;
  3036. request.open('GET', loadUrl, true);
  3037. if (useArrayBuffer) {
  3038. request.responseType = "arraybuffer";
  3039. }
  3040. request.onprogress = progressCallBack;
  3041. request.onreadystatechange = function () {
  3042. if (request.readyState === 4) {
  3043. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3044. callback(!useArrayBuffer ? request.responseText : request.response);
  3045. }
  3046. else {
  3047. if (onError) {
  3048. onError();
  3049. }
  3050. else {
  3051. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3052. }
  3053. }
  3054. }
  3055. };
  3056. request.send(null);
  3057. };
  3058. var loadFromIndexedDB = function () {
  3059. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3060. };
  3061. if (url.indexOf("file:") !== -1) {
  3062. var fileName = url.substring(5);
  3063. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3064. }
  3065. else {
  3066. // Caching all files
  3067. if (database && database.enableSceneOffline) {
  3068. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3069. }
  3070. else {
  3071. noIndexedDB();
  3072. }
  3073. }
  3074. };
  3075. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3076. var reader = new FileReader();
  3077. reader.onload = function (e) {
  3078. //target doesn't have result from ts 1.3
  3079. callback(e.target['result']);
  3080. };
  3081. reader.onprogress = progressCallback;
  3082. reader.readAsDataURL(fileToLoad);
  3083. };
  3084. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3085. var reader = new FileReader();
  3086. reader.onerror = function (e) {
  3087. Tools.Log("Error while reading file: " + fileToLoad.name);
  3088. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3089. };
  3090. reader.onload = function (e) {
  3091. //target doesn't have result from ts 1.3
  3092. callback(e.target['result']);
  3093. };
  3094. reader.onprogress = progressCallBack;
  3095. if (!useArrayBuffer) {
  3096. // Asynchronous read
  3097. reader.readAsText(fileToLoad);
  3098. }
  3099. else {
  3100. reader.readAsArrayBuffer(fileToLoad);
  3101. }
  3102. };
  3103. // Misc.
  3104. Tools.Clamp = function (value, min, max) {
  3105. if (min === void 0) { min = 0; }
  3106. if (max === void 0) { max = 1; }
  3107. return Math.min(max, Math.max(min, value));
  3108. };
  3109. // Returns -1 when value is a negative number and
  3110. // +1 when value is a positive number.
  3111. Tools.Sign = function (value) {
  3112. value = +value; // convert to a number
  3113. if (value === 0 || isNaN(value))
  3114. return value;
  3115. return value > 0 ? 1 : -1;
  3116. };
  3117. Tools.Format = function (value, decimals) {
  3118. if (decimals === void 0) { decimals = 2; }
  3119. return value.toFixed(decimals);
  3120. };
  3121. Tools.CheckExtends = function (v, min, max) {
  3122. if (v.x < min.x)
  3123. min.x = v.x;
  3124. if (v.y < min.y)
  3125. min.y = v.y;
  3126. if (v.z < min.z)
  3127. min.z = v.z;
  3128. if (v.x > max.x)
  3129. max.x = v.x;
  3130. if (v.y > max.y)
  3131. max.y = v.y;
  3132. if (v.z > max.z)
  3133. max.z = v.z;
  3134. };
  3135. Tools.WithinEpsilon = function (a, b, epsilon) {
  3136. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3137. var num = a - b;
  3138. return -epsilon <= num && num <= epsilon;
  3139. };
  3140. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3141. for (var prop in source) {
  3142. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3143. continue;
  3144. }
  3145. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3146. continue;
  3147. }
  3148. var sourceValue = source[prop];
  3149. var typeOfSourceValue = typeof sourceValue;
  3150. if (typeOfSourceValue === "function") {
  3151. continue;
  3152. }
  3153. if (typeOfSourceValue === "object") {
  3154. if (sourceValue instanceof Array) {
  3155. destination[prop] = [];
  3156. if (sourceValue.length > 0) {
  3157. if (typeof sourceValue[0] == "object") {
  3158. for (var index = 0; index < sourceValue.length; index++) {
  3159. var clonedValue = cloneValue(sourceValue[index], destination);
  3160. if (destination[prop].indexOf(clonedValue) === -1) {
  3161. destination[prop].push(clonedValue);
  3162. }
  3163. }
  3164. }
  3165. else {
  3166. destination[prop] = sourceValue.slice(0);
  3167. }
  3168. }
  3169. }
  3170. else {
  3171. destination[prop] = cloneValue(sourceValue, destination);
  3172. }
  3173. }
  3174. else {
  3175. destination[prop] = sourceValue;
  3176. }
  3177. }
  3178. };
  3179. Tools.IsEmpty = function (obj) {
  3180. for (var i in obj) {
  3181. return false;
  3182. }
  3183. return true;
  3184. };
  3185. Tools.RegisterTopRootEvents = function (events) {
  3186. for (var index = 0; index < events.length; index++) {
  3187. var event = events[index];
  3188. window.addEventListener(event.name, event.handler, false);
  3189. try {
  3190. if (window.parent) {
  3191. window.parent.addEventListener(event.name, event.handler, false);
  3192. }
  3193. }
  3194. catch (e) {
  3195. }
  3196. }
  3197. };
  3198. Tools.UnregisterTopRootEvents = function (events) {
  3199. for (var index = 0; index < events.length; index++) {
  3200. var event = events[index];
  3201. window.removeEventListener(event.name, event.handler);
  3202. try {
  3203. if (window.parent) {
  3204. window.parent.removeEventListener(event.name, event.handler);
  3205. }
  3206. }
  3207. catch (e) {
  3208. }
  3209. }
  3210. };
  3211. Tools.DumpFramebuffer = function (width, height, engine) {
  3212. // Read the contents of the framebuffer
  3213. var numberOfChannelsByLine = width * 4;
  3214. var halfHeight = height / 2;
  3215. //Reading datas from WebGL
  3216. var data = engine.readPixels(0, 0, width, height);
  3217. for (var i = 0; i < halfHeight; i++) {
  3218. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3219. var currentCell = j + i * numberOfChannelsByLine;
  3220. var targetLine = height - i - 1;
  3221. var targetCell = j + targetLine * numberOfChannelsByLine;
  3222. var temp = data[currentCell];
  3223. data[currentCell] = data[targetCell];
  3224. data[targetCell] = temp;
  3225. }
  3226. }
  3227. // Create a 2D canvas to store the result
  3228. if (!screenshotCanvas) {
  3229. screenshotCanvas = document.createElement('canvas');
  3230. }
  3231. screenshotCanvas.width = width;
  3232. screenshotCanvas.height = height;
  3233. var context = screenshotCanvas.getContext('2d');
  3234. // Copy the pixels to a 2D canvas
  3235. var imageData = context.createImageData(width, height);
  3236. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3237. var castData = imageData.data;
  3238. castData.set(data);
  3239. context.putImageData(imageData, 0, 0);
  3240. var base64Image = screenshotCanvas.toDataURL();
  3241. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3242. if (("download" in document.createElement("a"))) {
  3243. var a = window.document.createElement("a");
  3244. a.href = base64Image;
  3245. var date = new Date();
  3246. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3247. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3248. window.document.body.appendChild(a);
  3249. a.addEventListener("click", function () {
  3250. a.parentElement.removeChild(a);
  3251. });
  3252. a.click();
  3253. }
  3254. else {
  3255. var newWindow = window.open("");
  3256. var img = newWindow.document.createElement("img");
  3257. img.src = base64Image;
  3258. newWindow.document.body.appendChild(img);
  3259. }
  3260. };
  3261. Tools.CreateScreenshot = function (engine, camera, size) {
  3262. var width;
  3263. var height;
  3264. var scene = camera.getScene();
  3265. var previousCamera = null;
  3266. if (scene.activeCamera !== camera) {
  3267. previousCamera = scene.activeCamera;
  3268. scene.activeCamera = camera;
  3269. }
  3270. //If a precision value is specified
  3271. if (size.precision) {
  3272. width = Math.round(engine.getRenderWidth() * size.precision);
  3273. height = Math.round(width / engine.getAspectRatio(camera));
  3274. size = { width: width, height: height };
  3275. }
  3276. else if (size.width && size.height) {
  3277. width = size.width;
  3278. height = size.height;
  3279. }
  3280. else if (size.width && !size.height) {
  3281. width = size.width;
  3282. height = Math.round(width / engine.getAspectRatio(camera));
  3283. size = { width: width, height: height };
  3284. }
  3285. else if (size.height && !size.width) {
  3286. height = size.height;
  3287. width = Math.round(height * engine.getAspectRatio(camera));
  3288. size = { width: width, height: height };
  3289. }
  3290. else if (!isNaN(size)) {
  3291. height = size;
  3292. width = size;
  3293. }
  3294. else {
  3295. Tools.Error("Invalid 'size' parameter !");
  3296. return;
  3297. }
  3298. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3299. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3300. texture.renderList = scene.meshes;
  3301. texture.onAfterRender = function () {
  3302. Tools.DumpFramebuffer(width, height, engine);
  3303. };
  3304. scene.incrementRenderId();
  3305. texture.render(true);
  3306. texture.dispose();
  3307. if (previousCamera) {
  3308. scene.activeCamera = previousCamera;
  3309. }
  3310. };
  3311. // XHR response validator for local file scenario
  3312. Tools.ValidateXHRData = function (xhr, dataType) {
  3313. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3314. if (dataType === void 0) { dataType = 7; }
  3315. try {
  3316. if (dataType & 1) {
  3317. if (xhr.responseText && xhr.responseText.length > 0) {
  3318. return true;
  3319. }
  3320. else if (dataType === 1) {
  3321. return false;
  3322. }
  3323. }
  3324. if (dataType & 2) {
  3325. // Check header width and height since there is no "TGA" magic number
  3326. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3327. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3328. return true;
  3329. }
  3330. else if (dataType === 2) {
  3331. return false;
  3332. }
  3333. }
  3334. if (dataType & 4) {
  3335. // Check for the "DDS" magic number
  3336. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3337. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3338. return true;
  3339. }
  3340. else {
  3341. return false;
  3342. }
  3343. }
  3344. }
  3345. catch (e) {
  3346. }
  3347. return false;
  3348. };
  3349. Object.defineProperty(Tools, "NoneLogLevel", {
  3350. get: function () {
  3351. return Tools._NoneLogLevel;
  3352. },
  3353. enumerable: true,
  3354. configurable: true
  3355. });
  3356. Object.defineProperty(Tools, "MessageLogLevel", {
  3357. get: function () {
  3358. return Tools._MessageLogLevel;
  3359. },
  3360. enumerable: true,
  3361. configurable: true
  3362. });
  3363. Object.defineProperty(Tools, "WarningLogLevel", {
  3364. get: function () {
  3365. return Tools._WarningLogLevel;
  3366. },
  3367. enumerable: true,
  3368. configurable: true
  3369. });
  3370. Object.defineProperty(Tools, "ErrorLogLevel", {
  3371. get: function () {
  3372. return Tools._ErrorLogLevel;
  3373. },
  3374. enumerable: true,
  3375. configurable: true
  3376. });
  3377. Object.defineProperty(Tools, "AllLogLevel", {
  3378. get: function () {
  3379. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3380. },
  3381. enumerable: true,
  3382. configurable: true
  3383. });
  3384. Tools._AddLogEntry = function (entry) {
  3385. Tools._LogCache = entry + Tools._LogCache;
  3386. if (Tools.OnNewCacheEntry) {
  3387. Tools.OnNewCacheEntry(entry);
  3388. }
  3389. };
  3390. Tools._FormatMessage = function (message) {
  3391. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3392. var date = new Date();
  3393. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3394. };
  3395. Tools._LogDisabled = function (message) {
  3396. // nothing to do
  3397. };
  3398. Tools._LogEnabled = function (message) {
  3399. var formattedMessage = Tools._FormatMessage(message);
  3400. console.log("BJS - " + formattedMessage);
  3401. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3402. Tools._AddLogEntry(entry);
  3403. };
  3404. Tools._WarnDisabled = function (message) {
  3405. // nothing to do
  3406. };
  3407. Tools._WarnEnabled = function (message) {
  3408. var formattedMessage = Tools._FormatMessage(message);
  3409. console.warn("BJS - " + formattedMessage);
  3410. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3411. Tools._AddLogEntry(entry);
  3412. };
  3413. Tools._ErrorDisabled = function (message) {
  3414. // nothing to do
  3415. };
  3416. Tools._ErrorEnabled = function (message) {
  3417. var formattedMessage = Tools._FormatMessage(message);
  3418. console.error("BJS - " + formattedMessage);
  3419. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3420. Tools._AddLogEntry(entry);
  3421. };
  3422. Object.defineProperty(Tools, "LogCache", {
  3423. get: function () {
  3424. return Tools._LogCache;
  3425. },
  3426. enumerable: true,
  3427. configurable: true
  3428. });
  3429. Object.defineProperty(Tools, "LogLevels", {
  3430. set: function (level) {
  3431. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3432. Tools.Log = Tools._LogEnabled;
  3433. }
  3434. else {
  3435. Tools.Log = Tools._LogDisabled;
  3436. }
  3437. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3438. Tools.Warn = Tools._WarnEnabled;
  3439. }
  3440. else {
  3441. Tools.Warn = Tools._WarnDisabled;
  3442. }
  3443. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3444. Tools.Error = Tools._ErrorEnabled;
  3445. }
  3446. else {
  3447. Tools.Error = Tools._ErrorDisabled;
  3448. }
  3449. },
  3450. enumerable: true,
  3451. configurable: true
  3452. });
  3453. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3454. get: function () {
  3455. return Tools._PerformanceNoneLogLevel;
  3456. },
  3457. enumerable: true,
  3458. configurable: true
  3459. });
  3460. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3461. get: function () {
  3462. return Tools._PerformanceUserMarkLogLevel;
  3463. },
  3464. enumerable: true,
  3465. configurable: true
  3466. });
  3467. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3468. get: function () {
  3469. return Tools._PerformanceConsoleLogLevel;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3475. set: function (level) {
  3476. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3477. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3478. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3479. return;
  3480. }
  3481. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3482. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3483. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3484. return;
  3485. }
  3486. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3487. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3488. },
  3489. enumerable: true,
  3490. configurable: true
  3491. });
  3492. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3493. };
  3494. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3495. };
  3496. Tools._StartUserMark = function (counterName, condition) {
  3497. if (condition === void 0) { condition = true; }
  3498. if (!condition || !Tools._performance.mark) {
  3499. return;
  3500. }
  3501. Tools._performance.mark(counterName + "-Begin");
  3502. };
  3503. Tools._EndUserMark = function (counterName, condition) {
  3504. if (condition === void 0) { condition = true; }
  3505. if (!condition || !Tools._performance.mark) {
  3506. return;
  3507. }
  3508. Tools._performance.mark(counterName + "-End");
  3509. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3510. };
  3511. Tools._StartPerformanceConsole = function (counterName, condition) {
  3512. if (condition === void 0) { condition = true; }
  3513. if (!condition) {
  3514. return;
  3515. }
  3516. Tools._StartUserMark(counterName, condition);
  3517. if (console.time) {
  3518. console.time(counterName);
  3519. }
  3520. };
  3521. Tools._EndPerformanceConsole = function (counterName, condition) {
  3522. if (condition === void 0) { condition = true; }
  3523. if (!condition) {
  3524. return;
  3525. }
  3526. Tools._EndUserMark(counterName, condition);
  3527. if (console.time) {
  3528. console.timeEnd(counterName);
  3529. }
  3530. };
  3531. Object.defineProperty(Tools, "Now", {
  3532. get: function () {
  3533. if (window.performance && window.performance.now) {
  3534. return window.performance.now();
  3535. }
  3536. return new Date().getTime();
  3537. },
  3538. enumerable: true,
  3539. configurable: true
  3540. });
  3541. // Deprecated
  3542. Tools.GetFps = function () {
  3543. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3544. return 0;
  3545. };
  3546. Tools.BaseUrl = "";
  3547. Tools.GetExponantOfTwo = function (value, max) {
  3548. var count = 1;
  3549. do {
  3550. count *= 2;
  3551. } while (count < value);
  3552. if (count > max)
  3553. count = max;
  3554. return count;
  3555. };
  3556. // Logs
  3557. Tools._NoneLogLevel = 0;
  3558. Tools._MessageLogLevel = 1;
  3559. Tools._WarningLogLevel = 2;
  3560. Tools._ErrorLogLevel = 4;
  3561. Tools._LogCache = "";
  3562. Tools.Log = Tools._LogEnabled;
  3563. Tools.Warn = Tools._WarnEnabled;
  3564. Tools.Error = Tools._ErrorEnabled;
  3565. // Performances
  3566. Tools._PerformanceNoneLogLevel = 0;
  3567. Tools._PerformanceUserMarkLogLevel = 1;
  3568. Tools._PerformanceConsoleLogLevel = 2;
  3569. Tools._performance = window.performance;
  3570. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3571. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3572. return Tools;
  3573. })();
  3574. BABYLON.Tools = Tools;
  3575. /**
  3576. * An implementation of a loop for asynchronous functions.
  3577. */
  3578. var AsyncLoop = (function () {
  3579. /**
  3580. * Constroctor.
  3581. * @param iterations the number of iterations.
  3582. * @param _fn the function to run each iteration
  3583. * @param _successCallback the callback that will be called upon succesful execution
  3584. * @param offset starting offset.
  3585. */
  3586. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3587. if (offset === void 0) { offset = 0; }
  3588. this.iterations = iterations;
  3589. this._fn = _fn;
  3590. this._successCallback = _successCallback;
  3591. this.index = offset - 1;
  3592. this._done = false;
  3593. }
  3594. /**
  3595. * Execute the next iteration. Must be called after the last iteration was finished.
  3596. */
  3597. AsyncLoop.prototype.executeNext = function () {
  3598. if (!this._done) {
  3599. if (this.index + 1 < this.iterations) {
  3600. ++this.index;
  3601. this._fn(this);
  3602. }
  3603. else {
  3604. this.breakLoop();
  3605. }
  3606. }
  3607. };
  3608. /**
  3609. * Break the loop and run the success callback.
  3610. */
  3611. AsyncLoop.prototype.breakLoop = function () {
  3612. this._done = true;
  3613. this._successCallback();
  3614. };
  3615. /**
  3616. * Helper function
  3617. */
  3618. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3619. if (offset === void 0) { offset = 0; }
  3620. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3621. loop.executeNext();
  3622. return loop;
  3623. };
  3624. /**
  3625. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3626. * @param iterations total number of iterations
  3627. * @param syncedIterations number of synchronous iterations in each async iteration.
  3628. * @param fn the function to call each iteration.
  3629. * @param callback a success call back that will be called when iterating stops.
  3630. * @param breakFunction a break condition (optional)
  3631. * @param timeout timeout settings for the setTimeout function. default - 0.
  3632. * @constructor
  3633. */
  3634. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3635. if (timeout === void 0) { timeout = 0; }
  3636. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3637. if (breakFunction && breakFunction())
  3638. loop.breakLoop();
  3639. else {
  3640. setTimeout(function () {
  3641. for (var i = 0; i < syncedIterations; ++i) {
  3642. var iteration = (loop.index * syncedIterations) + i;
  3643. if (iteration >= iterations)
  3644. break;
  3645. fn(iteration);
  3646. if (breakFunction && breakFunction()) {
  3647. loop.breakLoop();
  3648. break;
  3649. }
  3650. }
  3651. loop.executeNext();
  3652. }, timeout);
  3653. }
  3654. }, callback);
  3655. };
  3656. return AsyncLoop;
  3657. })();
  3658. BABYLON.AsyncLoop = AsyncLoop;
  3659. })(BABYLON || (BABYLON = {}));
  3660. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3661. (function (BABYLON) {
  3662. var _DepthCullingState = (function () {
  3663. function _DepthCullingState() {
  3664. this._isDepthTestDirty = false;
  3665. this._isDepthMaskDirty = false;
  3666. this._isDepthFuncDirty = false;
  3667. this._isCullFaceDirty = false;
  3668. this._isCullDirty = false;
  3669. this._isZOffsetDirty = false;
  3670. }
  3671. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3672. get: function () {
  3673. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3674. },
  3675. enumerable: true,
  3676. configurable: true
  3677. });
  3678. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3679. get: function () {
  3680. return this._zOffset;
  3681. },
  3682. set: function (value) {
  3683. if (this._zOffset === value) {
  3684. return;
  3685. }
  3686. this._zOffset = value;
  3687. this._isZOffsetDirty = true;
  3688. },
  3689. enumerable: true,
  3690. configurable: true
  3691. });
  3692. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3693. get: function () {
  3694. return this._cullFace;
  3695. },
  3696. set: function (value) {
  3697. if (this._cullFace === value) {
  3698. return;
  3699. }
  3700. this._cullFace = value;
  3701. this._isCullFaceDirty = true;
  3702. },
  3703. enumerable: true,
  3704. configurable: true
  3705. });
  3706. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3707. get: function () {
  3708. return this._cull;
  3709. },
  3710. set: function (value) {
  3711. if (this._cull === value) {
  3712. return;
  3713. }
  3714. this._cull = value;
  3715. this._isCullDirty = true;
  3716. },
  3717. enumerable: true,
  3718. configurable: true
  3719. });
  3720. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3721. get: function () {
  3722. return this._depthFunc;
  3723. },
  3724. set: function (value) {
  3725. if (this._depthFunc === value) {
  3726. return;
  3727. }
  3728. this._depthFunc = value;
  3729. this._isDepthFuncDirty = true;
  3730. },
  3731. enumerable: true,
  3732. configurable: true
  3733. });
  3734. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3735. get: function () {
  3736. return this._depthMask;
  3737. },
  3738. set: function (value) {
  3739. if (this._depthMask === value) {
  3740. return;
  3741. }
  3742. this._depthMask = value;
  3743. this._isDepthMaskDirty = true;
  3744. },
  3745. enumerable: true,
  3746. configurable: true
  3747. });
  3748. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3749. get: function () {
  3750. return this._depthTest;
  3751. },
  3752. set: function (value) {
  3753. if (this._depthTest === value) {
  3754. return;
  3755. }
  3756. this._depthTest = value;
  3757. this._isDepthTestDirty = true;
  3758. },
  3759. enumerable: true,
  3760. configurable: true
  3761. });
  3762. _DepthCullingState.prototype.reset = function () {
  3763. this._depthMask = true;
  3764. this._depthTest = true;
  3765. this._depthFunc = null;
  3766. this._cull = null;
  3767. this._cullFace = null;
  3768. this._zOffset = 0;
  3769. this._isDepthTestDirty = true;
  3770. this._isDepthMaskDirty = true;
  3771. this._isDepthFuncDirty = false;
  3772. this._isCullFaceDirty = false;
  3773. this._isCullDirty = false;
  3774. this._isZOffsetDirty = false;
  3775. };
  3776. _DepthCullingState.prototype.apply = function (gl) {
  3777. if (!this.isDirty) {
  3778. return;
  3779. }
  3780. // Cull
  3781. if (this._isCullDirty) {
  3782. if (this.cull) {
  3783. gl.enable(gl.CULL_FACE);
  3784. }
  3785. else {
  3786. gl.disable(gl.CULL_FACE);
  3787. }
  3788. this._isCullDirty = false;
  3789. }
  3790. // Cull face
  3791. if (this._isCullFaceDirty) {
  3792. gl.cullFace(this.cullFace);
  3793. this._isCullFaceDirty = false;
  3794. }
  3795. // Depth mask
  3796. if (this._isDepthMaskDirty) {
  3797. gl.depthMask(this.depthMask);
  3798. this._isDepthMaskDirty = false;
  3799. }
  3800. // Depth test
  3801. if (this._isDepthTestDirty) {
  3802. if (this.depthTest) {
  3803. gl.enable(gl.DEPTH_TEST);
  3804. }
  3805. else {
  3806. gl.disable(gl.DEPTH_TEST);
  3807. }
  3808. this._isDepthTestDirty = false;
  3809. }
  3810. // Depth func
  3811. if (this._isDepthFuncDirty) {
  3812. gl.depthFunc(this.depthFunc);
  3813. this._isDepthFuncDirty = false;
  3814. }
  3815. // zOffset
  3816. if (this._isZOffsetDirty) {
  3817. if (this.zOffset) {
  3818. gl.enable(gl.POLYGON_OFFSET_FILL);
  3819. gl.polygonOffset(this.zOffset, 0);
  3820. }
  3821. else {
  3822. gl.disable(gl.POLYGON_OFFSET_FILL);
  3823. }
  3824. this._isZOffsetDirty = false;
  3825. }
  3826. };
  3827. return _DepthCullingState;
  3828. })();
  3829. BABYLON._DepthCullingState = _DepthCullingState;
  3830. var _AlphaState = (function () {
  3831. function _AlphaState() {
  3832. this._isAlphaBlendDirty = false;
  3833. this._isBlendFunctionParametersDirty = false;
  3834. this._alphaBlend = false;
  3835. this._blendFunctionParameters = new Array(4);
  3836. }
  3837. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3838. get: function () {
  3839. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3840. },
  3841. enumerable: true,
  3842. configurable: true
  3843. });
  3844. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3845. get: function () {
  3846. return this._alphaBlend;
  3847. },
  3848. set: function (value) {
  3849. if (this._alphaBlend === value) {
  3850. return;
  3851. }
  3852. this._alphaBlend = value;
  3853. this._isAlphaBlendDirty = true;
  3854. },
  3855. enumerable: true,
  3856. configurable: true
  3857. });
  3858. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3859. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3860. return;
  3861. }
  3862. this._blendFunctionParameters[0] = value0;
  3863. this._blendFunctionParameters[1] = value1;
  3864. this._blendFunctionParameters[2] = value2;
  3865. this._blendFunctionParameters[3] = value3;
  3866. this._isBlendFunctionParametersDirty = true;
  3867. };
  3868. _AlphaState.prototype.reset = function () {
  3869. this._alphaBlend = false;
  3870. this._blendFunctionParameters[0] = null;
  3871. this._blendFunctionParameters[1] = null;
  3872. this._blendFunctionParameters[2] = null;
  3873. this._blendFunctionParameters[3] = null;
  3874. this._isAlphaBlendDirty = true;
  3875. this._isBlendFunctionParametersDirty = false;
  3876. };
  3877. _AlphaState.prototype.apply = function (gl) {
  3878. if (!this.isDirty) {
  3879. return;
  3880. }
  3881. // Alpha blend
  3882. if (this._isAlphaBlendDirty) {
  3883. if (this._alphaBlend) {
  3884. gl.enable(gl.BLEND);
  3885. }
  3886. else {
  3887. gl.disable(gl.BLEND);
  3888. }
  3889. this._isAlphaBlendDirty = false;
  3890. }
  3891. // Alpha function
  3892. if (this._isBlendFunctionParametersDirty) {
  3893. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3894. this._isBlendFunctionParametersDirty = false;
  3895. }
  3896. };
  3897. return _AlphaState;
  3898. })();
  3899. BABYLON._AlphaState = _AlphaState;
  3900. var compileShader = function (gl, source, type, defines) {
  3901. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3902. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3903. gl.compileShader(shader);
  3904. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3905. throw new Error(gl.getShaderInfoLog(shader));
  3906. }
  3907. return shader;
  3908. };
  3909. var getWebGLTextureType = function (gl, type) {
  3910. var textureType = gl.UNSIGNED_BYTE;
  3911. if (type === Engine.TEXTURETYPE_FLOAT)
  3912. textureType = gl.FLOAT;
  3913. return textureType;
  3914. };
  3915. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3916. var magFilter = gl.NEAREST;
  3917. var minFilter = gl.NEAREST;
  3918. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3919. magFilter = gl.LINEAR;
  3920. if (generateMipMaps) {
  3921. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3922. }
  3923. else {
  3924. minFilter = gl.LINEAR;
  3925. }
  3926. }
  3927. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3928. magFilter = gl.LINEAR;
  3929. if (generateMipMaps) {
  3930. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3931. }
  3932. else {
  3933. minFilter = gl.LINEAR;
  3934. }
  3935. }
  3936. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3937. magFilter = gl.NEAREST;
  3938. if (generateMipMaps) {
  3939. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3940. }
  3941. else {
  3942. minFilter = gl.NEAREST;
  3943. }
  3944. }
  3945. return {
  3946. min: minFilter,
  3947. mag: magFilter
  3948. };
  3949. };
  3950. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3952. var engine = scene.getEngine();
  3953. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3954. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3955. gl.bindTexture(gl.TEXTURE_2D, texture);
  3956. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3957. texture._baseWidth = width;
  3958. texture._baseHeight = height;
  3959. texture._width = potWidth;
  3960. texture._height = potHeight;
  3961. texture.isReady = true;
  3962. processFunction(potWidth, potHeight);
  3963. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3965. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3966. if (!noMipmap && !isCompressed) {
  3967. gl.generateMipmap(gl.TEXTURE_2D);
  3968. }
  3969. gl.bindTexture(gl.TEXTURE_2D, null);
  3970. engine._activeTexturesCache = [];
  3971. texture.samplingMode = samplingMode;
  3972. scene._removePendingData(texture);
  3973. };
  3974. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3975. var onload = function () {
  3976. loadedImages[index] = img;
  3977. loadedImages._internalCount++;
  3978. scene._removePendingData(img);
  3979. if (loadedImages._internalCount === 6) {
  3980. onfinish(loadedImages);
  3981. }
  3982. };
  3983. var onerror = function () {
  3984. scene._removePendingData(img);
  3985. };
  3986. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3987. scene._addPendingData(img);
  3988. };
  3989. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3990. var loadedImages = [];
  3991. loadedImages._internalCount = 0;
  3992. for (var index = 0; index < 6; index++) {
  3993. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3994. }
  3995. };
  3996. var EngineCapabilities = (function () {
  3997. function EngineCapabilities() {
  3998. }
  3999. return EngineCapabilities;
  4000. })();
  4001. BABYLON.EngineCapabilities = EngineCapabilities;
  4002. /**
  4003. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  4004. */
  4005. var Engine = (function () {
  4006. /**
  4007. * @constructor
  4008. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  4009. * @param {boolean} [antialias] - enable antialias
  4010. * @param options - further options to be sent to the getContext function
  4011. */
  4012. function Engine(canvas, antialias, options) {
  4013. var _this = this;
  4014. // Public members
  4015. this.isFullscreen = false;
  4016. this.isPointerLock = false;
  4017. this.cullBackFaces = true;
  4018. this.renderEvenInBackground = true;
  4019. this.scenes = new Array();
  4020. this._windowIsBackground = false;
  4021. this._loadingDivBackgroundColor = "black";
  4022. this._drawCalls = 0;
  4023. this._renderingQueueLaunched = false;
  4024. this._activeRenderLoops = [];
  4025. // FPS
  4026. this.fpsRange = 60;
  4027. this.previousFramesDuration = [];
  4028. this.fps = 60;
  4029. this.deltaTime = 0;
  4030. // States
  4031. this._depthCullingState = new _DepthCullingState();
  4032. this._alphaState = new _AlphaState();
  4033. this._alphaMode = Engine.ALPHA_DISABLE;
  4034. // Cache
  4035. this._loadedTexturesCache = new Array();
  4036. this._activeTexturesCache = new Array();
  4037. this._compiledEffects = {};
  4038. this._uintIndicesCurrentlySet = false;
  4039. this._renderingCanvas = canvas;
  4040. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4041. options = options || {};
  4042. options.antialias = antialias;
  4043. try {
  4044. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4045. }
  4046. catch (e) {
  4047. throw new Error("WebGL not supported");
  4048. }
  4049. if (!this._gl) {
  4050. throw new Error("WebGL not supported");
  4051. }
  4052. this._onBlur = function () {
  4053. _this._windowIsBackground = true;
  4054. };
  4055. this._onFocus = function () {
  4056. _this._windowIsBackground = false;
  4057. };
  4058. window.addEventListener("blur", this._onBlur);
  4059. window.addEventListener("focus", this._onFocus);
  4060. // Viewport
  4061. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4062. this.resize();
  4063. // Caps
  4064. this._caps = new EngineCapabilities();
  4065. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4066. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4067. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4068. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4069. // Infos
  4070. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4071. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4072. if (rendererInfo != null) {
  4073. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4074. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4075. }
  4076. if (!this._glVendor) {
  4077. this._glVendor = "Unknown vendor";
  4078. }
  4079. if (!this._glRenderer) {
  4080. this._glRenderer = "Unknown renderer";
  4081. }
  4082. // Extensions
  4083. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4084. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4085. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4086. 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');
  4087. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4088. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4089. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4090. this._caps.highPrecisionShaderSupported = true;
  4091. if (this._gl.getShaderPrecisionFormat) {
  4092. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  4093. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  4094. }
  4095. // Depth buffer
  4096. this.setDepthBuffer(true);
  4097. this.setDepthFunctionToLessOrEqual();
  4098. this.setDepthWrite(true);
  4099. // Fullscreen
  4100. this._onFullscreenChange = function () {
  4101. if (document.fullscreen !== undefined) {
  4102. _this.isFullscreen = document.fullscreen;
  4103. }
  4104. else if (document.mozFullScreen !== undefined) {
  4105. _this.isFullscreen = document.mozFullScreen;
  4106. }
  4107. else if (document.webkitIsFullScreen !== undefined) {
  4108. _this.isFullscreen = document.webkitIsFullScreen;
  4109. }
  4110. else if (document.msIsFullScreen !== undefined) {
  4111. _this.isFullscreen = document.msIsFullScreen;
  4112. }
  4113. // Pointer lock
  4114. if (_this.isFullscreen && _this._pointerLockRequested) {
  4115. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4116. if (canvas.requestPointerLock) {
  4117. canvas.requestPointerLock();
  4118. }
  4119. }
  4120. };
  4121. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4122. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4123. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4124. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4125. // Pointer lock
  4126. this._onPointerLockChange = function () {
  4127. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4128. };
  4129. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4130. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4131. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4132. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4133. if (!Engine.audioEngine) {
  4134. Engine.audioEngine = new BABYLON.AudioEngine();
  4135. }
  4136. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4137. }
  4138. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4139. get: function () {
  4140. return Engine._ALPHA_DISABLE;
  4141. },
  4142. enumerable: true,
  4143. configurable: true
  4144. });
  4145. Object.defineProperty(Engine, "ALPHA_ADD", {
  4146. get: function () {
  4147. return Engine._ALPHA_ADD;
  4148. },
  4149. enumerable: true,
  4150. configurable: true
  4151. });
  4152. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4153. get: function () {
  4154. return Engine._ALPHA_COMBINE;
  4155. },
  4156. enumerable: true,
  4157. configurable: true
  4158. });
  4159. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4160. get: function () {
  4161. return Engine._DELAYLOADSTATE_NONE;
  4162. },
  4163. enumerable: true,
  4164. configurable: true
  4165. });
  4166. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4167. get: function () {
  4168. return Engine._DELAYLOADSTATE_LOADED;
  4169. },
  4170. enumerable: true,
  4171. configurable: true
  4172. });
  4173. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4174. get: function () {
  4175. return Engine._DELAYLOADSTATE_LOADING;
  4176. },
  4177. enumerable: true,
  4178. configurable: true
  4179. });
  4180. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4181. get: function () {
  4182. return Engine._DELAYLOADSTATE_NOTLOADED;
  4183. },
  4184. enumerable: true,
  4185. configurable: true
  4186. });
  4187. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4188. get: function () {
  4189. return Engine._TEXTUREFORMAT_ALPHA;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4195. get: function () {
  4196. return Engine._TEXTUREFORMAT_LUMINANCE;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4202. get: function () {
  4203. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4204. },
  4205. enumerable: true,
  4206. configurable: true
  4207. });
  4208. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4209. get: function () {
  4210. return Engine._TEXTUREFORMAT_RGB;
  4211. },
  4212. enumerable: true,
  4213. configurable: true
  4214. });
  4215. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4216. get: function () {
  4217. return Engine._TEXTUREFORMAT_RGBA;
  4218. },
  4219. enumerable: true,
  4220. configurable: true
  4221. });
  4222. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4223. get: function () {
  4224. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4225. },
  4226. enumerable: true,
  4227. configurable: true
  4228. });
  4229. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4230. get: function () {
  4231. return Engine._TEXTURETYPE_FLOAT;
  4232. },
  4233. enumerable: true,
  4234. configurable: true
  4235. });
  4236. Object.defineProperty(Engine, "Version", {
  4237. get: function () {
  4238. return "2.1.0 beta";
  4239. },
  4240. enumerable: true,
  4241. configurable: true
  4242. });
  4243. Engine.prototype._prepareWorkingCanvas = function () {
  4244. if (this._workingCanvas) {
  4245. return;
  4246. }
  4247. this._workingCanvas = document.createElement("canvas");
  4248. this._workingContext = this._workingCanvas.getContext("2d");
  4249. };
  4250. Engine.prototype.getGlInfo = function () {
  4251. return {
  4252. vendor: this._glVendor,
  4253. renderer: this._glRenderer,
  4254. version: this._glVersion
  4255. };
  4256. };
  4257. Engine.prototype.getAspectRatio = function (camera) {
  4258. var viewport = camera.viewport;
  4259. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4260. };
  4261. Engine.prototype.getRenderWidth = function () {
  4262. if (this._currentRenderTarget) {
  4263. return this._currentRenderTarget._width;
  4264. }
  4265. return this._renderingCanvas.width;
  4266. };
  4267. Engine.prototype.getRenderHeight = function () {
  4268. if (this._currentRenderTarget) {
  4269. return this._currentRenderTarget._height;
  4270. }
  4271. return this._renderingCanvas.height;
  4272. };
  4273. Engine.prototype.getRenderingCanvas = function () {
  4274. return this._renderingCanvas;
  4275. };
  4276. Engine.prototype.getRenderingCanvasClientRect = function () {
  4277. return this._renderingCanvas.getBoundingClientRect();
  4278. };
  4279. Engine.prototype.setHardwareScalingLevel = function (level) {
  4280. this._hardwareScalingLevel = level;
  4281. this.resize();
  4282. };
  4283. Engine.prototype.getHardwareScalingLevel = function () {
  4284. return this._hardwareScalingLevel;
  4285. };
  4286. Engine.prototype.getLoadedTexturesCache = function () {
  4287. return this._loadedTexturesCache;
  4288. };
  4289. Engine.prototype.getCaps = function () {
  4290. return this._caps;
  4291. };
  4292. Object.defineProperty(Engine.prototype, "drawCalls", {
  4293. get: function () {
  4294. return this._drawCalls;
  4295. },
  4296. enumerable: true,
  4297. configurable: true
  4298. });
  4299. // Methods
  4300. Engine.prototype.resetDrawCalls = function () {
  4301. this._drawCalls = 0;
  4302. };
  4303. Engine.prototype.setDepthFunctionToGreater = function () {
  4304. this._depthCullingState.depthFunc = this._gl.GREATER;
  4305. };
  4306. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4307. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4308. };
  4309. Engine.prototype.setDepthFunctionToLess = function () {
  4310. this._depthCullingState.depthFunc = this._gl.LESS;
  4311. };
  4312. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4313. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4314. };
  4315. /**
  4316. * stop executing a render loop function and remove it from the execution array
  4317. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4318. */
  4319. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4320. if (!renderFunction) {
  4321. this._activeRenderLoops = [];
  4322. return;
  4323. }
  4324. var index = this._activeRenderLoops.indexOf(renderFunction);
  4325. if (index >= 0) {
  4326. this._activeRenderLoops.splice(index, 1);
  4327. }
  4328. };
  4329. Engine.prototype._renderLoop = function () {
  4330. var _this = this;
  4331. var shouldRender = true;
  4332. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4333. shouldRender = false;
  4334. }
  4335. if (shouldRender) {
  4336. // Start new frame
  4337. this.beginFrame();
  4338. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4339. var renderFunction = this._activeRenderLoops[index];
  4340. renderFunction();
  4341. }
  4342. // Present
  4343. this.endFrame();
  4344. }
  4345. if (this._activeRenderLoops.length > 0) {
  4346. // Register new frame
  4347. BABYLON.Tools.QueueNewFrame(function () {
  4348. _this._renderLoop();
  4349. });
  4350. }
  4351. else {
  4352. this._renderingQueueLaunched = false;
  4353. }
  4354. };
  4355. /**
  4356. * Register and execute a render loop. The engine can have more than one render function.
  4357. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4358. * @example
  4359. * engine.runRenderLoop(function () {
  4360. * scene.render()
  4361. * })
  4362. */
  4363. Engine.prototype.runRenderLoop = function (renderFunction) {
  4364. var _this = this;
  4365. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4366. return;
  4367. }
  4368. this._activeRenderLoops.push(renderFunction);
  4369. if (!this._renderingQueueLaunched) {
  4370. this._renderingQueueLaunched = true;
  4371. BABYLON.Tools.QueueNewFrame(function () {
  4372. _this._renderLoop();
  4373. });
  4374. }
  4375. };
  4376. /**
  4377. * Toggle full screen mode.
  4378. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4379. */
  4380. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4381. if (this.isFullscreen) {
  4382. BABYLON.Tools.ExitFullscreen();
  4383. }
  4384. else {
  4385. this._pointerLockRequested = requestPointerLock;
  4386. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4387. }
  4388. };
  4389. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4390. this.applyStates();
  4391. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4392. if (this._depthCullingState.depthMask) {
  4393. this._gl.clearDepth(1.0);
  4394. }
  4395. var mode = 0;
  4396. if (backBuffer)
  4397. mode |= this._gl.COLOR_BUFFER_BIT;
  4398. if (depthStencil && this._depthCullingState.depthMask)
  4399. mode |= this._gl.DEPTH_BUFFER_BIT;
  4400. this._gl.clear(mode);
  4401. };
  4402. /**
  4403. * Set the WebGL's viewport
  4404. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4405. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4406. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4407. */
  4408. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4409. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  4410. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  4411. var x = viewport.x || 0;
  4412. var y = viewport.y || 0;
  4413. this._cachedViewport = viewport;
  4414. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4415. };
  4416. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4417. this._cachedViewport = null;
  4418. this._gl.viewport(x, y, width, height);
  4419. };
  4420. Engine.prototype.beginFrame = function () {
  4421. this._measureFps();
  4422. };
  4423. Engine.prototype.endFrame = function () {
  4424. //this.flushFramebuffer();
  4425. };
  4426. /**
  4427. * resize the view according to the canvas' size.
  4428. * @example
  4429. * window.addEventListener("resize", function () {
  4430. * engine.resize();
  4431. * });
  4432. */
  4433. Engine.prototype.resize = function () {
  4434. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  4435. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  4436. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  4437. };
  4438. /**
  4439. * force a specific size of the canvas
  4440. * @param {number} width - the new canvas' width
  4441. * @param {number} height - the new canvas' height
  4442. */
  4443. Engine.prototype.setSize = function (width, height) {
  4444. this._renderingCanvas.width = width;
  4445. this._renderingCanvas.height = height;
  4446. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4447. for (var index = 0; index < this.scenes.length; index++) {
  4448. var scene = this.scenes[index];
  4449. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  4450. var cam = scene.cameras[camIndex];
  4451. cam._currentRenderId = 0;
  4452. }
  4453. }
  4454. };
  4455. Engine.prototype.bindFramebuffer = function (texture) {
  4456. this._currentRenderTarget = texture;
  4457. var gl = this._gl;
  4458. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4459. this._gl.viewport(0, 0, texture._width, texture._height);
  4460. this.wipeCaches();
  4461. };
  4462. Engine.prototype.unBindFramebuffer = function (texture) {
  4463. this._currentRenderTarget = null;
  4464. if (texture.generateMipMaps) {
  4465. var gl = this._gl;
  4466. gl.bindTexture(gl.TEXTURE_2D, texture);
  4467. gl.generateMipmap(gl.TEXTURE_2D);
  4468. gl.bindTexture(gl.TEXTURE_2D, null);
  4469. }
  4470. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4471. };
  4472. Engine.prototype.flushFramebuffer = function () {
  4473. this._gl.flush();
  4474. };
  4475. Engine.prototype.restoreDefaultFramebuffer = function () {
  4476. this._currentRenderTarget = null;
  4477. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4478. this.setViewport(this._cachedViewport);
  4479. this.wipeCaches();
  4480. };
  4481. // VBOs
  4482. Engine.prototype._resetVertexBufferBinding = function () {
  4483. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4484. this._cachedVertexBuffers = null;
  4485. };
  4486. Engine.prototype.createVertexBuffer = function (vertices) {
  4487. var vbo = this._gl.createBuffer();
  4488. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4489. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4490. this._resetVertexBufferBinding();
  4491. vbo.references = 1;
  4492. return vbo;
  4493. };
  4494. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4495. var vbo = this._gl.createBuffer();
  4496. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4497. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4498. this._resetVertexBufferBinding();
  4499. vbo.references = 1;
  4500. return vbo;
  4501. };
  4502. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4503. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4504. if (offset === undefined) {
  4505. offset = 0;
  4506. }
  4507. if (vertices instanceof Float32Array) {
  4508. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4509. }
  4510. else {
  4511. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4512. }
  4513. this._resetVertexBufferBinding();
  4514. };
  4515. Engine.prototype._resetIndexBufferBinding = function () {
  4516. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4517. this._cachedIndexBuffer = null;
  4518. };
  4519. Engine.prototype.createIndexBuffer = function (indices) {
  4520. var vbo = this._gl.createBuffer();
  4521. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4522. // Check for 32 bits indices
  4523. var arrayBuffer;
  4524. var need32Bits = false;
  4525. if (this._caps.uintIndices) {
  4526. for (var index = 0; index < indices.length; index++) {
  4527. if (indices[index] > 65535) {
  4528. need32Bits = true;
  4529. break;
  4530. }
  4531. }
  4532. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4533. }
  4534. else {
  4535. arrayBuffer = new Uint16Array(indices);
  4536. }
  4537. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4538. this._resetIndexBufferBinding();
  4539. vbo.references = 1;
  4540. vbo.is32Bits = need32Bits;
  4541. return vbo;
  4542. };
  4543. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4544. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4545. this._cachedVertexBuffers = vertexBuffer;
  4546. this._cachedEffectForVertexBuffers = effect;
  4547. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4548. var offset = 0;
  4549. for (var index = 0; index < vertexDeclaration.length; index++) {
  4550. var order = effect.getAttributeLocation(index);
  4551. if (order >= 0) {
  4552. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4553. }
  4554. offset += vertexDeclaration[index] * 4;
  4555. }
  4556. }
  4557. if (this._cachedIndexBuffer !== indexBuffer) {
  4558. this._cachedIndexBuffer = indexBuffer;
  4559. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4560. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4561. }
  4562. };
  4563. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4564. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4565. this._cachedVertexBuffers = vertexBuffers;
  4566. this._cachedEffectForVertexBuffers = effect;
  4567. var attributes = effect.getAttributesNames();
  4568. for (var index = 0; index < attributes.length; index++) {
  4569. var order = effect.getAttributeLocation(index);
  4570. if (order >= 0) {
  4571. var vertexBuffer = vertexBuffers[attributes[index]];
  4572. if (!vertexBuffer) {
  4573. continue;
  4574. }
  4575. var stride = vertexBuffer.getStrideSize();
  4576. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4577. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4578. }
  4579. }
  4580. }
  4581. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4582. this._cachedIndexBuffer = indexBuffer;
  4583. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4584. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4585. }
  4586. };
  4587. Engine.prototype._releaseBuffer = function (buffer) {
  4588. buffer.references--;
  4589. if (buffer.references === 0) {
  4590. this._gl.deleteBuffer(buffer);
  4591. return true;
  4592. }
  4593. return false;
  4594. };
  4595. Engine.prototype.createInstancesBuffer = function (capacity) {
  4596. var buffer = this._gl.createBuffer();
  4597. buffer.capacity = capacity;
  4598. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4599. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4600. return buffer;
  4601. };
  4602. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4603. this._gl.deleteBuffer(buffer);
  4604. };
  4605. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4606. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4607. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4608. for (var index = 0; index < 4; index++) {
  4609. var offsetLocation = offsetLocations[index];
  4610. this._gl.enableVertexAttribArray(offsetLocation);
  4611. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4612. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4613. }
  4614. };
  4615. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4616. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4617. for (var index = 0; index < 4; index++) {
  4618. var offsetLocation = offsetLocations[index];
  4619. this._gl.disableVertexAttribArray(offsetLocation);
  4620. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4621. }
  4622. };
  4623. Engine.prototype.applyStates = function () {
  4624. this._depthCullingState.apply(this._gl);
  4625. this._alphaState.apply(this._gl);
  4626. };
  4627. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4628. // Apply states
  4629. this.applyStates();
  4630. this._drawCalls++;
  4631. // Render
  4632. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4633. if (instancesCount) {
  4634. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4635. return;
  4636. }
  4637. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4638. };
  4639. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4640. // Apply states
  4641. this.applyStates();
  4642. this._drawCalls++;
  4643. if (instancesCount) {
  4644. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4645. return;
  4646. }
  4647. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4648. };
  4649. // Shaders
  4650. Engine.prototype._releaseEffect = function (effect) {
  4651. if (this._compiledEffects[effect._key]) {
  4652. delete this._compiledEffects[effect._key];
  4653. if (effect.getProgram()) {
  4654. this._gl.deleteProgram(effect.getProgram());
  4655. }
  4656. }
  4657. };
  4658. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4659. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4660. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4661. var name = vertex + "+" + fragment + "@" + defines;
  4662. if (this._compiledEffects[name]) {
  4663. return this._compiledEffects[name];
  4664. }
  4665. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4666. effect._key = name;
  4667. this._compiledEffects[name] = effect;
  4668. return effect;
  4669. };
  4670. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4671. if (uniformsNames === void 0) { uniformsNames = []; }
  4672. if (samplers === void 0) { samplers = []; }
  4673. if (defines === void 0) { defines = ""; }
  4674. return this.createEffect({
  4675. vertex: "particles",
  4676. fragmentElement: fragmentName
  4677. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4678. };
  4679. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4680. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4681. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4682. var shaderProgram = this._gl.createProgram();
  4683. this._gl.attachShader(shaderProgram, vertexShader);
  4684. this._gl.attachShader(shaderProgram, fragmentShader);
  4685. this._gl.linkProgram(shaderProgram);
  4686. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4687. if (!linked) {
  4688. var error = this._gl.getProgramInfoLog(shaderProgram);
  4689. if (error) {
  4690. throw new Error(error);
  4691. }
  4692. }
  4693. this._gl.deleteShader(vertexShader);
  4694. this._gl.deleteShader(fragmentShader);
  4695. return shaderProgram;
  4696. };
  4697. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4698. var results = [];
  4699. for (var index = 0; index < uniformsNames.length; index++) {
  4700. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4701. }
  4702. return results;
  4703. };
  4704. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4705. var results = [];
  4706. for (var index = 0; index < attributesNames.length; index++) {
  4707. try {
  4708. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4709. }
  4710. catch (e) {
  4711. results.push(-1);
  4712. }
  4713. }
  4714. return results;
  4715. };
  4716. Engine.prototype.enableEffect = function (effect) {
  4717. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4718. if (effect && effect.onBind) {
  4719. effect.onBind(effect);
  4720. }
  4721. return;
  4722. }
  4723. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4724. // Use program
  4725. this._gl.useProgram(effect.getProgram());
  4726. for (var i in this._vertexAttribArrays) {
  4727. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4728. continue;
  4729. }
  4730. this._vertexAttribArrays[i] = false;
  4731. this._gl.disableVertexAttribArray(i);
  4732. }
  4733. var attributesCount = effect.getAttributesCount();
  4734. for (var index = 0; index < attributesCount; index++) {
  4735. // Attributes
  4736. var order = effect.getAttributeLocation(index);
  4737. if (order >= 0) {
  4738. this._vertexAttribArrays[order] = true;
  4739. this._gl.enableVertexAttribArray(order);
  4740. }
  4741. }
  4742. this._currentEffect = effect;
  4743. if (effect.onBind) {
  4744. effect.onBind(effect);
  4745. }
  4746. };
  4747. Engine.prototype.setArray = function (uniform, array) {
  4748. if (!uniform)
  4749. return;
  4750. this._gl.uniform1fv(uniform, array);
  4751. };
  4752. Engine.prototype.setArray2 = function (uniform, array) {
  4753. if (!uniform || array.length % 2 !== 0)
  4754. return;
  4755. this._gl.uniform2fv(uniform, array);
  4756. };
  4757. Engine.prototype.setArray3 = function (uniform, array) {
  4758. if (!uniform || array.length % 3 !== 0)
  4759. return;
  4760. this._gl.uniform3fv(uniform, array);
  4761. };
  4762. Engine.prototype.setArray4 = function (uniform, array) {
  4763. if (!uniform || array.length % 4 !== 0)
  4764. return;
  4765. this._gl.uniform4fv(uniform, array);
  4766. };
  4767. Engine.prototype.setMatrices = function (uniform, matrices) {
  4768. if (!uniform)
  4769. return;
  4770. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4771. };
  4772. Engine.prototype.setMatrix = function (uniform, matrix) {
  4773. if (!uniform)
  4774. return;
  4775. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4776. };
  4777. Engine.prototype.setFloat = function (uniform, value) {
  4778. if (!uniform)
  4779. return;
  4780. this._gl.uniform1f(uniform, value);
  4781. };
  4782. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4783. if (!uniform)
  4784. return;
  4785. this._gl.uniform2f(uniform, x, y);
  4786. };
  4787. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4788. if (!uniform)
  4789. return;
  4790. this._gl.uniform3f(uniform, x, y, z);
  4791. };
  4792. Engine.prototype.setBool = function (uniform, bool) {
  4793. if (!uniform)
  4794. return;
  4795. this._gl.uniform1i(uniform, bool);
  4796. };
  4797. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4798. if (!uniform)
  4799. return;
  4800. this._gl.uniform4f(uniform, x, y, z, w);
  4801. };
  4802. Engine.prototype.setColor3 = function (uniform, color3) {
  4803. if (!uniform)
  4804. return;
  4805. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4806. };
  4807. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4808. if (!uniform)
  4809. return;
  4810. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4811. };
  4812. // States
  4813. Engine.prototype.setState = function (culling, zOffset, force) {
  4814. if (zOffset === void 0) { zOffset = 0; }
  4815. // Culling
  4816. if (this._depthCullingState.cull !== culling || force) {
  4817. if (culling) {
  4818. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4819. this._depthCullingState.cull = true;
  4820. }
  4821. else {
  4822. this._depthCullingState.cull = false;
  4823. }
  4824. }
  4825. // Z offset
  4826. this._depthCullingState.zOffset = zOffset;
  4827. };
  4828. Engine.prototype.setDepthBuffer = function (enable) {
  4829. this._depthCullingState.depthTest = enable;
  4830. };
  4831. Engine.prototype.getDepthWrite = function () {
  4832. return this._depthCullingState.depthMask;
  4833. };
  4834. Engine.prototype.setDepthWrite = function (enable) {
  4835. this._depthCullingState.depthMask = enable;
  4836. };
  4837. Engine.prototype.setColorWrite = function (enable) {
  4838. this._gl.colorMask(enable, enable, enable, enable);
  4839. };
  4840. Engine.prototype.setAlphaMode = function (mode) {
  4841. switch (mode) {
  4842. case Engine.ALPHA_DISABLE:
  4843. this.setDepthWrite(true);
  4844. this._alphaState.alphaBlend = false;
  4845. break;
  4846. case Engine.ALPHA_COMBINE:
  4847. this.setDepthWrite(false);
  4848. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4849. this._alphaState.alphaBlend = true;
  4850. break;
  4851. case Engine.ALPHA_ADD:
  4852. this.setDepthWrite(false);
  4853. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4854. this._alphaState.alphaBlend = true;
  4855. break;
  4856. }
  4857. this._alphaMode = mode;
  4858. };
  4859. Engine.prototype.getAlphaMode = function () {
  4860. return this._alphaMode;
  4861. };
  4862. Engine.prototype.setAlphaTesting = function (enable) {
  4863. this._alphaTest = enable;
  4864. };
  4865. Engine.prototype.getAlphaTesting = function () {
  4866. return this._alphaTest;
  4867. };
  4868. // Textures
  4869. Engine.prototype.wipeCaches = function () {
  4870. this._activeTexturesCache = [];
  4871. this._currentEffect = null;
  4872. this._depthCullingState.reset();
  4873. this._alphaState.reset();
  4874. this._cachedVertexBuffers = null;
  4875. this._cachedIndexBuffer = null;
  4876. this._cachedEffectForVertexBuffers = null;
  4877. };
  4878. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4879. var gl = this._gl;
  4880. gl.bindTexture(gl.TEXTURE_2D, texture);
  4881. var magFilter = gl.NEAREST;
  4882. var minFilter = gl.NEAREST;
  4883. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4884. magFilter = gl.LINEAR;
  4885. minFilter = gl.LINEAR;
  4886. }
  4887. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4888. magFilter = gl.LINEAR;
  4889. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4890. }
  4891. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4893. gl.bindTexture(gl.TEXTURE_2D, null);
  4894. texture.samplingMode = samplingMode;
  4895. };
  4896. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4897. var _this = this;
  4898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4899. if (onLoad === void 0) { onLoad = null; }
  4900. if (onError === void 0) { onError = null; }
  4901. if (buffer === void 0) { buffer = null; }
  4902. var texture = this._gl.createTexture();
  4903. var extension;
  4904. var fromData = false;
  4905. if (url.substr(0, 5) === "data:") {
  4906. fromData = true;
  4907. }
  4908. if (!fromData)
  4909. extension = url.substr(url.length - 4, 4).toLowerCase();
  4910. else {
  4911. var oldUrl = url;
  4912. fromData = oldUrl.split(':');
  4913. url = oldUrl;
  4914. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4915. }
  4916. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4917. var isTGA = (extension === ".tga");
  4918. scene._addPendingData(texture);
  4919. texture.url = url;
  4920. texture.noMipmap = noMipmap;
  4921. texture.references = 1;
  4922. this._loadedTexturesCache.push(texture);
  4923. var onerror = function () {
  4924. scene._removePendingData(texture);
  4925. if (onError) {
  4926. onError();
  4927. }
  4928. };
  4929. if (isTGA) {
  4930. var callback = function (arrayBuffer) {
  4931. var data = new Uint8Array(arrayBuffer);
  4932. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4933. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4934. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4935. if (onLoad) {
  4936. onLoad();
  4937. }
  4938. }, samplingMode);
  4939. };
  4940. if (!(fromData instanceof Array))
  4941. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4942. callback(arrayBuffer);
  4943. }, onerror, scene.database, true);
  4944. else
  4945. callback(buffer);
  4946. }
  4947. else if (isDDS) {
  4948. callback = function (data) {
  4949. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4950. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4951. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4952. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4953. if (onLoad) {
  4954. onLoad();
  4955. }
  4956. }, samplingMode);
  4957. };
  4958. if (!(fromData instanceof Array))
  4959. BABYLON.Tools.LoadFile(url, function (data) {
  4960. callback(data);
  4961. }, onerror, scene.database, true);
  4962. else
  4963. callback(buffer);
  4964. }
  4965. else {
  4966. var onload = function (img) {
  4967. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4968. var isPot = (img.width === potWidth && img.height === potHeight);
  4969. if (!isPot) {
  4970. _this._prepareWorkingCanvas();
  4971. _this._workingCanvas.width = potWidth;
  4972. _this._workingCanvas.height = potHeight;
  4973. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4974. _this._workingContext.imageSmoothingEnabled = false;
  4975. _this._workingContext.mozImageSmoothingEnabled = false;
  4976. _this._workingContext.oImageSmoothingEnabled = false;
  4977. _this._workingContext.webkitImageSmoothingEnabled = false;
  4978. _this._workingContext.msImageSmoothingEnabled = false;
  4979. }
  4980. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4981. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4982. _this._workingContext.imageSmoothingEnabled = true;
  4983. _this._workingContext.mozImageSmoothingEnabled = true;
  4984. _this._workingContext.oImageSmoothingEnabled = true;
  4985. _this._workingContext.webkitImageSmoothingEnabled = true;
  4986. _this._workingContext.msImageSmoothingEnabled = true;
  4987. }
  4988. }
  4989. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4990. if (onLoad) {
  4991. onLoad();
  4992. }
  4993. }, samplingMode);
  4994. };
  4995. if (!(fromData instanceof Array))
  4996. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4997. else
  4998. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4999. }
  5000. return texture;
  5001. };
  5002. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  5003. var texture = this._gl.createTexture();
  5004. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5005. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5006. // Format
  5007. var internalFormat = this._gl.RGBA;
  5008. switch (format) {
  5009. case Engine.TEXTUREFORMAT_ALPHA:
  5010. internalFormat = this._gl.ALPHA;
  5011. break;
  5012. case Engine.TEXTUREFORMAT_LUMINANCE:
  5013. internalFormat = this._gl.LUMINANCE;
  5014. break;
  5015. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5016. internalFormat = this._gl.LUMINANCE_ALPHA;
  5017. break;
  5018. case Engine.TEXTUREFORMAT_RGB:
  5019. internalFormat = this._gl.RGB;
  5020. break;
  5021. case Engine.TEXTUREFORMAT_RGBA:
  5022. internalFormat = this._gl.RGBA;
  5023. break;
  5024. }
  5025. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  5026. if (generateMipMaps) {
  5027. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5028. }
  5029. // Filters
  5030. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  5031. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5032. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5033. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5034. this._activeTexturesCache = [];
  5035. texture._baseWidth = width;
  5036. texture._baseHeight = height;
  5037. texture._width = width;
  5038. texture._height = height;
  5039. texture.isReady = true;
  5040. texture.references = 1;
  5041. texture.samplingMode = samplingMode;
  5042. this._loadedTexturesCache.push(texture);
  5043. return texture;
  5044. };
  5045. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5046. var texture = this._gl.createTexture();
  5047. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5048. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5049. this._activeTexturesCache = [];
  5050. texture._baseWidth = width;
  5051. texture._baseHeight = height;
  5052. texture._width = width;
  5053. texture._height = height;
  5054. texture.isReady = false;
  5055. texture.generateMipMaps = generateMipMaps;
  5056. texture.references = 1;
  5057. texture.samplingMode = samplingMode;
  5058. this.updateTextureSamplingMode(samplingMode, texture);
  5059. this._loadedTexturesCache.push(texture);
  5060. return texture;
  5061. };
  5062. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5063. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5064. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5065. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5066. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5067. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5068. };
  5069. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5070. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5071. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5072. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5073. if (texture.generateMipMaps) {
  5074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5075. }
  5076. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5077. this._activeTexturesCache = [];
  5078. texture.isReady = true;
  5079. };
  5080. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5081. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5082. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5083. // Scale the video if it is a NPOT using the current working canvas
  5084. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5085. if (!texture._workingCanvas) {
  5086. texture._workingCanvas = document.createElement("canvas");
  5087. texture._workingContext = texture._workingCanvas.getContext("2d");
  5088. texture._workingCanvas.width = texture._width;
  5089. texture._workingCanvas.height = texture._height;
  5090. }
  5091. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5092. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5093. }
  5094. else {
  5095. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5096. }
  5097. if (texture.generateMipMaps) {
  5098. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5099. }
  5100. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5101. this._activeTexturesCache = [];
  5102. texture.isReady = true;
  5103. };
  5104. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5105. // old version had a "generateMipMaps" arg instead of options.
  5106. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5107. // in the same way, generateDepthBuffer is defaulted to true
  5108. var generateMipMaps = false;
  5109. var generateDepthBuffer = true;
  5110. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5111. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5112. if (options !== undefined) {
  5113. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5114. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5115. type = options.type === undefined ? type : options.type;
  5116. if (options.samplingMode !== undefined) {
  5117. samplingMode = options.samplingMode;
  5118. }
  5119. if (type === Engine.TEXTURETYPE_FLOAT) {
  5120. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5121. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5122. }
  5123. }
  5124. var gl = this._gl;
  5125. var texture = gl.createTexture();
  5126. gl.bindTexture(gl.TEXTURE_2D, texture);
  5127. var width = size.width || size;
  5128. var height = size.height || size;
  5129. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5130. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5131. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5132. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5133. }
  5134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5138. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5139. var depthBuffer;
  5140. // Create the depth buffer
  5141. if (generateDepthBuffer) {
  5142. depthBuffer = gl.createRenderbuffer();
  5143. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5144. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5145. }
  5146. // Create the framebuffer
  5147. var framebuffer = gl.createFramebuffer();
  5148. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5149. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5150. if (generateDepthBuffer) {
  5151. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5152. }
  5153. // Unbind
  5154. gl.bindTexture(gl.TEXTURE_2D, null);
  5155. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5156. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5157. texture._framebuffer = framebuffer;
  5158. if (generateDepthBuffer) {
  5159. texture._depthBuffer = depthBuffer;
  5160. }
  5161. texture._width = width;
  5162. texture._height = height;
  5163. texture.isReady = true;
  5164. texture.generateMipMaps = generateMipMaps;
  5165. texture.references = 1;
  5166. texture.samplingMode = samplingMode;
  5167. this._activeTexturesCache = [];
  5168. this._loadedTexturesCache.push(texture);
  5169. return texture;
  5170. };
  5171. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5172. var _this = this;
  5173. var gl = this._gl;
  5174. var texture = gl.createTexture();
  5175. texture.isCube = true;
  5176. texture.url = rootUrl;
  5177. texture.references = 1;
  5178. this._loadedTexturesCache.push(texture);
  5179. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5180. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5181. if (isDDS) {
  5182. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5183. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5184. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5185. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5186. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5187. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5188. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5189. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5190. }
  5191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5193. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5194. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5195. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5196. _this._activeTexturesCache = [];
  5197. texture._width = info.width;
  5198. texture._height = info.height;
  5199. texture.isReady = true;
  5200. }, null, null, true);
  5201. }
  5202. else {
  5203. cascadeLoad(rootUrl, scene, function (imgs) {
  5204. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5205. var height = width;
  5206. _this._prepareWorkingCanvas();
  5207. _this._workingCanvas.width = width;
  5208. _this._workingCanvas.height = height;
  5209. var faces = [
  5210. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5211. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5212. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5213. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5214. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5215. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5216. ];
  5217. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5218. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5219. for (var index = 0; index < faces.length; index++) {
  5220. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5221. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5222. }
  5223. if (!noMipmap) {
  5224. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5225. }
  5226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5229. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5230. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5231. _this._activeTexturesCache = [];
  5232. texture._width = width;
  5233. texture._height = height;
  5234. texture.isReady = true;
  5235. }, extensions);
  5236. }
  5237. return texture;
  5238. };
  5239. Engine.prototype._releaseTexture = function (texture) {
  5240. var gl = this._gl;
  5241. if (texture._framebuffer) {
  5242. gl.deleteFramebuffer(texture._framebuffer);
  5243. }
  5244. if (texture._depthBuffer) {
  5245. gl.deleteRenderbuffer(texture._depthBuffer);
  5246. }
  5247. gl.deleteTexture(texture);
  5248. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5249. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5250. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5251. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5252. this._activeTexturesCache[channel] = null;
  5253. }
  5254. var index = this._loadedTexturesCache.indexOf(texture);
  5255. if (index !== -1) {
  5256. this._loadedTexturesCache.splice(index, 1);
  5257. }
  5258. };
  5259. Engine.prototype.bindSamplers = function (effect) {
  5260. this._gl.useProgram(effect.getProgram());
  5261. var samplers = effect.getSamplers();
  5262. for (var index = 0; index < samplers.length; index++) {
  5263. var uniform = effect.getUniform(samplers[index]);
  5264. this._gl.uniform1i(uniform, index);
  5265. }
  5266. this._currentEffect = null;
  5267. };
  5268. Engine.prototype._bindTexture = function (channel, texture) {
  5269. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5270. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5271. this._activeTexturesCache[channel] = null;
  5272. };
  5273. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5274. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5275. };
  5276. Engine.prototype.setTexture = function (channel, texture) {
  5277. if (channel < 0) {
  5278. return;
  5279. }
  5280. // Not ready?
  5281. if (!texture || !texture.isReady()) {
  5282. if (this._activeTexturesCache[channel] != null) {
  5283. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5284. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5285. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5286. this._activeTexturesCache[channel] = null;
  5287. }
  5288. return;
  5289. }
  5290. // Video
  5291. if (texture instanceof BABYLON.VideoTexture) {
  5292. if (texture.update()) {
  5293. this._activeTexturesCache[channel] = null;
  5294. }
  5295. }
  5296. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5297. texture.delayLoad();
  5298. return;
  5299. }
  5300. if (this._activeTexturesCache[channel] === texture) {
  5301. return;
  5302. }
  5303. this._activeTexturesCache[channel] = texture;
  5304. var internalTexture = texture.getInternalTexture();
  5305. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5306. if (internalTexture.isCube) {
  5307. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5308. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5309. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5310. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5311. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5312. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5313. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5314. }
  5315. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5316. }
  5317. else {
  5318. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5319. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5320. internalTexture._cachedWrapU = texture.wrapU;
  5321. switch (texture.wrapU) {
  5322. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5324. break;
  5325. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5326. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5327. break;
  5328. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5329. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5330. break;
  5331. }
  5332. }
  5333. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5334. internalTexture._cachedWrapV = texture.wrapV;
  5335. switch (texture.wrapV) {
  5336. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5337. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5338. break;
  5339. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5340. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5341. break;
  5342. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5343. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5344. break;
  5345. }
  5346. }
  5347. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5348. }
  5349. };
  5350. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5351. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5352. var value = texture.anisotropicFilteringLevel;
  5353. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5354. value = 1;
  5355. }
  5356. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5357. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5358. texture._cachedAnisotropicFilteringLevel = value;
  5359. }
  5360. };
  5361. Engine.prototype.readPixels = function (x, y, width, height) {
  5362. var data = new Uint8Array(height * width * 4);
  5363. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5364. return data;
  5365. };
  5366. // Dispose
  5367. Engine.prototype.dispose = function () {
  5368. this.hideLoadingUI();
  5369. this.stopRenderLoop();
  5370. while (this.scenes.length) {
  5371. this.scenes[0].dispose();
  5372. }
  5373. // Release audio engine
  5374. Engine.audioEngine.dispose();
  5375. for (var name in this._compiledEffects) {
  5376. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5377. }
  5378. for (var i in this._vertexAttribArrays) {
  5379. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5380. continue;
  5381. }
  5382. this._gl.disableVertexAttribArray(i);
  5383. }
  5384. // Events
  5385. window.removeEventListener("blur", this._onBlur);
  5386. window.removeEventListener("focus", this._onFocus);
  5387. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5388. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5389. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5390. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5391. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5392. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5393. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5394. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5395. };
  5396. // Loading screen
  5397. Engine.prototype.displayLoadingUI = function () {
  5398. var _this = this;
  5399. this._loadingDiv = document.createElement("div");
  5400. this._loadingDiv.style.opacity = "0";
  5401. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5402. // Loading text
  5403. this._loadingTextDiv = document.createElement("div");
  5404. this._loadingTextDiv.style.position = "absolute";
  5405. this._loadingTextDiv.style.left = "0";
  5406. this._loadingTextDiv.style.top = "50%";
  5407. this._loadingTextDiv.style.marginTop = "80px";
  5408. this._loadingTextDiv.style.width = "100%";
  5409. this._loadingTextDiv.style.height = "20px";
  5410. this._loadingTextDiv.style.fontFamily = "Arial";
  5411. this._loadingTextDiv.style.fontSize = "14px";
  5412. this._loadingTextDiv.style.color = "white";
  5413. this._loadingTextDiv.style.textAlign = "center";
  5414. this._loadingTextDiv.innerHTML = "Loading";
  5415. this._loadingDiv.appendChild(this._loadingTextDiv);
  5416. // Loading img
  5417. var imgBack = new Image();
  5418. 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==";
  5419. imgBack.style.position = "absolute";
  5420. imgBack.style.left = "50%";
  5421. imgBack.style.top = "50%";
  5422. imgBack.style.marginLeft = "-50px";
  5423. imgBack.style.marginTop = "-50px";
  5424. imgBack.style.transition = "transform 1.0s ease";
  5425. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5426. var deg = 360;
  5427. var onTransitionEnd = function () {
  5428. deg += 360;
  5429. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5430. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5431. };
  5432. imgBack.addEventListener("transitionend", onTransitionEnd);
  5433. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5434. this._loadingDiv.appendChild(imgBack);
  5435. // front image
  5436. var imgFront = new Image();
  5437. 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=";
  5438. imgFront.style.position = "absolute";
  5439. imgFront.style.left = "50%";
  5440. imgFront.style.top = "50%";
  5441. imgFront.style.marginLeft = "-50px";
  5442. imgFront.style.marginTop = "-50px";
  5443. this._loadingDiv.appendChild(imgFront);
  5444. // Resize
  5445. this._resizeLoadingUI = function () {
  5446. var canvasRect = _this.getRenderingCanvasClientRect();
  5447. _this._loadingDiv.style.position = "absolute";
  5448. _this._loadingDiv.style.left = canvasRect.left + "px";
  5449. _this._loadingDiv.style.top = canvasRect.top + "px";
  5450. _this._loadingDiv.style.width = canvasRect.width + "px";
  5451. _this._loadingDiv.style.height = canvasRect.height + "px";
  5452. };
  5453. this._resizeLoadingUI();
  5454. window.addEventListener("resize", this._resizeLoadingUI);
  5455. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5456. document.body.appendChild(this._loadingDiv);
  5457. setTimeout(function () {
  5458. _this._loadingDiv.style.opacity = "1";
  5459. imgBack.style.transform = "rotateZ(360deg)";
  5460. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5461. }, 0);
  5462. };
  5463. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5464. set: function (text) {
  5465. if (!this._loadingDiv) {
  5466. return;
  5467. }
  5468. this._loadingTextDiv.innerHTML = text;
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5474. get: function () {
  5475. return this._loadingDivBackgroundColor;
  5476. },
  5477. set: function (color) {
  5478. this._loadingDivBackgroundColor = color;
  5479. if (!this._loadingDiv) {
  5480. return;
  5481. }
  5482. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Engine.prototype.hideLoadingUI = function () {
  5488. var _this = this;
  5489. if (!this._loadingDiv) {
  5490. return;
  5491. }
  5492. var onTransitionEnd = function () {
  5493. if (!_this._loadingDiv) {
  5494. return;
  5495. }
  5496. document.body.removeChild(_this._loadingDiv);
  5497. window.removeEventListener("resize", _this._resizeLoadingUI);
  5498. _this._loadingDiv = null;
  5499. };
  5500. this._loadingDiv.style.opacity = "0";
  5501. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5502. };
  5503. // FPS
  5504. Engine.prototype.getFps = function () {
  5505. return this.fps;
  5506. };
  5507. Engine.prototype.getDeltaTime = function () {
  5508. return this.deltaTime;
  5509. };
  5510. Engine.prototype._measureFps = function () {
  5511. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5512. var length = this.previousFramesDuration.length;
  5513. if (length >= 2) {
  5514. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5515. }
  5516. if (length >= this.fpsRange) {
  5517. if (length > this.fpsRange) {
  5518. this.previousFramesDuration.splice(0, 1);
  5519. length = this.previousFramesDuration.length;
  5520. }
  5521. var sum = 0;
  5522. for (var id = 0; id < length - 1; id++) {
  5523. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5524. }
  5525. this.fps = 1000.0 / (sum / (length - 1));
  5526. }
  5527. };
  5528. // Statics
  5529. Engine.isSupported = function () {
  5530. try {
  5531. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5532. if (navigator.isCocoonJS) {
  5533. return true;
  5534. }
  5535. var tempcanvas = document.createElement("canvas");
  5536. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5537. return gl != null && !!window.WebGLRenderingContext;
  5538. }
  5539. catch (e) {
  5540. return false;
  5541. }
  5542. };
  5543. // Const statics
  5544. Engine._ALPHA_DISABLE = 0;
  5545. Engine._ALPHA_ADD = 1;
  5546. Engine._ALPHA_COMBINE = 2;
  5547. Engine._DELAYLOADSTATE_NONE = 0;
  5548. Engine._DELAYLOADSTATE_LOADED = 1;
  5549. Engine._DELAYLOADSTATE_LOADING = 2;
  5550. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5551. Engine._TEXTUREFORMAT_ALPHA = 0;
  5552. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5553. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5554. Engine._TEXTUREFORMAT_RGB = 4;
  5555. Engine._TEXTUREFORMAT_RGBA = 4;
  5556. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5557. Engine._TEXTURETYPE_FLOAT = 1;
  5558. // Updatable statics so stick with vars here
  5559. Engine.Epsilon = 0.001;
  5560. Engine.CollisionsEpsilon = 0.001;
  5561. Engine.ShadersRepository = "Babylon/Shaders/";
  5562. return Engine;
  5563. })();
  5564. BABYLON.Engine = Engine;
  5565. })(BABYLON || (BABYLON = {}));
  5566. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5567. (function (BABYLON) {
  5568. /**
  5569. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5570. */
  5571. var Node = (function () {
  5572. /**
  5573. * @constructor
  5574. * @param {string} name - the name and id to be given to this node
  5575. * @param {BABYLON.Scene} the scene this node will be added to
  5576. */
  5577. function Node(name, scene) {
  5578. this.state = "";
  5579. this.animations = new Array();
  5580. this._childrenFlag = -1;
  5581. this._isEnabled = true;
  5582. this._isReady = true;
  5583. this._currentRenderId = -1;
  5584. this._parentRenderId = -1;
  5585. this.name = name;
  5586. this.id = name;
  5587. this._scene = scene;
  5588. this._initCache();
  5589. }
  5590. Node.prototype.getScene = function () {
  5591. return this._scene;
  5592. };
  5593. Node.prototype.getEngine = function () {
  5594. return this._scene.getEngine();
  5595. };
  5596. // override it in derived class
  5597. Node.prototype.getWorldMatrix = function () {
  5598. return BABYLON.Matrix.Identity();
  5599. };
  5600. // override it in derived class if you add new variables to the cache
  5601. // and call the parent class method
  5602. Node.prototype._initCache = function () {
  5603. this._cache = {};
  5604. this._cache.parent = undefined;
  5605. };
  5606. Node.prototype.updateCache = function (force) {
  5607. if (!force && this.isSynchronized())
  5608. return;
  5609. this._cache.parent = this.parent;
  5610. this._updateCache();
  5611. };
  5612. // override it in derived class if you add new variables to the cache
  5613. // and call the parent class method if !ignoreParentClass
  5614. Node.prototype._updateCache = function (ignoreParentClass) {
  5615. };
  5616. // override it in derived class if you add new variables to the cache
  5617. Node.prototype._isSynchronized = function () {
  5618. return true;
  5619. };
  5620. Node.prototype._markSyncedWithParent = function () {
  5621. this._parentRenderId = this.parent._currentRenderId;
  5622. };
  5623. Node.prototype.isSynchronizedWithParent = function () {
  5624. if (!this.parent) {
  5625. return true;
  5626. }
  5627. if (this._parentRenderId !== this.parent._currentRenderId) {
  5628. return false;
  5629. }
  5630. return this.parent.isSynchronized();
  5631. };
  5632. Node.prototype.isSynchronized = function (updateCache) {
  5633. var check = this.hasNewParent();
  5634. check = check || !this.isSynchronizedWithParent();
  5635. check = check || !this._isSynchronized();
  5636. if (updateCache)
  5637. this.updateCache(true);
  5638. return !check;
  5639. };
  5640. Node.prototype.hasNewParent = function (update) {
  5641. if (this._cache.parent === this.parent)
  5642. return false;
  5643. if (update)
  5644. this._cache.parent = this.parent;
  5645. return true;
  5646. };
  5647. /**
  5648. * Is this node ready to be used/rendered
  5649. * @return {boolean} is it ready
  5650. */
  5651. Node.prototype.isReady = function () {
  5652. return this._isReady;
  5653. };
  5654. /**
  5655. * Is this node enabled.
  5656. * If the node has a parent and is enabled, the parent will be inspected as well.
  5657. * @return {boolean} whether this node (and its parent) is enabled.
  5658. * @see setEnabled
  5659. */
  5660. Node.prototype.isEnabled = function () {
  5661. if (!this._isEnabled) {
  5662. return false;
  5663. }
  5664. if (this.parent) {
  5665. return this.parent.isEnabled();
  5666. }
  5667. return true;
  5668. };
  5669. /**
  5670. * Set the enabled state of this node.
  5671. * @param {boolean} value - the new enabled state
  5672. * @see isEnabled
  5673. */
  5674. Node.prototype.setEnabled = function (value) {
  5675. this._isEnabled = value;
  5676. };
  5677. /**
  5678. * Is this node a descendant of the given node.
  5679. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5680. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5681. * @see parent
  5682. */
  5683. Node.prototype.isDescendantOf = function (ancestor) {
  5684. if (this.parent) {
  5685. if (this.parent === ancestor) {
  5686. return true;
  5687. }
  5688. return this.parent.isDescendantOf(ancestor);
  5689. }
  5690. return false;
  5691. };
  5692. Node.prototype._getDescendants = function (list, results) {
  5693. for (var index = 0; index < list.length; index++) {
  5694. var item = list[index];
  5695. if (item.isDescendantOf(this)) {
  5696. results.push(item);
  5697. }
  5698. }
  5699. };
  5700. /**
  5701. * Will return all nodes that have this node as parent.
  5702. * @return {BABYLON.Node[]} all children nodes of all types.
  5703. */
  5704. Node.prototype.getDescendants = function () {
  5705. var results = [];
  5706. this._getDescendants(this._scene.meshes, results);
  5707. this._getDescendants(this._scene.lights, results);
  5708. this._getDescendants(this._scene.cameras, results);
  5709. return results;
  5710. };
  5711. Node.prototype._setReady = function (state) {
  5712. if (state == this._isReady) {
  5713. return;
  5714. }
  5715. if (!state) {
  5716. this._isReady = false;
  5717. return;
  5718. }
  5719. this._isReady = true;
  5720. if (this.onReady) {
  5721. this.onReady(this);
  5722. }
  5723. };
  5724. return Node;
  5725. })();
  5726. BABYLON.Node = Node;
  5727. })(BABYLON || (BABYLON = {}));
  5728. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5729. (function (BABYLON) {
  5730. var BoundingSphere = (function () {
  5731. function BoundingSphere(minimum, maximum) {
  5732. this.minimum = minimum;
  5733. this.maximum = maximum;
  5734. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5735. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5736. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5737. this.radius = distance * 0.5;
  5738. this.centerWorld = BABYLON.Vector3.Zero();
  5739. this._update(BABYLON.Matrix.Identity());
  5740. }
  5741. // Methods
  5742. BoundingSphere.prototype._update = function (world) {
  5743. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5744. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5745. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5746. };
  5747. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5748. for (var i = 0; i < 6; i++) {
  5749. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5750. return false;
  5751. }
  5752. return true;
  5753. };
  5754. BoundingSphere.prototype.intersectsPoint = function (point) {
  5755. var x = this.centerWorld.x - point.x;
  5756. var y = this.centerWorld.y - point.y;
  5757. var z = this.centerWorld.z - point.z;
  5758. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5759. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5760. return false;
  5761. return true;
  5762. };
  5763. // Statics
  5764. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5765. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5766. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5767. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5768. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5769. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5770. return false;
  5771. return true;
  5772. };
  5773. return BoundingSphere;
  5774. })();
  5775. BABYLON.BoundingSphere = BoundingSphere;
  5776. })(BABYLON || (BABYLON = {}));
  5777. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5778. (function (BABYLON) {
  5779. var BoundingBox = (function () {
  5780. function BoundingBox(minimum, maximum) {
  5781. this.minimum = minimum;
  5782. this.maximum = maximum;
  5783. this.vectors = new Array();
  5784. this.vectorsWorld = new Array();
  5785. // Bounding vectors
  5786. this.vectors.push(this.minimum.clone());
  5787. this.vectors.push(this.maximum.clone());
  5788. this.vectors.push(this.minimum.clone());
  5789. this.vectors[2].x = this.maximum.x;
  5790. this.vectors.push(this.minimum.clone());
  5791. this.vectors[3].y = this.maximum.y;
  5792. this.vectors.push(this.minimum.clone());
  5793. this.vectors[4].z = this.maximum.z;
  5794. this.vectors.push(this.maximum.clone());
  5795. this.vectors[5].z = this.minimum.z;
  5796. this.vectors.push(this.maximum.clone());
  5797. this.vectors[6].x = this.minimum.x;
  5798. this.vectors.push(this.maximum.clone());
  5799. this.vectors[7].y = this.minimum.y;
  5800. // OBB
  5801. this.center = this.maximum.add(this.minimum).scale(0.5);
  5802. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5803. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5804. for (var index = 0; index < this.vectors.length; index++) {
  5805. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5806. }
  5807. this.minimumWorld = BABYLON.Vector3.Zero();
  5808. this.maximumWorld = BABYLON.Vector3.Zero();
  5809. this._update(BABYLON.Matrix.Identity());
  5810. }
  5811. // Methods
  5812. BoundingBox.prototype.getWorldMatrix = function () {
  5813. return this._worldMatrix;
  5814. };
  5815. BoundingBox.prototype._update = function (world) {
  5816. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5817. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5818. for (var index = 0; index < this.vectors.length; index++) {
  5819. var v = this.vectorsWorld[index];
  5820. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5821. if (v.x < this.minimumWorld.x)
  5822. this.minimumWorld.x = v.x;
  5823. if (v.y < this.minimumWorld.y)
  5824. this.minimumWorld.y = v.y;
  5825. if (v.z < this.minimumWorld.z)
  5826. this.minimumWorld.z = v.z;
  5827. if (v.x > this.maximumWorld.x)
  5828. this.maximumWorld.x = v.x;
  5829. if (v.y > this.maximumWorld.y)
  5830. this.maximumWorld.y = v.y;
  5831. if (v.z > this.maximumWorld.z)
  5832. this.maximumWorld.z = v.z;
  5833. }
  5834. // OBB
  5835. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5836. this.center.scaleInPlace(0.5);
  5837. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5838. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5839. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5840. this._worldMatrix = world;
  5841. };
  5842. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5843. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5844. };
  5845. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5846. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5847. };
  5848. BoundingBox.prototype.intersectsPoint = function (point) {
  5849. var delta = BABYLON.Engine.Epsilon;
  5850. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5851. return false;
  5852. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5853. return false;
  5854. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5855. return false;
  5856. return true;
  5857. };
  5858. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5859. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5860. };
  5861. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5862. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5863. return false;
  5864. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5865. return false;
  5866. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5867. return false;
  5868. return true;
  5869. };
  5870. // Statics
  5871. BoundingBox.Intersects = function (box0, box1) {
  5872. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5873. return false;
  5874. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5875. return false;
  5876. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5877. return false;
  5878. return true;
  5879. };
  5880. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5881. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5882. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5883. return (num <= (sphereRadius * sphereRadius));
  5884. };
  5885. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5886. for (var p = 0; p < 6; p++) {
  5887. for (var i = 0; i < 8; i++) {
  5888. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5889. return false;
  5890. }
  5891. }
  5892. }
  5893. return true;
  5894. };
  5895. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5896. for (var p = 0; p < 6; p++) {
  5897. var inCount = 8;
  5898. for (var i = 0; i < 8; i++) {
  5899. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5900. --inCount;
  5901. }
  5902. else {
  5903. break;
  5904. }
  5905. }
  5906. if (inCount === 0)
  5907. return false;
  5908. }
  5909. return true;
  5910. };
  5911. return BoundingBox;
  5912. })();
  5913. BABYLON.BoundingBox = BoundingBox;
  5914. })(BABYLON || (BABYLON = {}));
  5915. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5916. (function (BABYLON) {
  5917. var computeBoxExtents = function (axis, box) {
  5918. var p = BABYLON.Vector3.Dot(box.center, axis);
  5919. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5920. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5921. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5922. var r = r0 + r1 + r2;
  5923. return {
  5924. min: p - r,
  5925. max: p + r
  5926. };
  5927. };
  5928. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5929. var axisOverlap = function (axis, box0, box1) {
  5930. var result0 = computeBoxExtents(axis, box0);
  5931. var result1 = computeBoxExtents(axis, box1);
  5932. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5933. };
  5934. var BoundingInfo = (function () {
  5935. function BoundingInfo(minimum, maximum) {
  5936. this.minimum = minimum;
  5937. this.maximum = maximum;
  5938. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5939. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5940. }
  5941. // Methods
  5942. BoundingInfo.prototype._update = function (world) {
  5943. this.boundingBox._update(world);
  5944. this.boundingSphere._update(world);
  5945. };
  5946. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5947. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5948. return false;
  5949. return this.boundingBox.isInFrustum(frustumPlanes);
  5950. };
  5951. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5952. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5953. };
  5954. BoundingInfo.prototype._checkCollision = function (collider) {
  5955. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5956. };
  5957. BoundingInfo.prototype.intersectsPoint = function (point) {
  5958. if (!this.boundingSphere.centerWorld) {
  5959. return false;
  5960. }
  5961. if (!this.boundingSphere.intersectsPoint(point)) {
  5962. return false;
  5963. }
  5964. if (!this.boundingBox.intersectsPoint(point)) {
  5965. return false;
  5966. }
  5967. return true;
  5968. };
  5969. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5970. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5971. return false;
  5972. }
  5973. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5974. return false;
  5975. }
  5976. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5977. return false;
  5978. }
  5979. if (!precise) {
  5980. return true;
  5981. }
  5982. var box0 = this.boundingBox;
  5983. var box1 = boundingInfo.boundingBox;
  5984. if (!axisOverlap(box0.directions[0], box0, box1))
  5985. return false;
  5986. if (!axisOverlap(box0.directions[1], box0, box1))
  5987. return false;
  5988. if (!axisOverlap(box0.directions[2], box0, box1))
  5989. return false;
  5990. if (!axisOverlap(box1.directions[0], box0, box1))
  5991. return false;
  5992. if (!axisOverlap(box1.directions[1], box0, box1))
  5993. return false;
  5994. if (!axisOverlap(box1.directions[2], box0, box1))
  5995. return false;
  5996. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5997. return false;
  5998. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5999. return false;
  6000. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  6001. return false;
  6002. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  6003. return false;
  6004. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  6005. return false;
  6006. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  6007. return false;
  6008. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  6009. return false;
  6010. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  6011. return false;
  6012. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  6013. return false;
  6014. return true;
  6015. };
  6016. return BoundingInfo;
  6017. })();
  6018. BABYLON.BoundingInfo = BoundingInfo;
  6019. })(BABYLON || (BABYLON = {}));
  6020. //# sourceMappingURL=babylon.boundingInfo.js.map
  6021. var BABYLON;
  6022. (function (BABYLON) {
  6023. var Light = (function (_super) {
  6024. __extends(Light, _super);
  6025. function Light(name, scene) {
  6026. _super.call(this, name, scene);
  6027. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  6028. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  6029. this.intensity = 1.0;
  6030. this.range = Number.MAX_VALUE;
  6031. this.includeOnlyWithLayerMask = 0;
  6032. this.includedOnlyMeshes = new Array();
  6033. this.excludedMeshes = new Array();
  6034. this.excludeWithLayerMask = 0;
  6035. this._excludedMeshesIds = new Array();
  6036. this._includedOnlyMeshesIds = new Array();
  6037. scene.addLight(this);
  6038. }
  6039. Light.prototype.getShadowGenerator = function () {
  6040. return this._shadowGenerator;
  6041. };
  6042. Light.prototype.getAbsolutePosition = function () {
  6043. return BABYLON.Vector3.Zero();
  6044. };
  6045. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6046. };
  6047. Light.prototype._getWorldMatrix = function () {
  6048. return BABYLON.Matrix.Identity();
  6049. };
  6050. Light.prototype.canAffectMesh = function (mesh) {
  6051. if (!mesh) {
  6052. return true;
  6053. }
  6054. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6055. return false;
  6056. }
  6057. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6058. return false;
  6059. }
  6060. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  6061. return false;
  6062. }
  6063. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  6064. return false;
  6065. }
  6066. return true;
  6067. };
  6068. Light.prototype.getWorldMatrix = function () {
  6069. this._currentRenderId = this.getScene().getRenderId();
  6070. var worldMatrix = this._getWorldMatrix();
  6071. if (this.parent && this.parent.getWorldMatrix) {
  6072. if (!this._parentedWorldMatrix) {
  6073. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6074. }
  6075. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6076. this._markSyncedWithParent();
  6077. return this._parentedWorldMatrix;
  6078. }
  6079. return worldMatrix;
  6080. };
  6081. Light.prototype.dispose = function () {
  6082. if (this._shadowGenerator) {
  6083. this._shadowGenerator.dispose();
  6084. this._shadowGenerator = null;
  6085. }
  6086. // Remove from scene
  6087. this.getScene().removeLight(this);
  6088. };
  6089. return Light;
  6090. })(BABYLON.Node);
  6091. BABYLON.Light = Light;
  6092. })(BABYLON || (BABYLON = {}));
  6093. //# sourceMappingURL=babylon.light.js.map
  6094. var BABYLON;
  6095. (function (BABYLON) {
  6096. var PointLight = (function (_super) {
  6097. __extends(PointLight, _super);
  6098. function PointLight(name, position, scene) {
  6099. _super.call(this, name, scene);
  6100. this.position = position;
  6101. }
  6102. PointLight.prototype.getAbsolutePosition = function () {
  6103. return this._transformedPosition ? this._transformedPosition : this.position;
  6104. };
  6105. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6106. if (this.parent && this.parent.getWorldMatrix) {
  6107. if (!this._transformedPosition) {
  6108. this._transformedPosition = BABYLON.Vector3.Zero();
  6109. }
  6110. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6111. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6112. return;
  6113. }
  6114. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6115. };
  6116. PointLight.prototype.getShadowGenerator = function () {
  6117. return null;
  6118. };
  6119. PointLight.prototype._getWorldMatrix = function () {
  6120. if (!this._worldMatrix) {
  6121. this._worldMatrix = BABYLON.Matrix.Identity();
  6122. }
  6123. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6124. return this._worldMatrix;
  6125. };
  6126. return PointLight;
  6127. })(BABYLON.Light);
  6128. BABYLON.PointLight = PointLight;
  6129. })(BABYLON || (BABYLON = {}));
  6130. //# sourceMappingURL=babylon.pointLight.js.map
  6131. var BABYLON;
  6132. (function (BABYLON) {
  6133. var SpotLight = (function (_super) {
  6134. __extends(SpotLight, _super);
  6135. function SpotLight(name, position, direction, angle, exponent, scene) {
  6136. _super.call(this, name, scene);
  6137. this.position = position;
  6138. this.direction = direction;
  6139. this.angle = angle;
  6140. this.exponent = exponent;
  6141. }
  6142. SpotLight.prototype.getAbsolutePosition = function () {
  6143. return this.transformedPosition ? this.transformedPosition : this.position;
  6144. };
  6145. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6146. var activeCamera = this.getScene().activeCamera;
  6147. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6148. };
  6149. SpotLight.prototype.supportsVSM = function () {
  6150. return true;
  6151. };
  6152. SpotLight.prototype.needRefreshPerFrame = function () {
  6153. return false;
  6154. };
  6155. SpotLight.prototype.setDirectionToTarget = function (target) {
  6156. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6157. return this.direction;
  6158. };
  6159. SpotLight.prototype.computeTransformedPosition = function () {
  6160. if (this.parent && this.parent.getWorldMatrix) {
  6161. if (!this.transformedPosition) {
  6162. this.transformedPosition = BABYLON.Vector3.Zero();
  6163. }
  6164. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6165. return true;
  6166. }
  6167. return false;
  6168. };
  6169. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6170. var normalizeDirection;
  6171. if (this.parent && this.parent.getWorldMatrix) {
  6172. if (!this._transformedDirection) {
  6173. this._transformedDirection = BABYLON.Vector3.Zero();
  6174. }
  6175. this.computeTransformedPosition();
  6176. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6177. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6178. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6179. }
  6180. else {
  6181. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6182. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6183. }
  6184. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6185. };
  6186. SpotLight.prototype._getWorldMatrix = function () {
  6187. if (!this._worldMatrix) {
  6188. this._worldMatrix = BABYLON.Matrix.Identity();
  6189. }
  6190. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6191. return this._worldMatrix;
  6192. };
  6193. return SpotLight;
  6194. })(BABYLON.Light);
  6195. BABYLON.SpotLight = SpotLight;
  6196. })(BABYLON || (BABYLON = {}));
  6197. //# sourceMappingURL=babylon.spotLight.js.map
  6198. var BABYLON;
  6199. (function (BABYLON) {
  6200. var DirectionalLight = (function (_super) {
  6201. __extends(DirectionalLight, _super);
  6202. function DirectionalLight(name, direction, scene) {
  6203. _super.call(this, name, scene);
  6204. this.direction = direction;
  6205. this.shadowOrthoScale = 0.5;
  6206. this.position = direction.scale(-1);
  6207. }
  6208. DirectionalLight.prototype.getAbsolutePosition = function () {
  6209. return this.transformedPosition ? this.transformedPosition : this.position;
  6210. };
  6211. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6212. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6213. return this.direction;
  6214. };
  6215. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6216. var orthoLeft = Number.MAX_VALUE;
  6217. var orthoRight = Number.MIN_VALUE;
  6218. var orthoTop = Number.MIN_VALUE;
  6219. var orthoBottom = Number.MAX_VALUE;
  6220. var tempVector3 = BABYLON.Vector3.Zero();
  6221. var activeCamera = this.getScene().activeCamera;
  6222. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6223. var mesh = renderList[meshIndex];
  6224. if (!mesh) {
  6225. continue;
  6226. }
  6227. var boundingInfo = mesh.getBoundingInfo();
  6228. if (!boundingInfo) {
  6229. continue;
  6230. }
  6231. var boundingBox = boundingInfo.boundingBox;
  6232. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6233. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6234. if (tempVector3.x < orthoLeft)
  6235. orthoLeft = tempVector3.x;
  6236. if (tempVector3.y < orthoBottom)
  6237. orthoBottom = tempVector3.y;
  6238. if (tempVector3.x > orthoRight)
  6239. orthoRight = tempVector3.x;
  6240. if (tempVector3.y > orthoTop)
  6241. orthoTop = tempVector3.y;
  6242. }
  6243. }
  6244. var xOffset = orthoRight - orthoLeft;
  6245. var yOffset = orthoTop - orthoBottom;
  6246. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6247. };
  6248. DirectionalLight.prototype.supportsVSM = function () {
  6249. return true;
  6250. };
  6251. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6252. return true;
  6253. };
  6254. DirectionalLight.prototype.computeTransformedPosition = function () {
  6255. if (this.parent && this.parent.getWorldMatrix) {
  6256. if (!this.transformedPosition) {
  6257. this.transformedPosition = BABYLON.Vector3.Zero();
  6258. }
  6259. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6260. return true;
  6261. }
  6262. return false;
  6263. };
  6264. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6265. if (this.parent && this.parent.getWorldMatrix) {
  6266. if (!this._transformedDirection) {
  6267. this._transformedDirection = BABYLON.Vector3.Zero();
  6268. }
  6269. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6270. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6271. return;
  6272. }
  6273. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6274. };
  6275. DirectionalLight.prototype._getWorldMatrix = function () {
  6276. if (!this._worldMatrix) {
  6277. this._worldMatrix = BABYLON.Matrix.Identity();
  6278. }
  6279. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6280. return this._worldMatrix;
  6281. };
  6282. return DirectionalLight;
  6283. })(BABYLON.Light);
  6284. BABYLON.DirectionalLight = DirectionalLight;
  6285. })(BABYLON || (BABYLON = {}));
  6286. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6287. (function (BABYLON) {
  6288. var ShadowGenerator = (function () {
  6289. function ShadowGenerator(mapSize, light) {
  6290. var _this = this;
  6291. // Members
  6292. this._filter = ShadowGenerator.FILTER_NONE;
  6293. this.blurScale = 2;
  6294. this._blurBoxOffset = 0;
  6295. this._bias = 0.00005;
  6296. this._darkness = 0;
  6297. this._transparencyShadow = false;
  6298. this._viewMatrix = BABYLON.Matrix.Zero();
  6299. this._projectionMatrix = BABYLON.Matrix.Zero();
  6300. this._transformMatrix = BABYLON.Matrix.Zero();
  6301. this._worldViewProjection = BABYLON.Matrix.Zero();
  6302. this._light = light;
  6303. this._scene = light.getScene();
  6304. this._mapSize = mapSize;
  6305. light._shadowGenerator = this;
  6306. // Render target
  6307. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6308. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6309. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6310. this._shadowMap.anisotropicFilteringLevel = 1;
  6311. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6312. this._shadowMap.renderParticles = false;
  6313. this._shadowMap.onAfterUnbind = function () {
  6314. if (!_this.useBlurVarianceShadowMap) {
  6315. return;
  6316. }
  6317. if (!_this._shadowMap2) {
  6318. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6319. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6320. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6321. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6322. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6323. _this._downSamplePostprocess.onApply = function (effect) {
  6324. effect.setTexture("textureSampler", _this._shadowMap);
  6325. };
  6326. _this.blurBoxOffset = 1;
  6327. }
  6328. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6329. };
  6330. // Custom render function
  6331. var renderSubMesh = function (subMesh) {
  6332. var mesh = subMesh.getRenderingMesh();
  6333. var scene = _this._scene;
  6334. var engine = scene.getEngine();
  6335. // Culling
  6336. engine.setState(subMesh.getMaterial().backFaceCulling);
  6337. // Managing instances
  6338. var batch = mesh._getInstancesRenderList(subMesh._id);
  6339. if (batch.mustReturn) {
  6340. return;
  6341. }
  6342. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6343. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6344. engine.enableEffect(_this._effect);
  6345. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6346. var material = subMesh.getMaterial();
  6347. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6348. // Alpha test
  6349. if (material && material.needAlphaTesting()) {
  6350. var alphaTexture = material.getAlphaTestTexture();
  6351. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6352. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6353. }
  6354. // Bones
  6355. if (mesh.useBones) {
  6356. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6357. }
  6358. // Draw
  6359. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6360. }
  6361. else {
  6362. // Need to reset refresh rate of the shadowMap
  6363. _this._shadowMap.resetRefreshCounter();
  6364. }
  6365. };
  6366. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6367. var index;
  6368. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6369. renderSubMesh(opaqueSubMeshes.data[index]);
  6370. }
  6371. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6372. renderSubMesh(alphaTestSubMeshes.data[index]);
  6373. }
  6374. if (_this._transparencyShadow) {
  6375. for (index = 0; index < transparentSubMeshes.length; index++) {
  6376. renderSubMesh(transparentSubMeshes.data[index]);
  6377. }
  6378. }
  6379. };
  6380. this._shadowMap.onClear = function (engine) {
  6381. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6382. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6383. }
  6384. else {
  6385. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6386. }
  6387. };
  6388. }
  6389. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6390. // Static
  6391. get: function () {
  6392. return ShadowGenerator._FILTER_NONE;
  6393. },
  6394. enumerable: true,
  6395. configurable: true
  6396. });
  6397. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6398. get: function () {
  6399. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6400. },
  6401. enumerable: true,
  6402. configurable: true
  6403. });
  6404. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6405. get: function () {
  6406. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6407. },
  6408. enumerable: true,
  6409. configurable: true
  6410. });
  6411. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6412. get: function () {
  6413. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6414. },
  6415. enumerable: true,
  6416. configurable: true
  6417. });
  6418. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6419. get: function () {
  6420. return this._bias;
  6421. },
  6422. set: function (bias) {
  6423. this._bias = bias;
  6424. },
  6425. enumerable: true,
  6426. configurable: true
  6427. });
  6428. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6429. get: function () {
  6430. return this._blurBoxOffset;
  6431. },
  6432. set: function (value) {
  6433. var _this = this;
  6434. if (this._blurBoxOffset === value) {
  6435. return;
  6436. }
  6437. this._blurBoxOffset = value;
  6438. if (this._boxBlurPostprocess) {
  6439. this._boxBlurPostprocess.dispose();
  6440. }
  6441. 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);
  6442. this._boxBlurPostprocess.onApply = function (effect) {
  6443. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6444. };
  6445. },
  6446. enumerable: true,
  6447. configurable: true
  6448. });
  6449. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6450. get: function () {
  6451. return this._filter;
  6452. },
  6453. set: function (value) {
  6454. if (this._filter === value) {
  6455. return;
  6456. }
  6457. this._filter = value;
  6458. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6459. this._shadowMap.anisotropicFilteringLevel = 16;
  6460. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6461. }
  6462. else {
  6463. this._shadowMap.anisotropicFilteringLevel = 1;
  6464. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6465. }
  6466. },
  6467. enumerable: true,
  6468. configurable: true
  6469. });
  6470. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6471. get: function () {
  6472. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6473. },
  6474. set: function (value) {
  6475. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6476. },
  6477. enumerable: true,
  6478. configurable: true
  6479. });
  6480. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6481. get: function () {
  6482. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6483. },
  6484. set: function (value) {
  6485. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6486. },
  6487. enumerable: true,
  6488. configurable: true
  6489. });
  6490. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6491. get: function () {
  6492. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6493. },
  6494. set: function (value) {
  6495. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6496. },
  6497. enumerable: true,
  6498. configurable: true
  6499. });
  6500. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6501. var defines = [];
  6502. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6503. defines.push("#define VSM");
  6504. }
  6505. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6506. var mesh = subMesh.getMesh();
  6507. var material = subMesh.getMaterial();
  6508. // Alpha test
  6509. if (material && material.needAlphaTesting()) {
  6510. defines.push("#define ALPHATEST");
  6511. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6512. attribs.push(BABYLON.VertexBuffer.UVKind);
  6513. defines.push("#define UV1");
  6514. }
  6515. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6516. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6517. defines.push("#define UV2");
  6518. }
  6519. }
  6520. // Bones
  6521. if (mesh.useBones) {
  6522. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6523. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6524. defines.push("#define BONES");
  6525. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6526. }
  6527. // Instances
  6528. if (useInstances) {
  6529. defines.push("#define INSTANCES");
  6530. attribs.push("world0");
  6531. attribs.push("world1");
  6532. attribs.push("world2");
  6533. attribs.push("world3");
  6534. }
  6535. // Get correct effect
  6536. var join = defines.join("\n");
  6537. if (this._cachedDefines !== join) {
  6538. this._cachedDefines = join;
  6539. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6540. }
  6541. return this._effect.isReady();
  6542. };
  6543. ShadowGenerator.prototype.getShadowMap = function () {
  6544. return this._shadowMap;
  6545. };
  6546. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6547. if (this._shadowMap2) {
  6548. return this._shadowMap2;
  6549. }
  6550. return this._shadowMap;
  6551. };
  6552. ShadowGenerator.prototype.getLight = function () {
  6553. return this._light;
  6554. };
  6555. // Methods
  6556. ShadowGenerator.prototype.getTransformMatrix = function () {
  6557. var scene = this._scene;
  6558. if (this._currentRenderID === scene.getRenderId()) {
  6559. return this._transformMatrix;
  6560. }
  6561. this._currentRenderID = scene.getRenderId();
  6562. var lightPosition = this._light.position;
  6563. var lightDirection = this._light.direction;
  6564. if (this._light.computeTransformedPosition()) {
  6565. lightPosition = this._light.transformedPosition;
  6566. }
  6567. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6568. this._cachedPosition = lightPosition.clone();
  6569. this._cachedDirection = lightDirection.clone();
  6570. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6571. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6572. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6573. }
  6574. return this._transformMatrix;
  6575. };
  6576. ShadowGenerator.prototype.getDarkness = function () {
  6577. return this._darkness;
  6578. };
  6579. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6580. if (darkness >= 1.0)
  6581. this._darkness = 1.0;
  6582. else if (darkness <= 0.0)
  6583. this._darkness = 0.0;
  6584. else
  6585. this._darkness = darkness;
  6586. };
  6587. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6588. this._transparencyShadow = hasShadow;
  6589. };
  6590. ShadowGenerator.prototype._packHalf = function (depth) {
  6591. var scale = depth * 255.0;
  6592. var fract = scale - Math.floor(scale);
  6593. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6594. };
  6595. ShadowGenerator.prototype.dispose = function () {
  6596. this._shadowMap.dispose();
  6597. if (this._shadowMap2) {
  6598. this._shadowMap2.dispose();
  6599. }
  6600. if (this._downSamplePostprocess) {
  6601. this._downSamplePostprocess.dispose();
  6602. }
  6603. if (this._boxBlurPostprocess) {
  6604. this._boxBlurPostprocess.dispose();
  6605. }
  6606. };
  6607. ShadowGenerator._FILTER_NONE = 0;
  6608. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6609. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6610. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6611. return ShadowGenerator;
  6612. })();
  6613. BABYLON.ShadowGenerator = ShadowGenerator;
  6614. })(BABYLON || (BABYLON = {}));
  6615. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6616. var BABYLON;
  6617. (function (BABYLON) {
  6618. var HemisphericLight = (function (_super) {
  6619. __extends(HemisphericLight, _super);
  6620. function HemisphericLight(name, direction, scene) {
  6621. _super.call(this, name, scene);
  6622. this.direction = direction;
  6623. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6624. }
  6625. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6626. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6627. return this.direction;
  6628. };
  6629. HemisphericLight.prototype.getShadowGenerator = function () {
  6630. return null;
  6631. };
  6632. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6633. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6634. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6635. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6636. };
  6637. HemisphericLight.prototype._getWorldMatrix = function () {
  6638. if (!this._worldMatrix) {
  6639. this._worldMatrix = BABYLON.Matrix.Identity();
  6640. }
  6641. return this._worldMatrix;
  6642. };
  6643. return HemisphericLight;
  6644. })(BABYLON.Light);
  6645. BABYLON.HemisphericLight = HemisphericLight;
  6646. })(BABYLON || (BABYLON = {}));
  6647. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6648. (function (BABYLON) {
  6649. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6650. if (boxMin.x > sphereCenter.x + sphereRadius)
  6651. return false;
  6652. if (sphereCenter.x - sphereRadius > boxMax.x)
  6653. return false;
  6654. if (boxMin.y > sphereCenter.y + sphereRadius)
  6655. return false;
  6656. if (sphereCenter.y - sphereRadius > boxMax.y)
  6657. return false;
  6658. if (boxMin.z > sphereCenter.z + sphereRadius)
  6659. return false;
  6660. if (sphereCenter.z - sphereRadius > boxMax.z)
  6661. return false;
  6662. return true;
  6663. };
  6664. var getLowestRoot = function (a, b, c, maxR) {
  6665. var determinant = b * b - 4.0 * a * c;
  6666. var result = { root: 0, found: false };
  6667. if (determinant < 0)
  6668. return result;
  6669. var sqrtD = Math.sqrt(determinant);
  6670. var r1 = (-b - sqrtD) / (2.0 * a);
  6671. var r2 = (-b + sqrtD) / (2.0 * a);
  6672. if (r1 > r2) {
  6673. var temp = r2;
  6674. r2 = r1;
  6675. r1 = temp;
  6676. }
  6677. if (r1 > 0 && r1 < maxR) {
  6678. result.root = r1;
  6679. result.found = true;
  6680. return result;
  6681. }
  6682. if (r2 > 0 && r2 < maxR) {
  6683. result.root = r2;
  6684. result.found = true;
  6685. return result;
  6686. }
  6687. return result;
  6688. };
  6689. var Collider = (function () {
  6690. function Collider() {
  6691. this.radius = new BABYLON.Vector3(1, 1, 1);
  6692. this.retry = 0;
  6693. this.basePointWorld = BABYLON.Vector3.Zero();
  6694. this.velocityWorld = BABYLON.Vector3.Zero();
  6695. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6696. this._collisionPoint = BABYLON.Vector3.Zero();
  6697. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6698. this._tempVector = BABYLON.Vector3.Zero();
  6699. this._tempVector2 = BABYLON.Vector3.Zero();
  6700. this._tempVector3 = BABYLON.Vector3.Zero();
  6701. this._tempVector4 = BABYLON.Vector3.Zero();
  6702. this._edge = BABYLON.Vector3.Zero();
  6703. this._baseToVertex = BABYLON.Vector3.Zero();
  6704. this._destinationPoint = BABYLON.Vector3.Zero();
  6705. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6706. this._displacementVector = BABYLON.Vector3.Zero();
  6707. }
  6708. // Methods
  6709. Collider.prototype._initialize = function (source, dir, e) {
  6710. this.velocity = dir;
  6711. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6712. this.basePoint = source;
  6713. source.multiplyToRef(this.radius, this.basePointWorld);
  6714. dir.multiplyToRef(this.radius, this.velocityWorld);
  6715. this.velocityWorldLength = this.velocityWorld.length();
  6716. this.epsilon = e;
  6717. this.collisionFound = false;
  6718. };
  6719. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6720. pa.subtractToRef(point, this._tempVector);
  6721. pb.subtractToRef(point, this._tempVector2);
  6722. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6723. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6724. if (d < 0)
  6725. return false;
  6726. pc.subtractToRef(point, this._tempVector3);
  6727. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6728. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6729. if (d < 0)
  6730. return false;
  6731. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6732. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6733. return d >= 0;
  6734. };
  6735. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6736. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6737. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6738. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6739. return false;
  6740. }
  6741. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6742. return false;
  6743. return true;
  6744. };
  6745. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6746. var t0;
  6747. var embeddedInPlane = false;
  6748. if (!subMesh._trianglePlanes) {
  6749. subMesh._trianglePlanes = [];
  6750. }
  6751. if (!subMesh._trianglePlanes[faceIndex]) {
  6752. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6753. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6754. }
  6755. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6756. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6757. return;
  6758. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6759. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6760. if (normalDotVelocity == 0) {
  6761. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6762. return;
  6763. embeddedInPlane = true;
  6764. t0 = 0;
  6765. }
  6766. else {
  6767. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6768. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6769. if (t0 > t1) {
  6770. var temp = t1;
  6771. t1 = t0;
  6772. t0 = temp;
  6773. }
  6774. if (t0 > 1.0 || t1 < 0.0)
  6775. return;
  6776. if (t0 < 0)
  6777. t0 = 0;
  6778. if (t0 > 1.0)
  6779. t0 = 1.0;
  6780. }
  6781. this._collisionPoint.copyFromFloats(0, 0, 0);
  6782. var found = false;
  6783. var t = 1.0;
  6784. if (!embeddedInPlane) {
  6785. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6786. this.velocity.scaleToRef(t0, this._tempVector);
  6787. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6788. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6789. found = true;
  6790. t = t0;
  6791. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6792. }
  6793. }
  6794. if (!found) {
  6795. var velocitySquaredLength = this.velocity.lengthSquared();
  6796. var a = velocitySquaredLength;
  6797. this.basePoint.subtractToRef(p1, this._tempVector);
  6798. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6799. var c = this._tempVector.lengthSquared() - 1.0;
  6800. var lowestRoot = getLowestRoot(a, b, c, t);
  6801. if (lowestRoot.found) {
  6802. t = lowestRoot.root;
  6803. found = true;
  6804. this._collisionPoint.copyFrom(p1);
  6805. }
  6806. this.basePoint.subtractToRef(p2, this._tempVector);
  6807. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6808. c = this._tempVector.lengthSquared() - 1.0;
  6809. lowestRoot = getLowestRoot(a, b, c, t);
  6810. if (lowestRoot.found) {
  6811. t = lowestRoot.root;
  6812. found = true;
  6813. this._collisionPoint.copyFrom(p2);
  6814. }
  6815. this.basePoint.subtractToRef(p3, this._tempVector);
  6816. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6817. c = this._tempVector.lengthSquared() - 1.0;
  6818. lowestRoot = getLowestRoot(a, b, c, t);
  6819. if (lowestRoot.found) {
  6820. t = lowestRoot.root;
  6821. found = true;
  6822. this._collisionPoint.copyFrom(p3);
  6823. }
  6824. p2.subtractToRef(p1, this._edge);
  6825. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6826. var edgeSquaredLength = this._edge.lengthSquared();
  6827. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6828. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6829. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6830. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6831. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6832. lowestRoot = getLowestRoot(a, b, c, t);
  6833. if (lowestRoot.found) {
  6834. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6835. if (f >= 0.0 && f <= 1.0) {
  6836. t = lowestRoot.root;
  6837. found = true;
  6838. this._edge.scaleInPlace(f);
  6839. p1.addToRef(this._edge, this._collisionPoint);
  6840. }
  6841. }
  6842. p3.subtractToRef(p2, this._edge);
  6843. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6844. edgeSquaredLength = this._edge.lengthSquared();
  6845. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6846. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6847. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6848. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6849. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6850. lowestRoot = getLowestRoot(a, b, c, t);
  6851. if (lowestRoot.found) {
  6852. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6853. if (f >= 0.0 && f <= 1.0) {
  6854. t = lowestRoot.root;
  6855. found = true;
  6856. this._edge.scaleInPlace(f);
  6857. p2.addToRef(this._edge, this._collisionPoint);
  6858. }
  6859. }
  6860. p1.subtractToRef(p3, this._edge);
  6861. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6862. edgeSquaredLength = this._edge.lengthSquared();
  6863. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6864. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6865. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6866. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6867. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6868. lowestRoot = getLowestRoot(a, b, c, t);
  6869. if (lowestRoot.found) {
  6870. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6871. if (f >= 0.0 && f <= 1.0) {
  6872. t = lowestRoot.root;
  6873. found = true;
  6874. this._edge.scaleInPlace(f);
  6875. p3.addToRef(this._edge, this._collisionPoint);
  6876. }
  6877. }
  6878. }
  6879. if (found) {
  6880. var distToCollision = t * this.velocity.length();
  6881. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6882. if (!this.intersectionPoint) {
  6883. this.intersectionPoint = this._collisionPoint.clone();
  6884. }
  6885. else {
  6886. this.intersectionPoint.copyFrom(this._collisionPoint);
  6887. }
  6888. this.nearestDistance = distToCollision;
  6889. this.collisionFound = true;
  6890. this.collidedMesh = subMesh.getMesh();
  6891. }
  6892. }
  6893. };
  6894. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6895. for (var i = indexStart; i < indexEnd; i += 3) {
  6896. var p1 = pts[indices[i] - decal];
  6897. var p2 = pts[indices[i + 1] - decal];
  6898. var p3 = pts[indices[i + 2] - decal];
  6899. this._testTriangle(i, subMesh, p3, p2, p1);
  6900. }
  6901. };
  6902. Collider.prototype._getResponse = function (pos, vel) {
  6903. pos.addToRef(vel, this._destinationPoint);
  6904. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6905. this.basePoint.addToRef(vel, pos);
  6906. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6907. this._slidePlaneNormal.normalize();
  6908. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6909. pos.addInPlace(this._displacementVector);
  6910. this.intersectionPoint.addInPlace(this._displacementVector);
  6911. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6912. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6913. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6914. };
  6915. return Collider;
  6916. })();
  6917. BABYLON.Collider = Collider;
  6918. })(BABYLON || (BABYLON = {}));
  6919. //# sourceMappingURL=babylon.collider.js.map
  6920. var BABYLON;
  6921. (function (BABYLON) {
  6922. var Camera = (function (_super) {
  6923. __extends(Camera, _super);
  6924. function Camera(name, position, scene) {
  6925. _super.call(this, name, scene);
  6926. this.position = position;
  6927. // Members
  6928. this.upVector = BABYLON.Vector3.Up();
  6929. this.orthoLeft = null;
  6930. this.orthoRight = null;
  6931. this.orthoBottom = null;
  6932. this.orthoTop = null;
  6933. this.fov = 0.8;
  6934. this.minZ = 1.0;
  6935. this.maxZ = 10000.0;
  6936. this.inertia = 0.9;
  6937. this.mode = Camera.PERSPECTIVE_CAMERA;
  6938. this.isIntermediate = false;
  6939. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6940. this.subCameras = [];
  6941. this.layerMask = 0xFFFFFFFF;
  6942. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6943. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6944. this._projectionMatrix = new BABYLON.Matrix();
  6945. this._postProcesses = new Array();
  6946. this._postProcessesTakenIndices = [];
  6947. this._activeMeshes = new BABYLON.SmartArray(256);
  6948. this._globalPosition = BABYLON.Vector3.Zero();
  6949. scene.addCamera(this);
  6950. if (!scene.activeCamera) {
  6951. scene.activeCamera = this;
  6952. }
  6953. }
  6954. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6955. get: function () {
  6956. return Camera._PERSPECTIVE_CAMERA;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6962. get: function () {
  6963. return Camera._ORTHOGRAPHIC_CAMERA;
  6964. },
  6965. enumerable: true,
  6966. configurable: true
  6967. });
  6968. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6969. get: function () {
  6970. return Camera._FOVMODE_VERTICAL_FIXED;
  6971. },
  6972. enumerable: true,
  6973. configurable: true
  6974. });
  6975. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6976. get: function () {
  6977. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6978. },
  6979. enumerable: true,
  6980. configurable: true
  6981. });
  6982. Object.defineProperty(Camera.prototype, "globalPosition", {
  6983. get: function () {
  6984. return this._globalPosition;
  6985. },
  6986. enumerable: true,
  6987. configurable: true
  6988. });
  6989. Camera.prototype.getActiveMeshes = function () {
  6990. return this._activeMeshes;
  6991. };
  6992. Camera.prototype.isActiveMesh = function (mesh) {
  6993. return (this._activeMeshes.indexOf(mesh) !== -1);
  6994. };
  6995. //Cache
  6996. Camera.prototype._initCache = function () {
  6997. _super.prototype._initCache.call(this);
  6998. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6999. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7000. this._cache.mode = undefined;
  7001. this._cache.minZ = undefined;
  7002. this._cache.maxZ = undefined;
  7003. this._cache.fov = undefined;
  7004. this._cache.aspectRatio = undefined;
  7005. this._cache.orthoLeft = undefined;
  7006. this._cache.orthoRight = undefined;
  7007. this._cache.orthoBottom = undefined;
  7008. this._cache.orthoTop = undefined;
  7009. this._cache.renderWidth = undefined;
  7010. this._cache.renderHeight = undefined;
  7011. };
  7012. Camera.prototype._updateCache = function (ignoreParentClass) {
  7013. if (!ignoreParentClass) {
  7014. _super.prototype._updateCache.call(this);
  7015. }
  7016. var engine = this.getEngine();
  7017. this._cache.position.copyFrom(this.position);
  7018. this._cache.upVector.copyFrom(this.upVector);
  7019. this._cache.mode = this.mode;
  7020. this._cache.minZ = this.minZ;
  7021. this._cache.maxZ = this.maxZ;
  7022. this._cache.fov = this.fov;
  7023. this._cache.aspectRatio = engine.getAspectRatio(this);
  7024. this._cache.orthoLeft = this.orthoLeft;
  7025. this._cache.orthoRight = this.orthoRight;
  7026. this._cache.orthoBottom = this.orthoBottom;
  7027. this._cache.orthoTop = this.orthoTop;
  7028. this._cache.renderWidth = engine.getRenderWidth();
  7029. this._cache.renderHeight = engine.getRenderHeight();
  7030. };
  7031. Camera.prototype._updateFromScene = function () {
  7032. this.updateCache();
  7033. this._update();
  7034. };
  7035. // Synchronized
  7036. Camera.prototype._isSynchronized = function () {
  7037. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  7038. };
  7039. Camera.prototype._isSynchronizedViewMatrix = function () {
  7040. if (!_super.prototype._isSynchronized.call(this))
  7041. return false;
  7042. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  7043. };
  7044. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7045. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7046. if (!check) {
  7047. return false;
  7048. }
  7049. var engine = this.getEngine();
  7050. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7051. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7052. }
  7053. else {
  7054. 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();
  7055. }
  7056. return check;
  7057. };
  7058. // Controls
  7059. Camera.prototype.attachControl = function (element) {
  7060. };
  7061. Camera.prototype.detachControl = function (element) {
  7062. };
  7063. Camera.prototype._update = function () {
  7064. };
  7065. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7066. if (insertAt === void 0) { insertAt = null; }
  7067. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7068. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7069. return 0;
  7070. }
  7071. if (insertAt == null || insertAt < 0) {
  7072. this._postProcesses.push(postProcess);
  7073. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7074. return this._postProcesses.length - 1;
  7075. }
  7076. var add = 0;
  7077. if (this._postProcesses[insertAt]) {
  7078. var start = this._postProcesses.length - 1;
  7079. for (var i = start; i >= insertAt + 1; --i) {
  7080. this._postProcesses[i + 1] = this._postProcesses[i];
  7081. }
  7082. add = 1;
  7083. }
  7084. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7085. if (this._postProcessesTakenIndices[i] < insertAt) {
  7086. continue;
  7087. }
  7088. start = this._postProcessesTakenIndices.length - 1;
  7089. for (var j = start; j >= i; --j) {
  7090. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7091. }
  7092. this._postProcessesTakenIndices[i] = insertAt;
  7093. break;
  7094. }
  7095. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7096. this._postProcessesTakenIndices.push(insertAt);
  7097. }
  7098. var result = insertAt + add;
  7099. this._postProcesses[result] = postProcess;
  7100. return result;
  7101. };
  7102. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7103. if (atIndices === void 0) { atIndices = null; }
  7104. var result = [];
  7105. if (!atIndices) {
  7106. var length = this._postProcesses.length;
  7107. for (var i = 0; i < length; i++) {
  7108. if (this._postProcesses[i] !== postProcess) {
  7109. continue;
  7110. }
  7111. delete this._postProcesses[i];
  7112. var index = this._postProcessesTakenIndices.indexOf(i);
  7113. this._postProcessesTakenIndices.splice(index, 1);
  7114. }
  7115. }
  7116. else {
  7117. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7118. for (i = 0; i < atIndices.length; i++) {
  7119. var foundPostProcess = this._postProcesses[atIndices[i]];
  7120. if (foundPostProcess !== postProcess) {
  7121. result.push(i);
  7122. continue;
  7123. }
  7124. delete this._postProcesses[atIndices[i]];
  7125. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7126. this._postProcessesTakenIndices.splice(index, 1);
  7127. }
  7128. }
  7129. return result;
  7130. };
  7131. Camera.prototype.getWorldMatrix = function () {
  7132. if (!this._worldMatrix) {
  7133. this._worldMatrix = BABYLON.Matrix.Identity();
  7134. }
  7135. var viewMatrix = this.getViewMatrix();
  7136. viewMatrix.invertToRef(this._worldMatrix);
  7137. return this._worldMatrix;
  7138. };
  7139. Camera.prototype._getViewMatrix = function () {
  7140. return BABYLON.Matrix.Identity();
  7141. };
  7142. Camera.prototype.getViewMatrix = function (force) {
  7143. this._computedViewMatrix = this._computeViewMatrix(force);
  7144. if (!force && this._isSynchronizedViewMatrix()) {
  7145. return this._computedViewMatrix;
  7146. }
  7147. if (!this.parent || !this.parent.getWorldMatrix) {
  7148. this._globalPosition.copyFrom(this.position);
  7149. }
  7150. else {
  7151. if (!this._worldMatrix) {
  7152. this._worldMatrix = BABYLON.Matrix.Identity();
  7153. }
  7154. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7155. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7156. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7157. this._computedViewMatrix.invert();
  7158. this._markSyncedWithParent();
  7159. }
  7160. this._currentRenderId = this.getScene().getRenderId();
  7161. return this._computedViewMatrix;
  7162. };
  7163. Camera.prototype._computeViewMatrix = function (force) {
  7164. if (!force && this._isSynchronizedViewMatrix()) {
  7165. return this._computedViewMatrix;
  7166. }
  7167. this._computedViewMatrix = this._getViewMatrix();
  7168. this._currentRenderId = this.getScene().getRenderId();
  7169. return this._computedViewMatrix;
  7170. };
  7171. Camera.prototype.getProjectionMatrix = function (force) {
  7172. if (!force && this._isSynchronizedProjectionMatrix()) {
  7173. return this._projectionMatrix;
  7174. }
  7175. var engine = this.getEngine();
  7176. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7177. if (this.minZ <= 0) {
  7178. this.minZ = 0.1;
  7179. }
  7180. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7181. return this._projectionMatrix;
  7182. }
  7183. var halfWidth = engine.getRenderWidth() / 2.0;
  7184. var halfHeight = engine.getRenderHeight() / 2.0;
  7185. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7186. return this._projectionMatrix;
  7187. };
  7188. Camera.prototype.dispose = function () {
  7189. // Remove from scene
  7190. this.getScene().removeCamera(this);
  7191. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7192. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7193. }
  7194. };
  7195. // Statics
  7196. Camera._PERSPECTIVE_CAMERA = 0;
  7197. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7198. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7199. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7200. return Camera;
  7201. })(BABYLON.Node);
  7202. BABYLON.Camera = Camera;
  7203. })(BABYLON || (BABYLON = {}));
  7204. //# sourceMappingURL=babylon.camera.js.map
  7205. var BABYLON;
  7206. (function (BABYLON) {
  7207. var TargetCamera = (function (_super) {
  7208. __extends(TargetCamera, _super);
  7209. function TargetCamera(name, position, scene) {
  7210. _super.call(this, name, position, scene);
  7211. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7212. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7213. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7214. this.speed = 2.0;
  7215. this.noRotationConstraint = false;
  7216. this.lockedTarget = null;
  7217. this._currentTarget = BABYLON.Vector3.Zero();
  7218. this._viewMatrix = BABYLON.Matrix.Zero();
  7219. this._camMatrix = BABYLON.Matrix.Zero();
  7220. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7221. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7222. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7223. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7224. this._lookAtTemp = BABYLON.Matrix.Zero();
  7225. this._tempMatrix = BABYLON.Matrix.Zero();
  7226. }
  7227. TargetCamera.prototype._getLockedTargetPosition = function () {
  7228. if (!this.lockedTarget) {
  7229. return null;
  7230. }
  7231. return this.lockedTarget.position || this.lockedTarget;
  7232. };
  7233. // Cache
  7234. TargetCamera.prototype._initCache = function () {
  7235. _super.prototype._initCache.call(this);
  7236. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7237. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7238. };
  7239. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7240. if (!ignoreParentClass) {
  7241. _super.prototype._updateCache.call(this);
  7242. }
  7243. var lockedTargetPosition = this._getLockedTargetPosition();
  7244. if (!lockedTargetPosition) {
  7245. this._cache.lockedTarget = null;
  7246. }
  7247. else {
  7248. if (!this._cache.lockedTarget) {
  7249. this._cache.lockedTarget = lockedTargetPosition.clone();
  7250. }
  7251. else {
  7252. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7253. }
  7254. }
  7255. this._cache.rotation.copyFrom(this.rotation);
  7256. };
  7257. // Synchronized
  7258. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7259. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7260. return false;
  7261. }
  7262. var lockedTargetPosition = this._getLockedTargetPosition();
  7263. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7264. };
  7265. // Methods
  7266. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7267. var engine = this.getEngine();
  7268. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7269. };
  7270. // Target
  7271. TargetCamera.prototype.setTarget = function (target) {
  7272. this.upVector.normalize();
  7273. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7274. this._camMatrix.invert();
  7275. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7276. var vDir = target.subtract(this.position);
  7277. if (vDir.x >= 0.0) {
  7278. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7279. }
  7280. else {
  7281. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7282. }
  7283. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7284. if (isNaN(this.rotation.x)) {
  7285. this.rotation.x = 0;
  7286. }
  7287. if (isNaN(this.rotation.y)) {
  7288. this.rotation.y = 0;
  7289. }
  7290. if (isNaN(this.rotation.z)) {
  7291. this.rotation.z = 0;
  7292. }
  7293. };
  7294. TargetCamera.prototype.getTarget = function () {
  7295. return this._currentTarget;
  7296. };
  7297. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7298. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7299. };
  7300. TargetCamera.prototype._updatePosition = function () {
  7301. this.position.addInPlace(this.cameraDirection);
  7302. };
  7303. TargetCamera.prototype._update = function () {
  7304. var needToMove = this._decideIfNeedsToMove();
  7305. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7306. // Move
  7307. if (needToMove) {
  7308. this._updatePosition();
  7309. }
  7310. // Rotate
  7311. if (needToRotate) {
  7312. this.rotation.x += this.cameraRotation.x;
  7313. this.rotation.y += this.cameraRotation.y;
  7314. if (!this.noRotationConstraint) {
  7315. var limit = (Math.PI / 2) * 0.95;
  7316. if (this.rotation.x > limit)
  7317. this.rotation.x = limit;
  7318. if (this.rotation.x < -limit)
  7319. this.rotation.x = -limit;
  7320. }
  7321. }
  7322. // Inertia
  7323. if (needToMove) {
  7324. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7325. this.cameraDirection.x = 0;
  7326. }
  7327. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7328. this.cameraDirection.y = 0;
  7329. }
  7330. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7331. this.cameraDirection.z = 0;
  7332. }
  7333. this.cameraDirection.scaleInPlace(this.inertia);
  7334. }
  7335. if (needToRotate) {
  7336. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7337. this.cameraRotation.x = 0;
  7338. }
  7339. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7340. this.cameraRotation.y = 0;
  7341. }
  7342. this.cameraRotation.scaleInPlace(this.inertia);
  7343. }
  7344. };
  7345. TargetCamera.prototype._getViewMatrix = function () {
  7346. if (!this.lockedTarget) {
  7347. // Compute
  7348. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7349. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7350. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7351. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7352. this._lookAtTemp.invert();
  7353. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7354. }
  7355. else {
  7356. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7357. }
  7358. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7359. // Computing target and final matrix
  7360. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7361. }
  7362. else {
  7363. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7364. }
  7365. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7366. return this._viewMatrix;
  7367. };
  7368. return TargetCamera;
  7369. })(BABYLON.Camera);
  7370. BABYLON.TargetCamera = TargetCamera;
  7371. })(BABYLON || (BABYLON = {}));
  7372. //# sourceMappingURL=babylon.targetCamera.js.map
  7373. var BABYLON;
  7374. (function (BABYLON) {
  7375. var FollowCamera = (function (_super) {
  7376. __extends(FollowCamera, _super);
  7377. function FollowCamera(name, position, scene) {
  7378. _super.call(this, name, position, scene);
  7379. this.radius = 12;
  7380. this.rotationOffset = 0;
  7381. this.heightOffset = 4;
  7382. this.cameraAcceleration = 0.05;
  7383. this.maxCameraSpeed = 20;
  7384. }
  7385. FollowCamera.prototype.getRadians = function (degrees) {
  7386. return degrees * Math.PI / 180;
  7387. };
  7388. FollowCamera.prototype.follow = function (cameraTarget) {
  7389. if (!cameraTarget)
  7390. return;
  7391. var yRotation;
  7392. if (cameraTarget.rotationQuaternion) {
  7393. var rotMatrix = new BABYLON.Matrix();
  7394. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  7395. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  7396. }
  7397. else {
  7398. yRotation = cameraTarget.rotation.y;
  7399. }
  7400. var radians = this.getRadians(this.rotationOffset) + yRotation;
  7401. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7402. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7403. var dx = targetX - this.position.x;
  7404. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7405. var dz = (targetZ) - this.position.z;
  7406. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7407. var vy = dy * this.cameraAcceleration;
  7408. var vz = dz * this.cameraAcceleration * 2;
  7409. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7410. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7411. }
  7412. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7413. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7414. }
  7415. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7416. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7417. }
  7418. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7419. this.setTarget(cameraTarget.position);
  7420. };
  7421. FollowCamera.prototype._update = function () {
  7422. _super.prototype._update.call(this);
  7423. this.follow(this.target);
  7424. };
  7425. return FollowCamera;
  7426. })(BABYLON.TargetCamera);
  7427. BABYLON.FollowCamera = FollowCamera;
  7428. })(BABYLON || (BABYLON = {}));
  7429. //# sourceMappingURL=babylon.followCamera.js.map
  7430. var BABYLON;
  7431. (function (BABYLON) {
  7432. var FreeCamera = (function (_super) {
  7433. __extends(FreeCamera, _super);
  7434. function FreeCamera(name, position, scene) {
  7435. _super.call(this, name, position, scene);
  7436. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7437. this.keysUp = [38];
  7438. this.keysDown = [40];
  7439. this.keysLeft = [37];
  7440. this.keysRight = [39];
  7441. this.checkCollisions = false;
  7442. this.applyGravity = false;
  7443. this.angularSensibility = 2000.0;
  7444. this._keys = [];
  7445. this._collider = new BABYLON.Collider();
  7446. this._needMoveForGravity = true;
  7447. this._oldPosition = BABYLON.Vector3.Zero();
  7448. this._diffPosition = BABYLON.Vector3.Zero();
  7449. this._newPosition = BABYLON.Vector3.Zero();
  7450. }
  7451. // Controls
  7452. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7453. var _this = this;
  7454. var previousPosition;
  7455. var engine = this.getEngine();
  7456. if (this._attachedElement) {
  7457. return;
  7458. }
  7459. this._attachedElement = element;
  7460. if (this._onMouseDown === undefined) {
  7461. this._onMouseDown = function (evt) {
  7462. previousPosition = {
  7463. x: evt.clientX,
  7464. y: evt.clientY
  7465. };
  7466. if (!noPreventDefault) {
  7467. evt.preventDefault();
  7468. }
  7469. };
  7470. this._onMouseUp = function (evt) {
  7471. previousPosition = null;
  7472. if (!noPreventDefault) {
  7473. evt.preventDefault();
  7474. }
  7475. };
  7476. this._onMouseOut = function (evt) {
  7477. previousPosition = null;
  7478. _this._keys = [];
  7479. if (!noPreventDefault) {
  7480. evt.preventDefault();
  7481. }
  7482. };
  7483. this._onMouseMove = function (evt) {
  7484. if (!previousPosition && !engine.isPointerLock) {
  7485. return;
  7486. }
  7487. var offsetX;
  7488. var offsetY;
  7489. if (!engine.isPointerLock) {
  7490. offsetX = evt.clientX - previousPosition.x;
  7491. offsetY = evt.clientY - previousPosition.y;
  7492. }
  7493. else {
  7494. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7495. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7496. }
  7497. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7498. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7499. previousPosition = {
  7500. x: evt.clientX,
  7501. y: evt.clientY
  7502. };
  7503. if (!noPreventDefault) {
  7504. evt.preventDefault();
  7505. }
  7506. };
  7507. this._onKeyDown = function (evt) {
  7508. 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) {
  7509. var index = _this._keys.indexOf(evt.keyCode);
  7510. if (index === -1) {
  7511. _this._keys.push(evt.keyCode);
  7512. }
  7513. if (!noPreventDefault) {
  7514. evt.preventDefault();
  7515. }
  7516. }
  7517. };
  7518. this._onKeyUp = function (evt) {
  7519. 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) {
  7520. var index = _this._keys.indexOf(evt.keyCode);
  7521. if (index >= 0) {
  7522. _this._keys.splice(index, 1);
  7523. }
  7524. if (!noPreventDefault) {
  7525. evt.preventDefault();
  7526. }
  7527. }
  7528. };
  7529. this._onLostFocus = function () {
  7530. _this._keys = [];
  7531. };
  7532. this._reset = function () {
  7533. _this._keys = [];
  7534. previousPosition = null;
  7535. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7536. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7537. };
  7538. }
  7539. element.addEventListener("mousedown", this._onMouseDown, false);
  7540. element.addEventListener("mouseup", this._onMouseUp, false);
  7541. element.addEventListener("mouseout", this._onMouseOut, false);
  7542. element.addEventListener("mousemove", this._onMouseMove, false);
  7543. BABYLON.Tools.RegisterTopRootEvents([
  7544. { name: "keydown", handler: this._onKeyDown },
  7545. { name: "keyup", handler: this._onKeyUp },
  7546. { name: "blur", handler: this._onLostFocus }
  7547. ]);
  7548. };
  7549. FreeCamera.prototype.detachControl = function (element) {
  7550. if (this._attachedElement != element) {
  7551. return;
  7552. }
  7553. element.removeEventListener("mousedown", this._onMouseDown);
  7554. element.removeEventListener("mouseup", this._onMouseUp);
  7555. element.removeEventListener("mouseout", this._onMouseOut);
  7556. element.removeEventListener("mousemove", this._onMouseMove);
  7557. BABYLON.Tools.UnregisterTopRootEvents([
  7558. { name: "keydown", handler: this._onKeyDown },
  7559. { name: "keyup", handler: this._onKeyUp },
  7560. { name: "blur", handler: this._onLostFocus }
  7561. ]);
  7562. this._attachedElement = null;
  7563. if (this._reset) {
  7564. this._reset();
  7565. }
  7566. };
  7567. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7568. var globalPosition;
  7569. if (this.parent) {
  7570. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7571. }
  7572. else {
  7573. globalPosition = this.position;
  7574. }
  7575. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7576. this._collider.radius = this.ellipsoid;
  7577. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7578. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7579. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7580. this.position.addInPlace(this._diffPosition);
  7581. if (this.onCollide) {
  7582. this.onCollide(this._collider.collidedMesh);
  7583. }
  7584. }
  7585. };
  7586. FreeCamera.prototype._checkInputs = function () {
  7587. if (!this._localDirection) {
  7588. this._localDirection = BABYLON.Vector3.Zero();
  7589. this._transformedDirection = BABYLON.Vector3.Zero();
  7590. }
  7591. for (var index = 0; index < this._keys.length; index++) {
  7592. var keyCode = this._keys[index];
  7593. var speed = this._computeLocalCameraSpeed();
  7594. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7595. this._localDirection.copyFromFloats(-speed, 0, 0);
  7596. }
  7597. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7598. this._localDirection.copyFromFloats(0, 0, speed);
  7599. }
  7600. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7601. this._localDirection.copyFromFloats(speed, 0, 0);
  7602. }
  7603. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7604. this._localDirection.copyFromFloats(0, 0, -speed);
  7605. }
  7606. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7607. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7608. this.cameraDirection.addInPlace(this._transformedDirection);
  7609. }
  7610. };
  7611. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7612. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7613. };
  7614. FreeCamera.prototype._updatePosition = function () {
  7615. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7616. this._collideWithWorld(this.cameraDirection);
  7617. if (this.applyGravity) {
  7618. var oldPosition = this.position;
  7619. this._collideWithWorld(this.getScene().gravity);
  7620. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7621. }
  7622. }
  7623. else {
  7624. this.position.addInPlace(this.cameraDirection);
  7625. }
  7626. };
  7627. FreeCamera.prototype._update = function () {
  7628. this._checkInputs();
  7629. _super.prototype._update.call(this);
  7630. };
  7631. return FreeCamera;
  7632. })(BABYLON.TargetCamera);
  7633. BABYLON.FreeCamera = FreeCamera;
  7634. })(BABYLON || (BABYLON = {}));
  7635. //# sourceMappingURL=babylon.freeCamera.js.map
  7636. var BABYLON;
  7637. (function (BABYLON) {
  7638. // We're mainly based on the logic defined into the FreeCamera code
  7639. var TouchCamera = (function (_super) {
  7640. __extends(TouchCamera, _super);
  7641. function TouchCamera(name, position, scene) {
  7642. _super.call(this, name, position, scene);
  7643. this._offsetX = null;
  7644. this._offsetY = null;
  7645. this._pointerCount = 0;
  7646. this._pointerPressed = [];
  7647. this.angularSensibility = 200000.0;
  7648. this.moveSensibility = 500.0;
  7649. }
  7650. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7651. var _this = this;
  7652. var previousPosition;
  7653. if (this._attachedCanvas) {
  7654. return;
  7655. }
  7656. this._attachedCanvas = canvas;
  7657. if (this._onPointerDown === undefined) {
  7658. this._onPointerDown = function (evt) {
  7659. if (!noPreventDefault) {
  7660. evt.preventDefault();
  7661. }
  7662. _this._pointerPressed.push(evt.pointerId);
  7663. if (_this._pointerPressed.length !== 1) {
  7664. return;
  7665. }
  7666. previousPosition = {
  7667. x: evt.clientX,
  7668. y: evt.clientY
  7669. };
  7670. };
  7671. this._onPointerUp = function (evt) {
  7672. if (!noPreventDefault) {
  7673. evt.preventDefault();
  7674. }
  7675. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7676. if (index === -1) {
  7677. return;
  7678. }
  7679. _this._pointerPressed.splice(index, 1);
  7680. if (index != 0) {
  7681. return;
  7682. }
  7683. previousPosition = null;
  7684. _this._offsetX = null;
  7685. _this._offsetY = null;
  7686. };
  7687. this._onPointerMove = function (evt) {
  7688. if (!noPreventDefault) {
  7689. evt.preventDefault();
  7690. }
  7691. if (!previousPosition) {
  7692. return;
  7693. }
  7694. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7695. if (index != 0) {
  7696. return;
  7697. }
  7698. _this._offsetX = evt.clientX - previousPosition.x;
  7699. _this._offsetY = -(evt.clientY - previousPosition.y);
  7700. };
  7701. this._onLostFocus = function () {
  7702. _this._offsetX = null;
  7703. _this._offsetY = null;
  7704. };
  7705. }
  7706. canvas.addEventListener("pointerdown", this._onPointerDown);
  7707. canvas.addEventListener("pointerup", this._onPointerUp);
  7708. canvas.addEventListener("pointerout", this._onPointerUp);
  7709. canvas.addEventListener("pointermove", this._onPointerMove);
  7710. BABYLON.Tools.RegisterTopRootEvents([
  7711. { name: "blur", handler: this._onLostFocus }
  7712. ]);
  7713. };
  7714. TouchCamera.prototype.detachControl = function (canvas) {
  7715. if (this._attachedCanvas != canvas) {
  7716. return;
  7717. }
  7718. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7719. canvas.removeEventListener("pointerup", this._onPointerUp);
  7720. canvas.removeEventListener("pointerout", this._onPointerUp);
  7721. canvas.removeEventListener("pointermove", this._onPointerMove);
  7722. BABYLON.Tools.UnregisterTopRootEvents([
  7723. { name: "blur", handler: this._onLostFocus }
  7724. ]);
  7725. this._attachedCanvas = null;
  7726. };
  7727. TouchCamera.prototype._checkInputs = function () {
  7728. if (!this._offsetX) {
  7729. return;
  7730. }
  7731. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7732. if (this._pointerPressed.length > 1) {
  7733. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7734. }
  7735. else {
  7736. var speed = this._computeLocalCameraSpeed();
  7737. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7738. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7739. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7740. }
  7741. };
  7742. return TouchCamera;
  7743. })(BABYLON.FreeCamera);
  7744. BABYLON.TouchCamera = TouchCamera;
  7745. })(BABYLON || (BABYLON = {}));
  7746. //# sourceMappingURL=babylon.touchCamera.js.map
  7747. var BABYLON;
  7748. (function (BABYLON) {
  7749. // We're mainly based on the logic defined into the FreeCamera code
  7750. var DeviceOrientationCamera = (function (_super) {
  7751. __extends(DeviceOrientationCamera, _super);
  7752. function DeviceOrientationCamera(name, position, scene) {
  7753. var _this = this;
  7754. _super.call(this, name, position, scene);
  7755. this._offsetX = null;
  7756. this._offsetY = null;
  7757. this._orientationGamma = 0;
  7758. this._orientationBeta = 0;
  7759. this._initialOrientationGamma = 0;
  7760. this._initialOrientationBeta = 0;
  7761. this.angularSensibility = 10000.0;
  7762. this.moveSensibility = 50.0;
  7763. window.addEventListener("resize", function () {
  7764. _this._initialOrientationGamma = null;
  7765. }, false);
  7766. }
  7767. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7768. var _this = this;
  7769. if (this._attachedCanvas) {
  7770. return;
  7771. }
  7772. this._attachedCanvas = canvas;
  7773. if (!this._orientationChanged) {
  7774. this._orientationChanged = function (evt) {
  7775. if (!_this._initialOrientationGamma) {
  7776. _this._initialOrientationGamma = evt.gamma;
  7777. _this._initialOrientationBeta = evt.beta;
  7778. }
  7779. _this._orientationGamma = evt.gamma;
  7780. _this._orientationBeta = evt.beta;
  7781. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7782. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7783. };
  7784. }
  7785. window.addEventListener("deviceorientation", this._orientationChanged);
  7786. };
  7787. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7788. if (this._attachedCanvas != canvas) {
  7789. return;
  7790. }
  7791. window.removeEventListener("deviceorientation", this._orientationChanged);
  7792. this._attachedCanvas = null;
  7793. this._orientationGamma = 0;
  7794. this._orientationBeta = 0;
  7795. this._initialOrientationGamma = 0;
  7796. this._initialOrientationBeta = 0;
  7797. };
  7798. DeviceOrientationCamera.prototype._checkInputs = function () {
  7799. if (!this._offsetX) {
  7800. return;
  7801. }
  7802. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7803. var speed = this._computeLocalCameraSpeed();
  7804. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7805. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7806. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7807. };
  7808. return DeviceOrientationCamera;
  7809. })(BABYLON.FreeCamera);
  7810. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7811. })(BABYLON || (BABYLON = {}));
  7812. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7813. var BABYLON;
  7814. (function (BABYLON) {
  7815. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7816. var ArcRotateCamera = (function (_super) {
  7817. __extends(ArcRotateCamera, _super);
  7818. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7819. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7820. this.alpha = alpha;
  7821. this.beta = beta;
  7822. this.radius = radius;
  7823. this.target = target;
  7824. this.inertialAlphaOffset = 0;
  7825. this.inertialBetaOffset = 0;
  7826. this.inertialRadiusOffset = 0;
  7827. this.lowerAlphaLimit = null;
  7828. this.upperAlphaLimit = null;
  7829. this.lowerBetaLimit = 0.01;
  7830. this.upperBetaLimit = Math.PI;
  7831. this.lowerRadiusLimit = null;
  7832. this.upperRadiusLimit = null;
  7833. this.angularSensibility = 1000.0;
  7834. this.wheelPrecision = 3.0;
  7835. this.pinchPrecision = 2.0;
  7836. this.keysUp = [38];
  7837. this.keysDown = [40];
  7838. this.keysLeft = [37];
  7839. this.keysRight = [39];
  7840. this.zoomOnFactor = 1;
  7841. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7842. this._keys = [];
  7843. this._viewMatrix = new BABYLON.Matrix();
  7844. this.checkCollisions = false;
  7845. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7846. this._collider = new BABYLON.Collider();
  7847. this._previousPosition = BABYLON.Vector3.Zero();
  7848. this._collisionVelocity = BABYLON.Vector3.Zero();
  7849. this._newPosition = BABYLON.Vector3.Zero();
  7850. if (!this.target) {
  7851. this.target = BABYLON.Vector3.Zero();
  7852. }
  7853. this.getViewMatrix();
  7854. }
  7855. ArcRotateCamera.prototype._getTargetPosition = function () {
  7856. return this.target.position || this.target;
  7857. };
  7858. // Cache
  7859. ArcRotateCamera.prototype._initCache = function () {
  7860. _super.prototype._initCache.call(this);
  7861. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7862. this._cache.alpha = undefined;
  7863. this._cache.beta = undefined;
  7864. this._cache.radius = undefined;
  7865. this._cache.targetScreenOffset = undefined;
  7866. };
  7867. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7868. if (!ignoreParentClass) {
  7869. _super.prototype._updateCache.call(this);
  7870. }
  7871. this._cache.target.copyFrom(this._getTargetPosition());
  7872. this._cache.alpha = this.alpha;
  7873. this._cache.beta = this.beta;
  7874. this._cache.radius = this.radius;
  7875. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7876. };
  7877. // Synchronized
  7878. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7879. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7880. return false;
  7881. 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);
  7882. };
  7883. // Methods
  7884. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7885. var _this = this;
  7886. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7887. var previousPinchDistance = 0;
  7888. var pointers = new BABYLON.SmartCollection();
  7889. if (this._attachedElement) {
  7890. return;
  7891. }
  7892. this._attachedElement = element;
  7893. var engine = this.getEngine();
  7894. if (this._onPointerDown === undefined) {
  7895. this._onPointerDown = function (evt) {
  7896. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7897. cacheSoloPointer = pointers.item(evt.pointerId);
  7898. if (!noPreventDefault) {
  7899. evt.preventDefault();
  7900. }
  7901. };
  7902. this._onPointerUp = function (evt) {
  7903. cacheSoloPointer = null;
  7904. previousPinchDistance = 0;
  7905. pointers.remove(evt.pointerId);
  7906. if (!noPreventDefault) {
  7907. evt.preventDefault();
  7908. }
  7909. };
  7910. this._onPointerMove = function (evt) {
  7911. if (!noPreventDefault) {
  7912. evt.preventDefault();
  7913. }
  7914. switch (pointers.count) {
  7915. case 1:
  7916. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7917. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7918. var offsetX = evt.clientX - cacheSoloPointer.x;
  7919. var offsetY = evt.clientY - cacheSoloPointer.y;
  7920. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7921. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7922. //pointers.item(evt.pointerId).x = evt.clientX;
  7923. //pointers.item(evt.pointerId).y = evt.clientY;
  7924. cacheSoloPointer.x = evt.clientX;
  7925. cacheSoloPointer.y = evt.clientY;
  7926. break;
  7927. case 2:
  7928. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7929. pointers.item(evt.pointerId).x = evt.clientX;
  7930. pointers.item(evt.pointerId).y = evt.clientY;
  7931. var direction = 1;
  7932. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7933. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7934. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7935. if (previousPinchDistance === 0) {
  7936. previousPinchDistance = pinchSquaredDistance;
  7937. return;
  7938. }
  7939. if (pinchSquaredDistance !== previousPinchDistance) {
  7940. if (pinchSquaredDistance > previousPinchDistance) {
  7941. direction = -1;
  7942. }
  7943. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7944. previousPinchDistance = pinchSquaredDistance;
  7945. }
  7946. break;
  7947. default:
  7948. if (pointers.item(evt.pointerId)) {
  7949. pointers.item(evt.pointerId).x = evt.clientX;
  7950. pointers.item(evt.pointerId).y = evt.clientY;
  7951. }
  7952. }
  7953. };
  7954. this._onMouseMove = function (evt) {
  7955. if (!engine.isPointerLock) {
  7956. return;
  7957. }
  7958. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7959. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7960. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7961. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7962. if (!noPreventDefault) {
  7963. evt.preventDefault();
  7964. }
  7965. };
  7966. this._wheel = function (event) {
  7967. var delta = 0;
  7968. if (event.wheelDelta) {
  7969. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7970. }
  7971. else if (event.detail) {
  7972. delta = -event.detail / _this.wheelPrecision;
  7973. }
  7974. if (delta)
  7975. _this.inertialRadiusOffset += delta;
  7976. if (event.preventDefault) {
  7977. if (!noPreventDefault) {
  7978. event.preventDefault();
  7979. }
  7980. }
  7981. };
  7982. this._onKeyDown = function (evt) {
  7983. 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) {
  7984. var index = _this._keys.indexOf(evt.keyCode);
  7985. if (index === -1) {
  7986. _this._keys.push(evt.keyCode);
  7987. }
  7988. if (evt.preventDefault) {
  7989. if (!noPreventDefault) {
  7990. evt.preventDefault();
  7991. }
  7992. }
  7993. }
  7994. };
  7995. this._onKeyUp = function (evt) {
  7996. 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) {
  7997. var index = _this._keys.indexOf(evt.keyCode);
  7998. if (index >= 0) {
  7999. _this._keys.splice(index, 1);
  8000. }
  8001. if (evt.preventDefault) {
  8002. if (!noPreventDefault) {
  8003. evt.preventDefault();
  8004. }
  8005. }
  8006. }
  8007. };
  8008. this._onLostFocus = function () {
  8009. _this._keys = [];
  8010. pointers.empty();
  8011. previousPinchDistance = 0;
  8012. cacheSoloPointer = null;
  8013. };
  8014. this._onGestureStart = function (e) {
  8015. if (window.MSGesture === undefined) {
  8016. return;
  8017. }
  8018. if (!_this._MSGestureHandler) {
  8019. _this._MSGestureHandler = new MSGesture();
  8020. _this._MSGestureHandler.target = element;
  8021. }
  8022. _this._MSGestureHandler.addPointer(e.pointerId);
  8023. };
  8024. this._onGesture = function (e) {
  8025. _this.radius *= e.scale;
  8026. if (e.preventDefault) {
  8027. if (!noPreventDefault) {
  8028. e.stopPropagation();
  8029. e.preventDefault();
  8030. }
  8031. }
  8032. };
  8033. this._reset = function () {
  8034. _this._keys = [];
  8035. _this.inertialAlphaOffset = 0;
  8036. _this.inertialBetaOffset = 0;
  8037. _this.inertialRadiusOffset = 0;
  8038. pointers.empty();
  8039. previousPinchDistance = 0;
  8040. cacheSoloPointer = null;
  8041. };
  8042. }
  8043. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8044. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8045. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  8046. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8047. element.addEventListener("mousemove", this._onMouseMove, false);
  8048. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  8049. element.addEventListener("MSGestureChange", this._onGesture, false);
  8050. element.addEventListener('mousewheel', this._wheel, false);
  8051. element.addEventListener('DOMMouseScroll', this._wheel, false);
  8052. BABYLON.Tools.RegisterTopRootEvents([
  8053. { name: "keydown", handler: this._onKeyDown },
  8054. { name: "keyup", handler: this._onKeyUp },
  8055. { name: "blur", handler: this._onLostFocus }
  8056. ]);
  8057. };
  8058. ArcRotateCamera.prototype.detachControl = function (element) {
  8059. if (this._attachedElement !== element) {
  8060. return;
  8061. }
  8062. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8063. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8064. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8065. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8066. element.removeEventListener("mousemove", this._onMouseMove);
  8067. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8068. element.removeEventListener("MSGestureChange", this._onGesture);
  8069. element.removeEventListener('mousewheel', this._wheel);
  8070. element.removeEventListener('DOMMouseScroll', this._wheel);
  8071. BABYLON.Tools.UnregisterTopRootEvents([
  8072. { name: "keydown", handler: this._onKeyDown },
  8073. { name: "keyup", handler: this._onKeyUp },
  8074. { name: "blur", handler: this._onLostFocus }
  8075. ]);
  8076. this._MSGestureHandler = null;
  8077. this._attachedElement = null;
  8078. if (this._reset) {
  8079. this._reset();
  8080. }
  8081. };
  8082. ArcRotateCamera.prototype._update = function () {
  8083. for (var index = 0; index < this._keys.length; index++) {
  8084. var keyCode = this._keys[index];
  8085. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8086. this.inertialAlphaOffset -= 0.01;
  8087. }
  8088. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8089. this.inertialBetaOffset -= 0.01;
  8090. }
  8091. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8092. this.inertialAlphaOffset += 0.01;
  8093. }
  8094. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8095. this.inertialBetaOffset += 0.01;
  8096. }
  8097. }
  8098. // Inertia
  8099. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8100. this.alpha += this.inertialAlphaOffset;
  8101. this.beta += this.inertialBetaOffset;
  8102. this.radius -= this.inertialRadiusOffset;
  8103. this.inertialAlphaOffset *= this.inertia;
  8104. this.inertialBetaOffset *= this.inertia;
  8105. this.inertialRadiusOffset *= this.inertia;
  8106. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8107. this.inertialAlphaOffset = 0;
  8108. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8109. this.inertialBetaOffset = 0;
  8110. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8111. this.inertialRadiusOffset = 0;
  8112. }
  8113. // Limits
  8114. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8115. this.alpha = this.lowerAlphaLimit;
  8116. }
  8117. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8118. this.alpha = this.upperAlphaLimit;
  8119. }
  8120. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8121. this.beta = this.lowerBetaLimit;
  8122. }
  8123. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8124. this.beta = this.upperBetaLimit;
  8125. }
  8126. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8127. this.radius = this.lowerRadiusLimit;
  8128. }
  8129. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8130. this.radius = this.upperRadiusLimit;
  8131. }
  8132. };
  8133. ArcRotateCamera.prototype.setPosition = function (position) {
  8134. var radiusv3 = position.subtract(this._getTargetPosition());
  8135. this.radius = radiusv3.length();
  8136. // Alpha
  8137. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8138. if (radiusv3.z < 0) {
  8139. this.alpha = 2 * Math.PI - this.alpha;
  8140. }
  8141. // Beta
  8142. this.beta = Math.acos(radiusv3.y / this.radius);
  8143. };
  8144. ArcRotateCamera.prototype._getViewMatrix = function () {
  8145. // Compute
  8146. var cosa = Math.cos(this.alpha);
  8147. var sina = Math.sin(this.alpha);
  8148. var cosb = Math.cos(this.beta);
  8149. var sinb = Math.sin(this.beta);
  8150. var target = this._getTargetPosition();
  8151. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8152. if (this.checkCollisions) {
  8153. this._collider.radius = this.collisionRadius;
  8154. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8155. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8156. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8157. this.position.copyFrom(this._previousPosition);
  8158. this.alpha = this._previousAlpha;
  8159. this.beta = this._previousBeta;
  8160. this.radius = this._previousRadius;
  8161. if (this.onCollide) {
  8162. this.onCollide(this._collider.collidedMesh);
  8163. }
  8164. }
  8165. }
  8166. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8167. this._previousAlpha = this.alpha;
  8168. this._previousBeta = this.beta;
  8169. this._previousRadius = this.radius;
  8170. this._previousPosition.copyFrom(this.position);
  8171. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8172. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8173. return this._viewMatrix;
  8174. };
  8175. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8176. meshes = meshes || this.getScene().meshes;
  8177. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8178. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8179. this.radius = distance * this.zoomOnFactor;
  8180. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8181. };
  8182. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8183. var meshesOrMinMaxVector;
  8184. var distance;
  8185. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8186. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8187. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8188. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8189. }
  8190. else {
  8191. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8192. distance = meshesOrMinMaxVectorAndDistance.distance;
  8193. }
  8194. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8195. this.maxZ = distance * 2;
  8196. };
  8197. return ArcRotateCamera;
  8198. })(BABYLON.Camera);
  8199. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8200. })(BABYLON || (BABYLON = {}));
  8201. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8202. (function (BABYLON) {
  8203. /**
  8204. * Represents a scene to be rendered by the engine.
  8205. * @see http://doc.babylonjs.com/page.php?p=21911
  8206. */
  8207. var Scene = (function () {
  8208. /**
  8209. * @constructor
  8210. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8211. */
  8212. function Scene(engine) {
  8213. // Members
  8214. this.autoClear = true;
  8215. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8216. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8217. this.forceWireframe = false;
  8218. this.forcePointsCloud = false;
  8219. this.forceShowBoundingBoxes = false;
  8220. this.animationsEnabled = true;
  8221. 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
  8222. // Fog
  8223. /**
  8224. * is fog enabled on this scene.
  8225. * @type {boolean}
  8226. */
  8227. this.fogEnabled = true;
  8228. this.fogMode = Scene.FOGMODE_NONE;
  8229. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8230. this.fogDensity = 0.1;
  8231. this.fogStart = 0;
  8232. this.fogEnd = 1000.0;
  8233. // Lights
  8234. /**
  8235. * is shadow enabled on this scene.
  8236. * @type {boolean}
  8237. */
  8238. this.shadowsEnabled = true;
  8239. /**
  8240. * is light enabled on this scene.
  8241. * @type {boolean}
  8242. */
  8243. this.lightsEnabled = true;
  8244. /**
  8245. * All of the lights added to this scene.
  8246. * @see BABYLON.Light
  8247. * @type {BABYLON.Light[]}
  8248. */
  8249. this.lights = new Array();
  8250. // Cameras
  8251. /**
  8252. * All of the cameras added to this scene.
  8253. * @see BABYLON.Camera
  8254. * @type {BABYLON.Camera[]}
  8255. */
  8256. this.cameras = new Array();
  8257. this.activeCameras = new Array();
  8258. // Meshes
  8259. /**
  8260. * All of the (abstract) meshes added to this scene.
  8261. * @see BABYLON.AbstractMesh
  8262. * @type {BABYLON.AbstractMesh[]}
  8263. */
  8264. this.meshes = new Array();
  8265. // Geometries
  8266. this._geometries = new Array();
  8267. this.materials = new Array();
  8268. this.multiMaterials = new Array();
  8269. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8270. // Textures
  8271. this.texturesEnabled = true;
  8272. this.textures = new Array();
  8273. // Particles
  8274. this.particlesEnabled = true;
  8275. this.particleSystems = new Array();
  8276. // Sprites
  8277. this.spritesEnabled = true;
  8278. this.spriteManagers = new Array();
  8279. // Layers
  8280. this.layers = new Array();
  8281. // Skeletons
  8282. this.skeletonsEnabled = true;
  8283. this.skeletons = new Array();
  8284. // Lens flares
  8285. this.lensFlaresEnabled = true;
  8286. this.lensFlareSystems = new Array();
  8287. // Collisions
  8288. this.collisionsEnabled = true;
  8289. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8290. // Postprocesses
  8291. this.postProcessesEnabled = true;
  8292. // Customs render targets
  8293. this.renderTargetsEnabled = true;
  8294. this.dumpNextRenderTargets = false;
  8295. this.customRenderTargets = new Array();
  8296. // Imported meshes
  8297. this.importedMeshesFiles = new Array();
  8298. this._actionManagers = new Array();
  8299. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8300. // Procedural textures
  8301. this.proceduralTexturesEnabled = true;
  8302. this._proceduralTextures = new Array();
  8303. this.soundTracks = new Array();
  8304. this._audioEnabled = true;
  8305. this._headphone = false;
  8306. this._totalVertices = 0;
  8307. this._activeIndices = 0;
  8308. this._activeParticles = 0;
  8309. this._lastFrameDuration = 0;
  8310. this._evaluateActiveMeshesDuration = 0;
  8311. this._renderTargetsDuration = 0;
  8312. this._particlesDuration = 0;
  8313. this._renderDuration = 0;
  8314. this._spritesDuration = 0;
  8315. this._animationRatio = 0;
  8316. this._renderId = 0;
  8317. this._executeWhenReadyTimeoutId = -1;
  8318. this._toBeDisposed = new BABYLON.SmartArray(256);
  8319. this._onReadyCallbacks = new Array();
  8320. this._pendingData = []; //ANY
  8321. this._onBeforeRenderCallbacks = new Array();
  8322. this._onAfterRenderCallbacks = new Array();
  8323. this._activeMeshes = new BABYLON.SmartArray(256);
  8324. this._processedMaterials = new BABYLON.SmartArray(256);
  8325. this._renderTargets = new BABYLON.SmartArray(256);
  8326. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8327. this._activeSkeletons = new BABYLON.SmartArray(32);
  8328. this._activeBones = 0;
  8329. this._activeAnimatables = new Array();
  8330. this._transformMatrix = BABYLON.Matrix.Zero();
  8331. this._scaledPosition = BABYLON.Vector3.Zero();
  8332. this._scaledVelocity = BABYLON.Vector3.Zero();
  8333. this._uniqueIdCounter = 0;
  8334. this._engine = engine;
  8335. engine.scenes.push(this);
  8336. this._renderingManager = new BABYLON.RenderingManager(this);
  8337. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8338. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8339. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8340. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8341. this.attachControl();
  8342. this._debugLayer = new BABYLON.DebugLayer(this);
  8343. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8344. //simplification queue
  8345. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8346. }
  8347. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8348. get: function () {
  8349. return Scene._FOGMODE_NONE;
  8350. },
  8351. enumerable: true,
  8352. configurable: true
  8353. });
  8354. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8355. get: function () {
  8356. return Scene._FOGMODE_EXP;
  8357. },
  8358. enumerable: true,
  8359. configurable: true
  8360. });
  8361. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8362. get: function () {
  8363. return Scene._FOGMODE_EXP2;
  8364. },
  8365. enumerable: true,
  8366. configurable: true
  8367. });
  8368. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8369. get: function () {
  8370. return Scene._FOGMODE_LINEAR;
  8371. },
  8372. enumerable: true,
  8373. configurable: true
  8374. });
  8375. Object.defineProperty(Scene.prototype, "debugLayer", {
  8376. // Properties
  8377. get: function () {
  8378. return this._debugLayer;
  8379. },
  8380. enumerable: true,
  8381. configurable: true
  8382. });
  8383. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8384. /**
  8385. * The mesh that is currently under the pointer.
  8386. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8387. */
  8388. get: function () {
  8389. return this._meshUnderPointer;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Scene.prototype, "pointerX", {
  8395. /**
  8396. * Current on-screen X position of the pointer
  8397. * @return {number} X position of the pointer
  8398. */
  8399. get: function () {
  8400. return this._pointerX;
  8401. },
  8402. enumerable: true,
  8403. configurable: true
  8404. });
  8405. Object.defineProperty(Scene.prototype, "pointerY", {
  8406. /**
  8407. * Current on-screen Y position of the pointer
  8408. * @return {number} Y position of the pointer
  8409. */
  8410. get: function () {
  8411. return this._pointerY;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Scene.prototype.getCachedMaterial = function () {
  8417. return this._cachedMaterial;
  8418. };
  8419. Scene.prototype.getBoundingBoxRenderer = function () {
  8420. return this._boundingBoxRenderer;
  8421. };
  8422. Scene.prototype.getOutlineRenderer = function () {
  8423. return this._outlineRenderer;
  8424. };
  8425. Scene.prototype.getEngine = function () {
  8426. return this._engine;
  8427. };
  8428. Scene.prototype.getTotalVertices = function () {
  8429. return this._totalVertices;
  8430. };
  8431. Scene.prototype.getActiveIndices = function () {
  8432. return this._activeIndices;
  8433. };
  8434. Scene.prototype.getActiveParticles = function () {
  8435. return this._activeParticles;
  8436. };
  8437. Scene.prototype.getActiveBones = function () {
  8438. return this._activeBones;
  8439. };
  8440. // Stats
  8441. Scene.prototype.getLastFrameDuration = function () {
  8442. return this._lastFrameDuration;
  8443. };
  8444. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8445. return this._evaluateActiveMeshesDuration;
  8446. };
  8447. Scene.prototype.getActiveMeshes = function () {
  8448. return this._activeMeshes;
  8449. };
  8450. Scene.prototype.getRenderTargetsDuration = function () {
  8451. return this._renderTargetsDuration;
  8452. };
  8453. Scene.prototype.getRenderDuration = function () {
  8454. return this._renderDuration;
  8455. };
  8456. Scene.prototype.getParticlesDuration = function () {
  8457. return this._particlesDuration;
  8458. };
  8459. Scene.prototype.getSpritesDuration = function () {
  8460. return this._spritesDuration;
  8461. };
  8462. Scene.prototype.getAnimationRatio = function () {
  8463. return this._animationRatio;
  8464. };
  8465. Scene.prototype.getRenderId = function () {
  8466. return this._renderId;
  8467. };
  8468. Scene.prototype.incrementRenderId = function () {
  8469. this._renderId++;
  8470. };
  8471. Scene.prototype._updatePointerPosition = function (evt) {
  8472. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8473. this._pointerX = evt.clientX - canvasRect.left;
  8474. this._pointerY = evt.clientY - canvasRect.top;
  8475. if (this.cameraToUseForPointers) {
  8476. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8477. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8478. }
  8479. };
  8480. // Pointers handling
  8481. Scene.prototype.attachControl = function () {
  8482. var _this = this;
  8483. this._onPointerMove = function (evt) {
  8484. var canvas = _this._engine.getRenderingCanvas();
  8485. _this._updatePointerPosition(evt);
  8486. 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);
  8487. if (pickResult.hit) {
  8488. _this._meshUnderPointer = pickResult.pickedMesh;
  8489. _this.setPointerOverMesh(pickResult.pickedMesh);
  8490. canvas.style.cursor = "pointer";
  8491. }
  8492. else {
  8493. _this.setPointerOverMesh(null);
  8494. canvas.style.cursor = "";
  8495. _this._meshUnderPointer = null;
  8496. }
  8497. };
  8498. this._onPointerDown = function (evt) {
  8499. var predicate = null;
  8500. if (!_this.onPointerDown) {
  8501. predicate = function (mesh) {
  8502. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8503. };
  8504. }
  8505. _this._updatePointerPosition(evt);
  8506. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8507. if (pickResult.hit) {
  8508. if (pickResult.pickedMesh.actionManager) {
  8509. switch (evt.button) {
  8510. case 0:
  8511. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8512. break;
  8513. case 1:
  8514. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8515. break;
  8516. case 2:
  8517. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8518. break;
  8519. }
  8520. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8521. }
  8522. }
  8523. if (_this.onPointerDown) {
  8524. _this.onPointerDown(evt, pickResult);
  8525. }
  8526. };
  8527. this._onPointerUp = function (evt) {
  8528. var predicate = null;
  8529. if (!_this.onPointerUp) {
  8530. predicate = function (mesh) {
  8531. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  8532. };
  8533. }
  8534. _this._updatePointerPosition(evt);
  8535. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8536. if (pickResult.hit) {
  8537. if (pickResult.pickedMesh.actionManager) {
  8538. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8539. }
  8540. }
  8541. if (_this.onPointerUp) {
  8542. _this.onPointerUp(evt, pickResult);
  8543. }
  8544. };
  8545. this._onKeyDown = function (evt) {
  8546. if (_this.actionManager) {
  8547. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8548. }
  8549. };
  8550. this._onKeyUp = function (evt) {
  8551. if (_this.actionManager) {
  8552. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8553. }
  8554. };
  8555. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8556. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8557. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8558. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8559. BABYLON.Tools.RegisterTopRootEvents([
  8560. { name: "keydown", handler: this._onKeyDown },
  8561. { name: "keyup", handler: this._onKeyUp }
  8562. ]);
  8563. };
  8564. Scene.prototype.detachControl = function () {
  8565. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8566. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8567. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8568. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  8569. BABYLON.Tools.UnregisterTopRootEvents([
  8570. { name: "keydown", handler: this._onKeyDown },
  8571. { name: "keyup", handler: this._onKeyUp }
  8572. ]);
  8573. };
  8574. // Ready
  8575. Scene.prototype.isReady = function () {
  8576. if (this._pendingData.length > 0) {
  8577. return false;
  8578. }
  8579. for (var index = 0; index < this._geometries.length; index++) {
  8580. var geometry = this._geometries[index];
  8581. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8582. return false;
  8583. }
  8584. }
  8585. for (index = 0; index < this.meshes.length; index++) {
  8586. var mesh = this.meshes[index];
  8587. if (!mesh.isReady()) {
  8588. return false;
  8589. }
  8590. var mat = mesh.material;
  8591. if (mat) {
  8592. if (!mat.isReady(mesh)) {
  8593. return false;
  8594. }
  8595. }
  8596. }
  8597. return true;
  8598. };
  8599. Scene.prototype.resetCachedMaterial = function () {
  8600. this._cachedMaterial = null;
  8601. };
  8602. Scene.prototype.registerBeforeRender = function (func) {
  8603. this._onBeforeRenderCallbacks.push(func);
  8604. };
  8605. Scene.prototype.unregisterBeforeRender = function (func) {
  8606. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8607. if (index > -1) {
  8608. this._onBeforeRenderCallbacks.splice(index, 1);
  8609. }
  8610. };
  8611. Scene.prototype.registerAfterRender = function (func) {
  8612. this._onAfterRenderCallbacks.push(func);
  8613. };
  8614. Scene.prototype.unregisterAfterRender = function (func) {
  8615. var index = this._onAfterRenderCallbacks.indexOf(func);
  8616. if (index > -1) {
  8617. this._onAfterRenderCallbacks.splice(index, 1);
  8618. }
  8619. };
  8620. Scene.prototype._addPendingData = function (data) {
  8621. this._pendingData.push(data);
  8622. };
  8623. Scene.prototype._removePendingData = function (data) {
  8624. var index = this._pendingData.indexOf(data);
  8625. if (index !== -1) {
  8626. this._pendingData.splice(index, 1);
  8627. }
  8628. };
  8629. Scene.prototype.getWaitingItemsCount = function () {
  8630. return this._pendingData.length;
  8631. };
  8632. /**
  8633. * Registers a function to be executed when the scene is ready.
  8634. * @param {Function} func - the function to be executed.
  8635. */
  8636. Scene.prototype.executeWhenReady = function (func) {
  8637. var _this = this;
  8638. this._onReadyCallbacks.push(func);
  8639. if (this._executeWhenReadyTimeoutId !== -1) {
  8640. return;
  8641. }
  8642. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8643. _this._checkIsReady();
  8644. }, 150);
  8645. };
  8646. Scene.prototype._checkIsReady = function () {
  8647. var _this = this;
  8648. if (this.isReady()) {
  8649. this._onReadyCallbacks.forEach(function (func) {
  8650. func();
  8651. });
  8652. this._onReadyCallbacks = [];
  8653. this._executeWhenReadyTimeoutId = -1;
  8654. return;
  8655. }
  8656. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8657. _this._checkIsReady();
  8658. }, 150);
  8659. };
  8660. // Animations
  8661. /**
  8662. * Will start the animation sequence of a given target
  8663. * @param target - the target
  8664. * @param {number} from - from which frame should animation start
  8665. * @param {number} to - till which frame should animation run.
  8666. * @param {boolean} [loop] - should the animation loop
  8667. * @param {number} [speedRatio] - the speed in which to run the animation
  8668. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8669. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8670. * @return {BABYLON.Animatable} the animatable object created for this animation
  8671. * @see BABYLON.Animatable
  8672. * @see http://doc.babylonjs.com/page.php?p=22081
  8673. */
  8674. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8675. if (speedRatio === undefined) {
  8676. speedRatio = 1.0;
  8677. }
  8678. this.stopAnimation(target);
  8679. if (!animatable) {
  8680. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8681. }
  8682. // Local animations
  8683. if (target.animations) {
  8684. animatable.appendAnimations(target, target.animations);
  8685. }
  8686. // Children animations
  8687. if (target.getAnimatables) {
  8688. var animatables = target.getAnimatables();
  8689. for (var index = 0; index < animatables.length; index++) {
  8690. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8691. }
  8692. }
  8693. return animatable;
  8694. };
  8695. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8696. if (speedRatio === undefined) {
  8697. speedRatio = 1.0;
  8698. }
  8699. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8700. return animatable;
  8701. };
  8702. Scene.prototype.getAnimatableByTarget = function (target) {
  8703. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8704. if (this._activeAnimatables[index].target === target) {
  8705. return this._activeAnimatables[index];
  8706. }
  8707. }
  8708. return null;
  8709. };
  8710. /**
  8711. * Will stop the animation of the given target
  8712. * @param target - the target
  8713. * @see beginAnimation
  8714. */
  8715. Scene.prototype.stopAnimation = function (target) {
  8716. var animatable = this.getAnimatableByTarget(target);
  8717. if (animatable) {
  8718. animatable.stop();
  8719. }
  8720. };
  8721. Scene.prototype._animate = function () {
  8722. if (!this.animationsEnabled) {
  8723. return;
  8724. }
  8725. if (!this._animationStartDate) {
  8726. this._animationStartDate = BABYLON.Tools.Now;
  8727. }
  8728. // Getting time
  8729. var now = BABYLON.Tools.Now;
  8730. var delay = now - this._animationStartDate;
  8731. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8732. this._activeAnimatables[index]._animate(delay);
  8733. }
  8734. };
  8735. // Matrix
  8736. Scene.prototype.getViewMatrix = function () {
  8737. return this._viewMatrix;
  8738. };
  8739. Scene.prototype.getProjectionMatrix = function () {
  8740. return this._projectionMatrix;
  8741. };
  8742. Scene.prototype.getTransformMatrix = function () {
  8743. return this._transformMatrix;
  8744. };
  8745. Scene.prototype.setTransformMatrix = function (view, projection) {
  8746. this._viewMatrix = view;
  8747. this._projectionMatrix = projection;
  8748. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8749. };
  8750. // Methods
  8751. Scene.prototype.addMesh = function (newMesh) {
  8752. newMesh.uniqueId = this._uniqueIdCounter++;
  8753. var position = this.meshes.push(newMesh);
  8754. if (this.onNewMeshAdded) {
  8755. this.onNewMeshAdded(newMesh, position, this);
  8756. }
  8757. };
  8758. Scene.prototype.removeMesh = function (toRemove) {
  8759. var index = this.meshes.indexOf(toRemove);
  8760. if (index !== -1) {
  8761. // Remove from the scene if mesh found
  8762. this.meshes.splice(index, 1);
  8763. }
  8764. if (this.onMeshRemoved) {
  8765. this.onMeshRemoved(toRemove);
  8766. }
  8767. return index;
  8768. };
  8769. Scene.prototype.removeLight = function (toRemove) {
  8770. var index = this.lights.indexOf(toRemove);
  8771. if (index !== -1) {
  8772. // Remove from the scene if mesh found
  8773. this.lights.splice(index, 1);
  8774. }
  8775. if (this.onLightRemoved) {
  8776. this.onLightRemoved(toRemove);
  8777. }
  8778. return index;
  8779. };
  8780. Scene.prototype.removeCamera = function (toRemove) {
  8781. var index = this.cameras.indexOf(toRemove);
  8782. if (index !== -1) {
  8783. // Remove from the scene if mesh found
  8784. this.cameras.splice(index, 1);
  8785. }
  8786. // Remove from activeCameras
  8787. var index2 = this.activeCameras.indexOf(toRemove);
  8788. if (index2 !== -1) {
  8789. // Remove from the scene if mesh found
  8790. this.activeCameras.splice(index2, 1);
  8791. }
  8792. // Reset the activeCamera
  8793. if (this.activeCamera === toRemove) {
  8794. if (this.cameras.length > 0) {
  8795. this.activeCamera = this.cameras[0];
  8796. }
  8797. else {
  8798. this.activeCamera = null;
  8799. }
  8800. }
  8801. if (this.onCameraRemoved) {
  8802. this.onCameraRemoved(toRemove);
  8803. }
  8804. return index;
  8805. };
  8806. Scene.prototype.addLight = function (newLight) {
  8807. newLight.uniqueId = this._uniqueIdCounter++;
  8808. var position = this.lights.push(newLight);
  8809. if (this.onNewLightAdded) {
  8810. this.onNewLightAdded(newLight, position, this);
  8811. }
  8812. };
  8813. Scene.prototype.addCamera = function (newCamera) {
  8814. newCamera.uniqueId = this._uniqueIdCounter++;
  8815. var position = this.cameras.push(newCamera);
  8816. if (this.onNewCameraAdded) {
  8817. this.onNewCameraAdded(newCamera, position, this);
  8818. }
  8819. };
  8820. /**
  8821. * sets the active camera of the scene using its ID
  8822. * @param {string} id - the camera's ID
  8823. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8824. * @see activeCamera
  8825. */
  8826. Scene.prototype.setActiveCameraByID = function (id) {
  8827. var camera = this.getCameraByID(id);
  8828. if (camera) {
  8829. this.activeCamera = camera;
  8830. return camera;
  8831. }
  8832. return null;
  8833. };
  8834. /**
  8835. * sets the active camera of the scene using its name
  8836. * @param {string} name - the camera's name
  8837. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8838. * @see activeCamera
  8839. */
  8840. Scene.prototype.setActiveCameraByName = function (name) {
  8841. var camera = this.getCameraByName(name);
  8842. if (camera) {
  8843. this.activeCamera = camera;
  8844. return camera;
  8845. }
  8846. return null;
  8847. };
  8848. /**
  8849. * get a material using its id
  8850. * @param {string} the material's ID
  8851. * @return {BABYLON.Material|null} the material or null if none found.
  8852. */
  8853. Scene.prototype.getMaterialByID = function (id) {
  8854. for (var index = 0; index < this.materials.length; index++) {
  8855. if (this.materials[index].id === id) {
  8856. return this.materials[index];
  8857. }
  8858. }
  8859. return null;
  8860. };
  8861. /**
  8862. * get a material using its name
  8863. * @param {string} the material's name
  8864. * @return {BABYLON.Material|null} the material or null if none found.
  8865. */
  8866. Scene.prototype.getMaterialByName = function (name) {
  8867. for (var index = 0; index < this.materials.length; index++) {
  8868. if (this.materials[index].name === name) {
  8869. return this.materials[index];
  8870. }
  8871. }
  8872. return null;
  8873. };
  8874. Scene.prototype.getCameraByID = function (id) {
  8875. for (var index = 0; index < this.cameras.length; index++) {
  8876. if (this.cameras[index].id === id) {
  8877. return this.cameras[index];
  8878. }
  8879. }
  8880. return null;
  8881. };
  8882. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8883. for (var index = 0; index < this.cameras.length; index++) {
  8884. if (this.cameras[index].uniqueId === uniqueId) {
  8885. return this.cameras[index];
  8886. }
  8887. }
  8888. return null;
  8889. };
  8890. /**
  8891. * get a camera using its name
  8892. * @param {string} the camera's name
  8893. * @return {BABYLON.Camera|null} the camera or null if none found.
  8894. */
  8895. Scene.prototype.getCameraByName = function (name) {
  8896. for (var index = 0; index < this.cameras.length; index++) {
  8897. if (this.cameras[index].name === name) {
  8898. return this.cameras[index];
  8899. }
  8900. }
  8901. return null;
  8902. };
  8903. /**
  8904. * get a light node using its name
  8905. * @param {string} the light's name
  8906. * @return {BABYLON.Light|null} the light or null if none found.
  8907. */
  8908. Scene.prototype.getLightByName = function (name) {
  8909. for (var index = 0; index < this.lights.length; index++) {
  8910. if (this.lights[index].name === name) {
  8911. return this.lights[index];
  8912. }
  8913. }
  8914. return null;
  8915. };
  8916. /**
  8917. * get a light node using its ID
  8918. * @param {string} the light's id
  8919. * @return {BABYLON.Light|null} the light or null if none found.
  8920. */
  8921. Scene.prototype.getLightByID = function (id) {
  8922. for (var index = 0; index < this.lights.length; index++) {
  8923. if (this.lights[index].id === id) {
  8924. return this.lights[index];
  8925. }
  8926. }
  8927. return null;
  8928. };
  8929. /**
  8930. * get a light node using its scene-generated unique ID
  8931. * @param {number} the light's unique id
  8932. * @return {BABYLON.Light|null} the light or null if none found.
  8933. */
  8934. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8935. for (var index = 0; index < this.lights.length; index++) {
  8936. if (this.lights[index].uniqueId === uniqueId) {
  8937. return this.lights[index];
  8938. }
  8939. }
  8940. return null;
  8941. };
  8942. /**
  8943. * get a geometry using its ID
  8944. * @param {string} the geometry's id
  8945. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8946. */
  8947. Scene.prototype.getGeometryByID = function (id) {
  8948. for (var index = 0; index < this._geometries.length; index++) {
  8949. if (this._geometries[index].id === id) {
  8950. return this._geometries[index];
  8951. }
  8952. }
  8953. return null;
  8954. };
  8955. /**
  8956. * add a new geometry to this scene.
  8957. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8958. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8959. * @return {boolean} was the geometry added or not
  8960. */
  8961. Scene.prototype.pushGeometry = function (geometry, force) {
  8962. if (!force && this.getGeometryByID(geometry.id)) {
  8963. return false;
  8964. }
  8965. this._geometries.push(geometry);
  8966. if (this.onGeometryAdded) {
  8967. this.onGeometryAdded(geometry);
  8968. }
  8969. return true;
  8970. };
  8971. /**
  8972. * Removes an existing geometry
  8973. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  8974. * @return {boolean} was the geometry removed or not
  8975. */
  8976. Scene.prototype.removeGeometry = function (geometry) {
  8977. var index = this._geometries.indexOf(geometry);
  8978. if (index > -1) {
  8979. this._geometries.splice(index, 1);
  8980. if (this.onGeometryRemoved) {
  8981. this.onGeometryRemoved(geometry);
  8982. }
  8983. return true;
  8984. }
  8985. return false;
  8986. };
  8987. Scene.prototype.getGeometries = function () {
  8988. return this._geometries;
  8989. };
  8990. /**
  8991. * Get the first added mesh found of a given ID
  8992. * @param {string} id - the id to search for
  8993. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8994. */
  8995. Scene.prototype.getMeshByID = function (id) {
  8996. for (var index = 0; index < this.meshes.length; index++) {
  8997. if (this.meshes[index].id === id) {
  8998. return this.meshes[index];
  8999. }
  9000. }
  9001. return null;
  9002. };
  9003. /**
  9004. * Get a mesh with its auto-generated unique id
  9005. * @param {number} uniqueId - the unique id to search for
  9006. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  9007. */
  9008. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  9009. for (var index = 0; index < this.meshes.length; index++) {
  9010. if (this.meshes[index].uniqueId === uniqueId) {
  9011. return this.meshes[index];
  9012. }
  9013. }
  9014. return null;
  9015. };
  9016. /**
  9017. * Get a the last added mesh found of a given ID
  9018. * @param {string} id - the id to search for
  9019. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  9020. */
  9021. Scene.prototype.getLastMeshByID = function (id) {
  9022. for (var index = this.meshes.length - 1; index >= 0; index--) {
  9023. if (this.meshes[index].id === id) {
  9024. return this.meshes[index];
  9025. }
  9026. }
  9027. return null;
  9028. };
  9029. /**
  9030. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  9031. * @param {string} id - the id to search for
  9032. * @return {BABYLON.Node|null} the node found or null if not found at all.
  9033. */
  9034. Scene.prototype.getLastEntryByID = function (id) {
  9035. for (var index = this.meshes.length - 1; index >= 0; index--) {
  9036. if (this.meshes[index].id === id) {
  9037. return this.meshes[index];
  9038. }
  9039. }
  9040. for (index = this.cameras.length - 1; index >= 0; index--) {
  9041. if (this.cameras[index].id === id) {
  9042. return this.cameras[index];
  9043. }
  9044. }
  9045. for (index = this.lights.length - 1; index >= 0; index--) {
  9046. if (this.lights[index].id === id) {
  9047. return this.lights[index];
  9048. }
  9049. }
  9050. return null;
  9051. };
  9052. Scene.prototype.getNodeByName = function (name) {
  9053. var mesh = this.getMeshByName(name);
  9054. if (mesh) {
  9055. return mesh;
  9056. }
  9057. var light = this.getLightByName(name);
  9058. if (light) {
  9059. return light;
  9060. }
  9061. return this.getCameraByName(name);
  9062. };
  9063. Scene.prototype.getMeshByName = function (name) {
  9064. for (var index = 0; index < this.meshes.length; index++) {
  9065. if (this.meshes[index].name === name) {
  9066. return this.meshes[index];
  9067. }
  9068. }
  9069. return null;
  9070. };
  9071. Scene.prototype.getSoundByName = function (name) {
  9072. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  9073. if (this.mainSoundTrack.soundCollection[index].name === name) {
  9074. return this.mainSoundTrack.soundCollection[index];
  9075. }
  9076. }
  9077. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  9078. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  9079. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  9080. return this.soundTracks[sdIndex].soundCollection[index];
  9081. }
  9082. }
  9083. }
  9084. return null;
  9085. };
  9086. Scene.prototype.getLastSkeletonByID = function (id) {
  9087. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  9088. if (this.skeletons[index].id === id) {
  9089. return this.skeletons[index];
  9090. }
  9091. }
  9092. return null;
  9093. };
  9094. Scene.prototype.getSkeletonById = function (id) {
  9095. for (var index = 0; index < this.skeletons.length; index++) {
  9096. if (this.skeletons[index].id === id) {
  9097. return this.skeletons[index];
  9098. }
  9099. }
  9100. return null;
  9101. };
  9102. Scene.prototype.getSkeletonByName = function (name) {
  9103. for (var index = 0; index < this.skeletons.length; index++) {
  9104. if (this.skeletons[index].name === name) {
  9105. return this.skeletons[index];
  9106. }
  9107. }
  9108. return null;
  9109. };
  9110. Scene.prototype.isActiveMesh = function (mesh) {
  9111. return (this._activeMeshes.indexOf(mesh) !== -1);
  9112. };
  9113. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9114. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9115. var material = subMesh.getMaterial();
  9116. if (mesh.showSubMeshesBoundingBox) {
  9117. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9118. }
  9119. if (material) {
  9120. // Render targets
  9121. if (material.getRenderTargetTextures) {
  9122. if (this._processedMaterials.indexOf(material) === -1) {
  9123. this._processedMaterials.push(material);
  9124. this._renderTargets.concat(material.getRenderTargetTextures());
  9125. }
  9126. }
  9127. // Dispatch
  9128. this._activeIndices += subMesh.indexCount;
  9129. this._renderingManager.dispatch(subMesh);
  9130. }
  9131. }
  9132. };
  9133. Scene.prototype._evaluateActiveMeshes = function () {
  9134. this.activeCamera._activeMeshes.reset();
  9135. this._activeMeshes.reset();
  9136. this._renderingManager.reset();
  9137. this._processedMaterials.reset();
  9138. this._activeParticleSystems.reset();
  9139. this._activeSkeletons.reset();
  9140. this._boundingBoxRenderer.reset();
  9141. if (!this._frustumPlanes) {
  9142. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9143. }
  9144. else {
  9145. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9146. }
  9147. // Meshes
  9148. var meshes;
  9149. var len;
  9150. if (this._selectionOctree) {
  9151. var selection = this._selectionOctree.select(this._frustumPlanes);
  9152. meshes = selection.data;
  9153. len = selection.length;
  9154. }
  9155. else {
  9156. len = this.meshes.length;
  9157. meshes = this.meshes;
  9158. }
  9159. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9160. var mesh = meshes[meshIndex];
  9161. if (mesh.isBlocked) {
  9162. continue;
  9163. }
  9164. this._totalVertices += mesh.getTotalVertices();
  9165. if (!mesh.isReady()) {
  9166. continue;
  9167. }
  9168. mesh.computeWorldMatrix();
  9169. // Intersections
  9170. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9171. this._meshesForIntersections.pushNoDuplicate(mesh);
  9172. }
  9173. // Switch to current LOD
  9174. var meshLOD = mesh.getLOD(this.activeCamera);
  9175. if (!meshLOD) {
  9176. continue;
  9177. }
  9178. mesh._preActivate();
  9179. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9180. this._activeMeshes.push(mesh);
  9181. this.activeCamera._activeMeshes.push(mesh);
  9182. mesh._activate(this._renderId);
  9183. this._activeMesh(meshLOD);
  9184. }
  9185. }
  9186. // Particle systems
  9187. var beforeParticlesDate = BABYLON.Tools.Now;
  9188. if (this.particlesEnabled) {
  9189. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9190. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9191. var particleSystem = this.particleSystems[particleIndex];
  9192. if (!particleSystem.isStarted()) {
  9193. continue;
  9194. }
  9195. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9196. this._activeParticleSystems.push(particleSystem);
  9197. particleSystem.animate();
  9198. }
  9199. }
  9200. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9201. }
  9202. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9203. };
  9204. Scene.prototype._activeMesh = function (mesh) {
  9205. if (mesh.skeleton && this.skeletonsEnabled) {
  9206. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9207. }
  9208. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9209. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9210. }
  9211. if (mesh && mesh.subMeshes) {
  9212. // Submeshes Octrees
  9213. var len;
  9214. var subMeshes;
  9215. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9216. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9217. len = intersections.length;
  9218. subMeshes = intersections.data;
  9219. }
  9220. else {
  9221. subMeshes = mesh.subMeshes;
  9222. len = subMeshes.length;
  9223. }
  9224. for (var subIndex = 0; subIndex < len; subIndex++) {
  9225. var subMesh = subMeshes[subIndex];
  9226. this._evaluateSubMesh(subMesh, mesh);
  9227. }
  9228. }
  9229. };
  9230. Scene.prototype.updateTransformMatrix = function (force) {
  9231. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9232. };
  9233. Scene.prototype._renderForCamera = function (camera) {
  9234. var engine = this._engine;
  9235. this.activeCamera = camera;
  9236. if (!this.activeCamera)
  9237. throw new Error("Active camera not set");
  9238. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9239. // Viewport
  9240. engine.setViewport(this.activeCamera.viewport);
  9241. // Camera
  9242. this._renderId++;
  9243. this.updateTransformMatrix();
  9244. if (this.beforeCameraRender) {
  9245. this.beforeCameraRender(this.activeCamera);
  9246. }
  9247. // Meshes
  9248. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9249. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9250. this._evaluateActiveMeshes();
  9251. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9252. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9253. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9254. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9255. skeleton.prepare();
  9256. }
  9257. // Render targets
  9258. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9259. if (this.renderTargetsEnabled) {
  9260. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9261. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9262. var renderTarget = this._renderTargets.data[renderIndex];
  9263. if (renderTarget._shouldRender()) {
  9264. this._renderId++;
  9265. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9266. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9267. }
  9268. }
  9269. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9270. this._renderId++;
  9271. }
  9272. if (this._renderTargets.length > 0) {
  9273. engine.restoreDefaultFramebuffer();
  9274. }
  9275. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9276. // Prepare Frame
  9277. this.postProcessManager._prepareFrame();
  9278. var beforeRenderDate = BABYLON.Tools.Now;
  9279. // Backgrounds
  9280. if (this.layers.length) {
  9281. engine.setDepthBuffer(false);
  9282. var layerIndex;
  9283. var layer;
  9284. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9285. layer = this.layers[layerIndex];
  9286. if (layer.isBackground) {
  9287. layer.render();
  9288. }
  9289. }
  9290. engine.setDepthBuffer(true);
  9291. }
  9292. // Render
  9293. BABYLON.Tools.StartPerformanceCounter("Main render");
  9294. this._renderingManager.render(null, null, true, true);
  9295. BABYLON.Tools.EndPerformanceCounter("Main render");
  9296. // Bounding boxes
  9297. this._boundingBoxRenderer.render();
  9298. // Lens flares
  9299. if (this.lensFlaresEnabled) {
  9300. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9301. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9302. this.lensFlareSystems[lensFlareSystemIndex].render();
  9303. }
  9304. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9305. }
  9306. // Foregrounds
  9307. if (this.layers.length) {
  9308. engine.setDepthBuffer(false);
  9309. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9310. layer = this.layers[layerIndex];
  9311. if (!layer.isBackground) {
  9312. layer.render();
  9313. }
  9314. }
  9315. engine.setDepthBuffer(true);
  9316. }
  9317. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9318. // Finalize frame
  9319. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9320. // Update camera
  9321. this.activeCamera._updateFromScene();
  9322. // Reset some special arrays
  9323. this._renderTargets.reset();
  9324. if (this.afterCameraRender) {
  9325. this.afterCameraRender(this.activeCamera);
  9326. }
  9327. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9328. };
  9329. Scene.prototype._processSubCameras = function (camera) {
  9330. if (camera.subCameras.length === 0) {
  9331. this._renderForCamera(camera);
  9332. return;
  9333. }
  9334. for (var index = 0; index < camera.subCameras.length; index++) {
  9335. this._renderForCamera(camera.subCameras[index]);
  9336. }
  9337. this.activeCamera = camera;
  9338. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9339. // Update camera
  9340. this.activeCamera._updateFromScene();
  9341. };
  9342. Scene.prototype._checkIntersections = function () {
  9343. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9344. var sourceMesh = this._meshesForIntersections.data[index];
  9345. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9346. var action = sourceMesh.actionManager.actions[actionIndex];
  9347. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9348. var parameters = action.getTriggerParameter();
  9349. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9350. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9351. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9352. if (areIntersecting && currentIntersectionInProgress === -1) {
  9353. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9354. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9355. sourceMesh._intersectionsInProgress.push(otherMesh);
  9356. }
  9357. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9358. sourceMesh._intersectionsInProgress.push(otherMesh);
  9359. }
  9360. }
  9361. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9362. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9363. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9364. if (indexOfOther > -1) {
  9365. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9366. }
  9367. }
  9368. }
  9369. }
  9370. }
  9371. };
  9372. Scene.prototype.render = function () {
  9373. var startDate = BABYLON.Tools.Now;
  9374. this._particlesDuration = 0;
  9375. this._spritesDuration = 0;
  9376. this._activeParticles = 0;
  9377. this._renderDuration = 0;
  9378. this._renderTargetsDuration = 0;
  9379. this._evaluateActiveMeshesDuration = 0;
  9380. this._totalVertices = 0;
  9381. this._activeIndices = 0;
  9382. this._activeBones = 0;
  9383. this.getEngine().resetDrawCalls();
  9384. this._meshesForIntersections.reset();
  9385. this.resetCachedMaterial();
  9386. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9387. // Actions
  9388. if (this.actionManager) {
  9389. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9390. }
  9391. //Simplification Queue
  9392. if (!this.simplificationQueue.running) {
  9393. this.simplificationQueue.executeNext();
  9394. }
  9395. // Before render
  9396. if (this.beforeRender) {
  9397. this.beforeRender();
  9398. }
  9399. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9400. this._onBeforeRenderCallbacks[callbackIndex]();
  9401. }
  9402. // Animations
  9403. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9404. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9405. this._animate();
  9406. // Physics
  9407. if (this._physicsEngine) {
  9408. BABYLON.Tools.StartPerformanceCounter("Physics");
  9409. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9410. BABYLON.Tools.EndPerformanceCounter("Physics");
  9411. }
  9412. // Customs render targets
  9413. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9414. var engine = this.getEngine();
  9415. var currentActiveCamera = this.activeCamera;
  9416. if (this.renderTargetsEnabled) {
  9417. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9418. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9419. var renderTarget = this.customRenderTargets[customIndex];
  9420. if (renderTarget._shouldRender()) {
  9421. this._renderId++;
  9422. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9423. if (!this.activeCamera)
  9424. throw new Error("Active camera not set");
  9425. // Viewport
  9426. engine.setViewport(this.activeCamera.viewport);
  9427. // Camera
  9428. this.updateTransformMatrix();
  9429. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9430. }
  9431. }
  9432. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9433. this._renderId++;
  9434. }
  9435. if (this.customRenderTargets.length > 0) {
  9436. engine.restoreDefaultFramebuffer();
  9437. }
  9438. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9439. this.activeCamera = currentActiveCamera;
  9440. // Procedural textures
  9441. if (this.proceduralTexturesEnabled) {
  9442. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9443. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9444. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9445. if (proceduralTexture._shouldRender()) {
  9446. proceduralTexture.render();
  9447. }
  9448. }
  9449. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9450. }
  9451. // Clear
  9452. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9453. // Shadows
  9454. if (this.shadowsEnabled) {
  9455. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9456. var light = this.lights[lightIndex];
  9457. var shadowGenerator = light.getShadowGenerator();
  9458. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9459. this._renderTargets.push(shadowGenerator.getShadowMap());
  9460. }
  9461. }
  9462. }
  9463. // Depth renderer
  9464. if (this._depthRenderer) {
  9465. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9466. }
  9467. // RenderPipeline
  9468. this.postProcessRenderPipelineManager.update();
  9469. // Multi-cameras?
  9470. if (this.activeCameras.length > 0) {
  9471. var currentRenderId = this._renderId;
  9472. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9473. this._renderId = currentRenderId;
  9474. this._processSubCameras(this.activeCameras[cameraIndex]);
  9475. }
  9476. }
  9477. else {
  9478. if (!this.activeCamera) {
  9479. throw new Error("No camera defined");
  9480. }
  9481. this._processSubCameras(this.activeCamera);
  9482. }
  9483. // Intersection checks
  9484. this._checkIntersections();
  9485. // Update the audio listener attached to the camera
  9486. this._updateAudioParameters();
  9487. // After render
  9488. if (this.afterRender) {
  9489. this.afterRender();
  9490. }
  9491. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9492. this._onAfterRenderCallbacks[callbackIndex]();
  9493. }
  9494. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9495. this._toBeDisposed.data[index].dispose();
  9496. this._toBeDisposed[index] = null;
  9497. }
  9498. this._toBeDisposed.reset();
  9499. if (this.dumpNextRenderTargets) {
  9500. this.dumpNextRenderTargets = false;
  9501. }
  9502. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9503. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9504. };
  9505. Scene.prototype._updateAudioParameters = function () {
  9506. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9507. return;
  9508. }
  9509. var listeningCamera;
  9510. var audioEngine = BABYLON.Engine.audioEngine;
  9511. if (this.activeCameras.length > 0) {
  9512. listeningCamera = this.activeCameras[0];
  9513. }
  9514. else {
  9515. listeningCamera = this.activeCamera;
  9516. }
  9517. if (listeningCamera && audioEngine.canUseWebAudio) {
  9518. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9519. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9520. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9521. cameraDirection.normalize();
  9522. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9523. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9524. var sound = this.mainSoundTrack.soundCollection[i];
  9525. if (sound.useCustomAttenuation) {
  9526. sound.updateDistanceFromListener();
  9527. }
  9528. }
  9529. for (i = 0; i < this.soundTracks.length; i++) {
  9530. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9531. sound = this.soundTracks[i].soundCollection[j];
  9532. if (sound.useCustomAttenuation) {
  9533. sound.updateDistanceFromListener();
  9534. }
  9535. }
  9536. }
  9537. }
  9538. };
  9539. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9540. // Audio
  9541. get: function () {
  9542. return this._audioEnabled;
  9543. },
  9544. set: function (value) {
  9545. this._audioEnabled = value;
  9546. if (this._audioEnabled) {
  9547. this._enableAudio();
  9548. }
  9549. else {
  9550. this._disableAudio();
  9551. }
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Scene.prototype._disableAudio = function () {
  9557. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9558. this.mainSoundTrack.soundCollection[i].pause();
  9559. }
  9560. for (i = 0; i < this.soundTracks.length; i++) {
  9561. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9562. this.soundTracks[i].soundCollection[j].pause();
  9563. }
  9564. }
  9565. };
  9566. Scene.prototype._enableAudio = function () {
  9567. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9568. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9569. this.mainSoundTrack.soundCollection[i].play();
  9570. }
  9571. }
  9572. for (i = 0; i < this.soundTracks.length; i++) {
  9573. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9574. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9575. this.soundTracks[i].soundCollection[j].play();
  9576. }
  9577. }
  9578. }
  9579. };
  9580. Object.defineProperty(Scene.prototype, "headphone", {
  9581. get: function () {
  9582. return this._headphone;
  9583. },
  9584. set: function (value) {
  9585. this._headphone = value;
  9586. if (this._headphone) {
  9587. this._switchAudioModeForHeadphones();
  9588. }
  9589. else {
  9590. this._switchAudioModeForNormalSpeakers();
  9591. }
  9592. },
  9593. enumerable: true,
  9594. configurable: true
  9595. });
  9596. Scene.prototype._switchAudioModeForHeadphones = function () {
  9597. this.mainSoundTrack.switchPanningModelToHRTF();
  9598. for (var i = 0; i < this.soundTracks.length; i++) {
  9599. this.soundTracks[i].switchPanningModelToHRTF();
  9600. }
  9601. };
  9602. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9603. this.mainSoundTrack.switchPanningModelToEqualPower();
  9604. for (var i = 0; i < this.soundTracks.length; i++) {
  9605. this.soundTracks[i].switchPanningModelToEqualPower();
  9606. }
  9607. };
  9608. Scene.prototype.enableDepthRenderer = function () {
  9609. if (this._depthRenderer) {
  9610. return this._depthRenderer;
  9611. }
  9612. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9613. return this._depthRenderer;
  9614. };
  9615. Scene.prototype.disableDepthRenderer = function () {
  9616. if (!this._depthRenderer) {
  9617. return;
  9618. }
  9619. this._depthRenderer.dispose();
  9620. this._depthRenderer = null;
  9621. };
  9622. Scene.prototype.dispose = function () {
  9623. this.beforeRender = null;
  9624. this.afterRender = null;
  9625. this.skeletons = [];
  9626. this._boundingBoxRenderer.dispose();
  9627. if (this._depthRenderer) {
  9628. this._depthRenderer.dispose();
  9629. }
  9630. // Debug layer
  9631. this.debugLayer.hide();
  9632. // Events
  9633. if (this.onDispose) {
  9634. this.onDispose();
  9635. }
  9636. this._onBeforeRenderCallbacks = [];
  9637. this._onAfterRenderCallbacks = [];
  9638. this.detachControl();
  9639. // Release sounds & sounds tracks
  9640. this.disposeSounds();
  9641. // Detach cameras
  9642. var canvas = this._engine.getRenderingCanvas();
  9643. var index;
  9644. for (index = 0; index < this.cameras.length; index++) {
  9645. this.cameras[index].detachControl(canvas);
  9646. }
  9647. while (this.lights.length) {
  9648. this.lights[0].dispose();
  9649. }
  9650. while (this.meshes.length) {
  9651. this.meshes[0].dispose(true);
  9652. }
  9653. while (this.cameras.length) {
  9654. this.cameras[0].dispose();
  9655. }
  9656. while (this.materials.length) {
  9657. this.materials[0].dispose();
  9658. }
  9659. while (this.particleSystems.length) {
  9660. this.particleSystems[0].dispose();
  9661. }
  9662. while (this.spriteManagers.length) {
  9663. this.spriteManagers[0].dispose();
  9664. }
  9665. while (this.layers.length) {
  9666. this.layers[0].dispose();
  9667. }
  9668. while (this.textures.length) {
  9669. this.textures[0].dispose();
  9670. }
  9671. // Post-processes
  9672. this.postProcessManager.dispose();
  9673. // Physics
  9674. if (this._physicsEngine) {
  9675. this.disablePhysicsEngine();
  9676. }
  9677. // Remove from engine
  9678. index = this._engine.scenes.indexOf(this);
  9679. if (index > -1) {
  9680. this._engine.scenes.splice(index, 1);
  9681. }
  9682. this._engine.wipeCaches();
  9683. };
  9684. // Release sounds & sounds tracks
  9685. Scene.prototype.disposeSounds = function () {
  9686. this.mainSoundTrack.dispose();
  9687. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9688. this.soundTracks[scIndex].dispose();
  9689. }
  9690. };
  9691. // Collisions
  9692. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9693. if (excludedMesh === void 0) { excludedMesh = null; }
  9694. position.divideToRef(collider.radius, this._scaledPosition);
  9695. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9696. collider.retry = 0;
  9697. collider.initialVelocity = this._scaledVelocity;
  9698. collider.initialPosition = this._scaledPosition;
  9699. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9700. finalPosition.multiplyInPlace(collider.radius);
  9701. };
  9702. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9703. if (excludedMesh === void 0) { excludedMesh = null; }
  9704. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9705. if (collider.retry >= maximumRetry) {
  9706. finalPosition.copyFrom(position);
  9707. return;
  9708. }
  9709. collider._initialize(position, velocity, closeDistance);
  9710. for (var index = 0; index < this.meshes.length; index++) {
  9711. var mesh = this.meshes[index];
  9712. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9713. mesh._checkCollision(collider);
  9714. }
  9715. }
  9716. if (!collider.collisionFound) {
  9717. position.addToRef(velocity, finalPosition);
  9718. return;
  9719. }
  9720. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9721. collider._getResponse(position, velocity);
  9722. }
  9723. if (velocity.length() <= closeDistance) {
  9724. finalPosition.copyFrom(position);
  9725. return;
  9726. }
  9727. collider.retry++;
  9728. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9729. };
  9730. // Octrees
  9731. Scene.prototype.getWorldExtends = function () {
  9732. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9733. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9734. for (var index = 0; index < this.meshes.length; index++) {
  9735. var mesh = this.meshes[index];
  9736. mesh.computeWorldMatrix(true);
  9737. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9738. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9739. BABYLON.Tools.CheckExtends(minBox, min, max);
  9740. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9741. }
  9742. return {
  9743. min: min,
  9744. max: max
  9745. };
  9746. };
  9747. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9748. if (maxCapacity === void 0) { maxCapacity = 64; }
  9749. if (maxDepth === void 0) { maxDepth = 2; }
  9750. if (!this._selectionOctree) {
  9751. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9752. }
  9753. var worldExtends = this.getWorldExtends();
  9754. // Update octree
  9755. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9756. return this._selectionOctree;
  9757. };
  9758. // Picking
  9759. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9760. var engine = this._engine;
  9761. if (!camera) {
  9762. if (!this.activeCamera)
  9763. throw new Error("Active camera not set");
  9764. camera = this.activeCamera;
  9765. }
  9766. var cameraViewport = camera.viewport;
  9767. var viewport = cameraViewport.toGlobal(engine);
  9768. // Moving coordinates to local viewport world
  9769. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9770. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9771. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9772. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9773. };
  9774. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9775. var pickingInfo = null;
  9776. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9777. var mesh = this.meshes[meshIndex];
  9778. if (predicate) {
  9779. if (!predicate(mesh)) {
  9780. continue;
  9781. }
  9782. }
  9783. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9784. continue;
  9785. }
  9786. var world = mesh.getWorldMatrix();
  9787. var ray = rayFunction(world);
  9788. var result = mesh.intersects(ray, fastCheck);
  9789. if (!result || !result.hit)
  9790. continue;
  9791. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9792. continue;
  9793. pickingInfo = result;
  9794. if (fastCheck) {
  9795. break;
  9796. }
  9797. }
  9798. return pickingInfo || new BABYLON.PickingInfo();
  9799. };
  9800. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9801. var _this = this;
  9802. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9803. /// <param name="x">X position on screen</param>
  9804. /// <param name="y">Y position on screen</param>
  9805. /// <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>
  9806. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9807. /// <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>
  9808. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9809. };
  9810. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9811. var _this = this;
  9812. return this._internalPick(function (world) {
  9813. if (!_this._pickWithRayInverseMatrix) {
  9814. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9815. }
  9816. world.invertToRef(_this._pickWithRayInverseMatrix);
  9817. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9818. }, predicate, fastCheck);
  9819. };
  9820. Scene.prototype.setPointerOverMesh = function (mesh) {
  9821. if (this._pointerOverMesh === mesh) {
  9822. return;
  9823. }
  9824. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9825. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9826. }
  9827. this._pointerOverMesh = mesh;
  9828. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9829. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9830. }
  9831. };
  9832. Scene.prototype.getPointerOverMesh = function () {
  9833. return this._pointerOverMesh;
  9834. };
  9835. // Physics
  9836. Scene.prototype.getPhysicsEngine = function () {
  9837. return this._physicsEngine;
  9838. };
  9839. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9840. if (this._physicsEngine) {
  9841. return true;
  9842. }
  9843. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9844. if (!this._physicsEngine.isSupported()) {
  9845. this._physicsEngine = null;
  9846. return false;
  9847. }
  9848. this._physicsEngine._initialize(gravity);
  9849. return true;
  9850. };
  9851. Scene.prototype.disablePhysicsEngine = function () {
  9852. if (!this._physicsEngine) {
  9853. return;
  9854. }
  9855. this._physicsEngine.dispose();
  9856. this._physicsEngine = undefined;
  9857. };
  9858. Scene.prototype.isPhysicsEnabled = function () {
  9859. return this._physicsEngine !== undefined;
  9860. };
  9861. Scene.prototype.setGravity = function (gravity) {
  9862. if (!this._physicsEngine) {
  9863. return;
  9864. }
  9865. this._physicsEngine._setGravity(gravity);
  9866. };
  9867. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9868. if (parts.parts) {
  9869. options = parts;
  9870. parts = parts.parts;
  9871. }
  9872. if (!this._physicsEngine) {
  9873. return null;
  9874. }
  9875. for (var index = 0; index < parts.length; index++) {
  9876. var mesh = parts[index].mesh;
  9877. mesh._physicImpostor = parts[index].impostor;
  9878. mesh._physicsMass = options.mass / parts.length;
  9879. mesh._physicsFriction = options.friction;
  9880. mesh._physicRestitution = options.restitution;
  9881. }
  9882. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9883. };
  9884. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9885. for (var index = 0; index < compound.parts.length; index++) {
  9886. var mesh = compound.parts[index].mesh;
  9887. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9888. this._physicsEngine._unregisterMesh(mesh);
  9889. }
  9890. };
  9891. // Misc.
  9892. Scene.prototype.createDefaultCameraOrLight = function () {
  9893. // Light
  9894. if (this.lights.length === 0) {
  9895. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9896. }
  9897. // Camera
  9898. if (!this.activeCamera) {
  9899. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9900. // Compute position
  9901. var worldExtends = this.getWorldExtends();
  9902. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9903. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9904. camera.setTarget(worldCenter);
  9905. this.activeCamera = camera;
  9906. }
  9907. };
  9908. // Tags
  9909. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9910. if (tagsQuery === undefined) {
  9911. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9912. return list;
  9913. }
  9914. var listByTags = [];
  9915. forEach = forEach || (function (item) {
  9916. return;
  9917. });
  9918. for (var i in list) {
  9919. var item = list[i];
  9920. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9921. listByTags.push(item);
  9922. forEach(item);
  9923. }
  9924. }
  9925. return listByTags;
  9926. };
  9927. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9928. return this._getByTags(this.meshes, tagsQuery, forEach);
  9929. };
  9930. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9931. return this._getByTags(this.cameras, tagsQuery, forEach);
  9932. };
  9933. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9934. return this._getByTags(this.lights, tagsQuery, forEach);
  9935. };
  9936. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9937. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9938. };
  9939. // Statics
  9940. Scene._FOGMODE_NONE = 0;
  9941. Scene._FOGMODE_EXP = 1;
  9942. Scene._FOGMODE_EXP2 = 2;
  9943. Scene._FOGMODE_LINEAR = 3;
  9944. Scene.MinDeltaTime = 1.0;
  9945. Scene.MaxDeltaTime = 1000.0;
  9946. return Scene;
  9947. })();
  9948. BABYLON.Scene = Scene;
  9949. })(BABYLON || (BABYLON = {}));
  9950. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9951. (function (BABYLON) {
  9952. var VertexBuffer = (function () {
  9953. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9954. if (engine instanceof BABYLON.Mesh) {
  9955. this._engine = engine.getScene().getEngine();
  9956. }
  9957. else {
  9958. this._engine = engine;
  9959. }
  9960. this._updatable = updatable;
  9961. this._data = data;
  9962. if (!postponeInternalCreation) {
  9963. this.create();
  9964. }
  9965. this._kind = kind;
  9966. if (stride) {
  9967. this._strideSize = stride;
  9968. return;
  9969. }
  9970. switch (kind) {
  9971. case VertexBuffer.PositionKind:
  9972. this._strideSize = 3;
  9973. break;
  9974. case VertexBuffer.NormalKind:
  9975. this._strideSize = 3;
  9976. break;
  9977. case VertexBuffer.UVKind:
  9978. this._strideSize = 2;
  9979. break;
  9980. case VertexBuffer.UV2Kind:
  9981. this._strideSize = 2;
  9982. break;
  9983. case VertexBuffer.ColorKind:
  9984. this._strideSize = 4;
  9985. break;
  9986. case VertexBuffer.MatricesIndicesKind:
  9987. this._strideSize = 4;
  9988. break;
  9989. case VertexBuffer.MatricesWeightsKind:
  9990. this._strideSize = 4;
  9991. break;
  9992. }
  9993. }
  9994. // Properties
  9995. VertexBuffer.prototype.isUpdatable = function () {
  9996. return this._updatable;
  9997. };
  9998. VertexBuffer.prototype.getData = function () {
  9999. return this._data;
  10000. };
  10001. VertexBuffer.prototype.getBuffer = function () {
  10002. return this._buffer;
  10003. };
  10004. VertexBuffer.prototype.getStrideSize = function () {
  10005. return this._strideSize;
  10006. };
  10007. // Methods
  10008. VertexBuffer.prototype.create = function (data) {
  10009. if (!data && this._buffer) {
  10010. return; // nothing to do
  10011. }
  10012. data = data || this._data;
  10013. if (!this._buffer) {
  10014. if (this._updatable) {
  10015. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  10016. }
  10017. else {
  10018. this._buffer = this._engine.createVertexBuffer(data);
  10019. }
  10020. }
  10021. if (this._updatable) {
  10022. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  10023. this._data = data;
  10024. }
  10025. };
  10026. VertexBuffer.prototype.update = function (data) {
  10027. this.create(data);
  10028. };
  10029. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  10030. if (!this._buffer) {
  10031. return;
  10032. }
  10033. if (this._updatable) {
  10034. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  10035. this._data = null;
  10036. }
  10037. };
  10038. VertexBuffer.prototype.dispose = function () {
  10039. if (!this._buffer) {
  10040. return;
  10041. }
  10042. if (this._engine._releaseBuffer(this._buffer)) {
  10043. this._buffer = null;
  10044. }
  10045. };
  10046. Object.defineProperty(VertexBuffer, "PositionKind", {
  10047. get: function () {
  10048. return VertexBuffer._PositionKind;
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(VertexBuffer, "NormalKind", {
  10054. get: function () {
  10055. return VertexBuffer._NormalKind;
  10056. },
  10057. enumerable: true,
  10058. configurable: true
  10059. });
  10060. Object.defineProperty(VertexBuffer, "UVKind", {
  10061. get: function () {
  10062. return VertexBuffer._UVKind;
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. Object.defineProperty(VertexBuffer, "UV2Kind", {
  10068. get: function () {
  10069. return VertexBuffer._UV2Kind;
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. Object.defineProperty(VertexBuffer, "ColorKind", {
  10075. get: function () {
  10076. return VertexBuffer._ColorKind;
  10077. },
  10078. enumerable: true,
  10079. configurable: true
  10080. });
  10081. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  10082. get: function () {
  10083. return VertexBuffer._MatricesIndicesKind;
  10084. },
  10085. enumerable: true,
  10086. configurable: true
  10087. });
  10088. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  10089. get: function () {
  10090. return VertexBuffer._MatricesWeightsKind;
  10091. },
  10092. enumerable: true,
  10093. configurable: true
  10094. });
  10095. // Enums
  10096. VertexBuffer._PositionKind = "position";
  10097. VertexBuffer._NormalKind = "normal";
  10098. VertexBuffer._UVKind = "uv";
  10099. VertexBuffer._UV2Kind = "uv2";
  10100. VertexBuffer._ColorKind = "color";
  10101. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  10102. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  10103. return VertexBuffer;
  10104. })();
  10105. BABYLON.VertexBuffer = VertexBuffer;
  10106. })(BABYLON || (BABYLON = {}));
  10107. //# sourceMappingURL=babylon.vertexBuffer.js.map
  10108. var BABYLON;
  10109. (function (BABYLON) {
  10110. var AbstractMesh = (function (_super) {
  10111. __extends(AbstractMesh, _super);
  10112. function AbstractMesh(name, scene) {
  10113. _super.call(this, name, scene);
  10114. // Properties
  10115. this.definedFacingForward = true; // orientation for POV movement & rotation
  10116. this.position = new BABYLON.Vector3(0, 0, 0);
  10117. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10118. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10119. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10120. this.visibility = 1.0;
  10121. this.alphaIndex = Number.MAX_VALUE;
  10122. this.infiniteDistance = false;
  10123. this.isVisible = true;
  10124. this.isPickable = true;
  10125. this.showBoundingBox = false;
  10126. this.showSubMeshesBoundingBox = false;
  10127. this.onDispose = null;
  10128. this.checkCollisions = false;
  10129. this.isBlocker = false;
  10130. this.renderingGroupId = 0;
  10131. this.receiveShadows = false;
  10132. this.renderOutline = false;
  10133. this.outlineColor = BABYLON.Color3.Red();
  10134. this.outlineWidth = 0.02;
  10135. this.renderOverlay = false;
  10136. this.overlayColor = BABYLON.Color3.Red();
  10137. this.overlayAlpha = 0.5;
  10138. this.hasVertexAlpha = false;
  10139. this.useVertexColors = true;
  10140. this.applyFog = true;
  10141. this.useOctreeForRenderingSelection = true;
  10142. this.useOctreeForPicking = true;
  10143. this.useOctreeForCollisions = true;
  10144. this.layerMask = 0x0FFFFFFF;
  10145. // Physics
  10146. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10147. // Collisions
  10148. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10149. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10150. this._collider = new BABYLON.Collider();
  10151. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10152. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10153. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10154. // Cache
  10155. this._localScaling = BABYLON.Matrix.Zero();
  10156. this._localRotation = BABYLON.Matrix.Zero();
  10157. this._localTranslation = BABYLON.Matrix.Zero();
  10158. this._localBillboard = BABYLON.Matrix.Zero();
  10159. this._localPivotScaling = BABYLON.Matrix.Zero();
  10160. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10161. this._localWorld = BABYLON.Matrix.Zero();
  10162. this._worldMatrix = BABYLON.Matrix.Zero();
  10163. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10164. this._absolutePosition = BABYLON.Vector3.Zero();
  10165. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10166. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10167. this._isDirty = false;
  10168. this._pivotMatrix = BABYLON.Matrix.Identity();
  10169. this._isDisposed = false;
  10170. this._renderId = 0;
  10171. this._intersectionsInProgress = new Array();
  10172. this._onAfterWorldMatrixUpdate = new Array();
  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.rotate = function (axis, amount, space) {
  10278. if (!this.rotationQuaternion) {
  10279. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10280. this.rotation = BABYLON.Vector3.Zero();
  10281. }
  10282. if (!space || space === 0 /* LOCAL */) {
  10283. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10284. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10285. }
  10286. else {
  10287. if (this.parent) {
  10288. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10289. invertParentWorldMatrix.invert();
  10290. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10291. }
  10292. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10293. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10294. }
  10295. };
  10296. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10297. var displacementVector = axis.scale(distance);
  10298. if (!space || space === 0 /* LOCAL */) {
  10299. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10300. this.setPositionWithLocalVector(tempV3);
  10301. }
  10302. else {
  10303. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10304. }
  10305. };
  10306. AbstractMesh.prototype.getAbsolutePosition = function () {
  10307. this.computeWorldMatrix();
  10308. return this._absolutePosition;
  10309. };
  10310. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10311. if (!absolutePosition) {
  10312. return;
  10313. }
  10314. var absolutePositionX;
  10315. var absolutePositionY;
  10316. var absolutePositionZ;
  10317. if (absolutePosition.x === undefined) {
  10318. if (arguments.length < 3) {
  10319. return;
  10320. }
  10321. absolutePositionX = arguments[0];
  10322. absolutePositionY = arguments[1];
  10323. absolutePositionZ = arguments[2];
  10324. }
  10325. else {
  10326. absolutePositionX = absolutePosition.x;
  10327. absolutePositionY = absolutePosition.y;
  10328. absolutePositionZ = absolutePosition.z;
  10329. }
  10330. if (this.parent) {
  10331. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10332. invertParentWorldMatrix.invert();
  10333. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10334. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10335. }
  10336. else {
  10337. this.position.x = absolutePositionX;
  10338. this.position.y = absolutePositionY;
  10339. this.position.z = absolutePositionZ;
  10340. }
  10341. };
  10342. // ================================== Point of View Movement =================================
  10343. /**
  10344. * Perform relative position change from the point of view of behind the front of the mesh.
  10345. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10346. * Supports definition of mesh facing forward or backward.
  10347. * @param {number} amountRight
  10348. * @param {number} amountUp
  10349. * @param {number} amountForward
  10350. */
  10351. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10352. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10353. };
  10354. /**
  10355. * Calculate relative position change from the point of view of behind the front of the mesh.
  10356. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10357. * Supports definition of mesh facing forward or backward.
  10358. * @param {number} amountRight
  10359. * @param {number} amountUp
  10360. * @param {number} amountForward
  10361. */
  10362. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10363. var rotMatrix = new BABYLON.Matrix();
  10364. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10365. rotQuaternion.toRotationMatrix(rotMatrix);
  10366. var translationDelta = BABYLON.Vector3.Zero();
  10367. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10368. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10369. return translationDelta;
  10370. };
  10371. // ================================== Point of View Rotation =================================
  10372. /**
  10373. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10374. * Supports definition of mesh facing forward or backward.
  10375. * @param {number} flipBack
  10376. * @param {number} twirlClockwise
  10377. * @param {number} tiltRight
  10378. */
  10379. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10380. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10381. };
  10382. /**
  10383. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10384. * Supports definition of mesh facing forward or backward.
  10385. * @param {number} flipBack
  10386. * @param {number} twirlClockwise
  10387. * @param {number} tiltRight
  10388. */
  10389. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10390. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10391. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10392. };
  10393. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10394. this._pivotMatrix = matrix;
  10395. this._cache.pivotMatrixUpdated = true;
  10396. };
  10397. AbstractMesh.prototype.getPivotMatrix = function () {
  10398. return this._pivotMatrix;
  10399. };
  10400. AbstractMesh.prototype._isSynchronized = function () {
  10401. if (this._isDirty) {
  10402. return false;
  10403. }
  10404. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10405. return false;
  10406. if (this._cache.pivotMatrixUpdated) {
  10407. return false;
  10408. }
  10409. if (this.infiniteDistance) {
  10410. return false;
  10411. }
  10412. if (!this._cache.position.equals(this.position))
  10413. return false;
  10414. if (this.rotationQuaternion) {
  10415. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10416. return false;
  10417. }
  10418. else {
  10419. if (!this._cache.rotation.equals(this.rotation))
  10420. return false;
  10421. }
  10422. if (!this._cache.scaling.equals(this.scaling))
  10423. return false;
  10424. return true;
  10425. };
  10426. AbstractMesh.prototype._initCache = function () {
  10427. _super.prototype._initCache.call(this);
  10428. this._cache.localMatrixUpdated = false;
  10429. this._cache.position = BABYLON.Vector3.Zero();
  10430. this._cache.scaling = BABYLON.Vector3.Zero();
  10431. this._cache.rotation = BABYLON.Vector3.Zero();
  10432. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10433. };
  10434. AbstractMesh.prototype.markAsDirty = function (property) {
  10435. if (property === "rotation") {
  10436. this.rotationQuaternion = null;
  10437. }
  10438. this._currentRenderId = Number.MAX_VALUE;
  10439. this._isDirty = true;
  10440. };
  10441. AbstractMesh.prototype._updateBoundingInfo = function () {
  10442. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10443. this._boundingInfo._update(this.worldMatrixFromCache);
  10444. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10445. };
  10446. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10447. if (!this.subMeshes) {
  10448. return;
  10449. }
  10450. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10451. var subMesh = this.subMeshes[subIndex];
  10452. subMesh.updateBoundingInfo(matrix);
  10453. }
  10454. };
  10455. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10456. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10457. return this._worldMatrix;
  10458. }
  10459. this._cache.position.copyFrom(this.position);
  10460. this._cache.scaling.copyFrom(this.scaling);
  10461. this._cache.pivotMatrixUpdated = false;
  10462. this._currentRenderId = this.getScene().getRenderId();
  10463. this._isDirty = false;
  10464. // Scaling
  10465. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10466. // Rotation
  10467. if (this.rotationQuaternion) {
  10468. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10469. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10470. }
  10471. else {
  10472. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10473. this._cache.rotation.copyFrom(this.rotation);
  10474. }
  10475. // Translation
  10476. if (this.infiniteDistance && !this.parent) {
  10477. var camera = this.getScene().activeCamera;
  10478. var cameraWorldMatrix = camera.getWorldMatrix();
  10479. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10480. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10481. }
  10482. else {
  10483. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10484. }
  10485. // Composing transformations
  10486. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10487. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10488. // Billboarding
  10489. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10490. var localPosition = this.position.clone();
  10491. var zero = this.getScene().activeCamera.globalPosition.clone();
  10492. if (this.parent && this.parent.position) {
  10493. localPosition.addInPlace(this.parent.position);
  10494. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10495. }
  10496. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  10497. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10498. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10499. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10500. zero.y = localPosition.y + 0.001;
  10501. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10502. zero.z = localPosition.z + 0.001;
  10503. }
  10504. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10505. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10506. this._localBillboard.invert();
  10507. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10508. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10509. }
  10510. // Local world
  10511. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10512. // Parent
  10513. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10514. this._markSyncedWithParent();
  10515. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10516. }
  10517. else {
  10518. this._worldMatrix.copyFrom(this._localWorld);
  10519. }
  10520. // Bounding info
  10521. this._updateBoundingInfo();
  10522. // Absolute position
  10523. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10524. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10525. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10526. }
  10527. return this._worldMatrix;
  10528. };
  10529. /**
  10530. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10531. * @param func: callback function to add
  10532. */
  10533. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10534. this._onAfterWorldMatrixUpdate.push(func);
  10535. };
  10536. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10537. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10538. if (index > -1) {
  10539. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10540. }
  10541. };
  10542. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10543. this.computeWorldMatrix();
  10544. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10545. };
  10546. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10547. this.computeWorldMatrix();
  10548. var invLocalWorldMatrix = this._localWorld.clone();
  10549. invLocalWorldMatrix.invert();
  10550. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10551. };
  10552. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10553. this.computeWorldMatrix();
  10554. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10555. };
  10556. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10557. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10558. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10559. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10560. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10561. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10562. /// <returns>Mesh oriented towards targetMesh</returns>
  10563. yawCor = yawCor || 0; // default to zero if undefined
  10564. pitchCor = pitchCor || 0;
  10565. rollCor = rollCor || 0;
  10566. var dv = targetPoint.subtract(this.position);
  10567. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10568. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10569. var pitch = Math.atan2(dv.y, len);
  10570. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10571. };
  10572. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10573. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10574. return false;
  10575. }
  10576. return true;
  10577. };
  10578. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10579. if (!camera) {
  10580. camera = this.getScene().activeCamera;
  10581. }
  10582. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10583. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10584. return false;
  10585. }
  10586. return true;
  10587. };
  10588. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10589. if (!this._boundingInfo || !mesh._boundingInfo) {
  10590. return false;
  10591. }
  10592. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10593. };
  10594. AbstractMesh.prototype.intersectsPoint = function (point) {
  10595. if (!this._boundingInfo) {
  10596. return false;
  10597. }
  10598. return this._boundingInfo.intersectsPoint(point);
  10599. };
  10600. // Physics
  10601. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10602. var physicsEngine = this.getScene().getPhysicsEngine();
  10603. if (!physicsEngine) {
  10604. return;
  10605. }
  10606. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10607. if (impostor.impostor) {
  10608. // Old API
  10609. options = impostor;
  10610. impostor = impostor.impostor;
  10611. }
  10612. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10613. physicsEngine._unregisterMesh(this);
  10614. return;
  10615. }
  10616. if (!options) {
  10617. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10618. }
  10619. else {
  10620. if (!options.mass && options.mass !== 0)
  10621. options.mass = 0;
  10622. if (!options.friction && options.friction !== 0)
  10623. options.friction = 0.2;
  10624. if (!options.restitution && options.restitution !== 0)
  10625. options.restitution = 0.2;
  10626. }
  10627. this._physicImpostor = impostor;
  10628. this._physicsMass = options.mass;
  10629. this._physicsFriction = options.friction;
  10630. this._physicRestitution = options.restitution;
  10631. return physicsEngine._registerMesh(this, impostor, options);
  10632. };
  10633. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10634. if (!this._physicImpostor) {
  10635. return BABYLON.PhysicsEngine.NoImpostor;
  10636. }
  10637. return this._physicImpostor;
  10638. };
  10639. AbstractMesh.prototype.getPhysicsMass = function () {
  10640. if (!this._physicsMass) {
  10641. return 0;
  10642. }
  10643. return this._physicsMass;
  10644. };
  10645. AbstractMesh.prototype.getPhysicsFriction = function () {
  10646. if (!this._physicsFriction) {
  10647. return 0;
  10648. }
  10649. return this._physicsFriction;
  10650. };
  10651. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10652. if (!this._physicRestitution) {
  10653. return 0;
  10654. }
  10655. return this._physicRestitution;
  10656. };
  10657. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10658. if (!camera) {
  10659. camera = this.getScene().activeCamera;
  10660. }
  10661. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10662. };
  10663. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10664. if (!camera) {
  10665. camera = this.getScene().activeCamera;
  10666. }
  10667. return this.absolutePosition.subtract(camera.position).length();
  10668. };
  10669. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10670. if (!this._physicImpostor) {
  10671. return;
  10672. }
  10673. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10674. };
  10675. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10676. if (!this._physicImpostor) {
  10677. return;
  10678. }
  10679. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10680. };
  10681. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10682. if (!this._physicImpostor) {
  10683. return;
  10684. }
  10685. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10686. };
  10687. // Collisions
  10688. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10689. var globalPosition = this.getAbsolutePosition();
  10690. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10691. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10692. this._collider.radius = this.ellipsoid;
  10693. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10694. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10695. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10696. this.position.addInPlace(this._diffPositionForCollisions);
  10697. }
  10698. };
  10699. // Submeshes octree
  10700. /**
  10701. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10702. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10703. */
  10704. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10705. if (maxCapacity === void 0) { maxCapacity = 64; }
  10706. if (maxDepth === void 0) { maxDepth = 2; }
  10707. if (!this._submeshesOctree) {
  10708. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10709. }
  10710. this.computeWorldMatrix(true);
  10711. // Update octree
  10712. var bbox = this.getBoundingInfo().boundingBox;
  10713. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10714. return this._submeshesOctree;
  10715. };
  10716. // Collisions
  10717. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10718. this._generatePointsArray();
  10719. // Transformation
  10720. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10721. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10722. subMesh._lastColliderWorldVertices = [];
  10723. subMesh._trianglePlanes = [];
  10724. var start = subMesh.verticesStart;
  10725. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10726. for (var i = start; i < end; i++) {
  10727. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10728. }
  10729. }
  10730. // Collide
  10731. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10732. };
  10733. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10734. var subMeshes;
  10735. var len;
  10736. // Octrees
  10737. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10738. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10739. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10740. len = intersections.length;
  10741. subMeshes = intersections.data;
  10742. }
  10743. else {
  10744. subMeshes = this.subMeshes;
  10745. len = subMeshes.length;
  10746. }
  10747. for (var index = 0; index < len; index++) {
  10748. var subMesh = subMeshes[index];
  10749. // Bounding test
  10750. if (len > 1 && !subMesh._checkCollision(collider))
  10751. continue;
  10752. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10753. }
  10754. };
  10755. AbstractMesh.prototype._checkCollision = function (collider) {
  10756. // Bounding box test
  10757. if (!this._boundingInfo._checkCollision(collider))
  10758. return;
  10759. // Transformation matrix
  10760. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10761. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10762. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10763. };
  10764. // Picking
  10765. AbstractMesh.prototype._generatePointsArray = function () {
  10766. return false;
  10767. };
  10768. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10769. var pickingInfo = new BABYLON.PickingInfo();
  10770. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10771. return pickingInfo;
  10772. }
  10773. if (!this._generatePointsArray()) {
  10774. return pickingInfo;
  10775. }
  10776. var intersectInfo = null;
  10777. // Octrees
  10778. var subMeshes;
  10779. var len;
  10780. if (this._submeshesOctree && this.useOctreeForPicking) {
  10781. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10782. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10783. len = intersections.length;
  10784. subMeshes = intersections.data;
  10785. }
  10786. else {
  10787. subMeshes = this.subMeshes;
  10788. len = subMeshes.length;
  10789. }
  10790. for (var index = 0; index < len; index++) {
  10791. var subMesh = subMeshes[index];
  10792. // Bounding test
  10793. if (len > 1 && !subMesh.canIntersects(ray))
  10794. continue;
  10795. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10796. if (currentIntersectInfo) {
  10797. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10798. intersectInfo = currentIntersectInfo;
  10799. intersectInfo.subMeshId = index;
  10800. if (fastCheck) {
  10801. break;
  10802. }
  10803. }
  10804. }
  10805. }
  10806. if (intersectInfo) {
  10807. // Get picked point
  10808. var world = this.getWorldMatrix();
  10809. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10810. var direction = ray.direction.clone();
  10811. direction = direction.scale(intersectInfo.distance);
  10812. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10813. var pickedPoint = worldOrigin.add(worldDirection);
  10814. // Return result
  10815. pickingInfo.hit = true;
  10816. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10817. pickingInfo.pickedPoint = pickedPoint;
  10818. pickingInfo.pickedMesh = this;
  10819. pickingInfo.bu = intersectInfo.bu;
  10820. pickingInfo.bv = intersectInfo.bv;
  10821. pickingInfo.faceId = intersectInfo.faceId;
  10822. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10823. return pickingInfo;
  10824. }
  10825. return pickingInfo;
  10826. };
  10827. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10828. return null;
  10829. };
  10830. AbstractMesh.prototype.releaseSubMeshes = function () {
  10831. if (this.subMeshes) {
  10832. while (this.subMeshes.length) {
  10833. this.subMeshes[0].dispose();
  10834. }
  10835. }
  10836. else {
  10837. this.subMeshes = new Array();
  10838. }
  10839. };
  10840. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10841. var index;
  10842. // Physics
  10843. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10844. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10845. }
  10846. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10847. var other = this._intersectionsInProgress[index];
  10848. var pos = other._intersectionsInProgress.indexOf(this);
  10849. other._intersectionsInProgress.splice(pos, 1);
  10850. }
  10851. this._intersectionsInProgress = [];
  10852. // SubMeshes
  10853. this.releaseSubMeshes();
  10854. // Remove from scene
  10855. this.getScene().removeMesh(this);
  10856. if (!doNotRecurse) {
  10857. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10858. if (this.getScene().particleSystems[index].emitter === this) {
  10859. this.getScene().particleSystems[index].dispose();
  10860. index--;
  10861. }
  10862. }
  10863. // Children
  10864. var objects = this.getScene().meshes.slice(0);
  10865. for (index = 0; index < objects.length; index++) {
  10866. if (objects[index].parent === this) {
  10867. objects[index].dispose();
  10868. }
  10869. }
  10870. }
  10871. else {
  10872. for (index = 0; index < this.getScene().meshes.length; index++) {
  10873. var obj = this.getScene().meshes[index];
  10874. if (obj.parent === this) {
  10875. obj.parent = null;
  10876. obj.computeWorldMatrix(true);
  10877. }
  10878. }
  10879. }
  10880. this._onAfterWorldMatrixUpdate = [];
  10881. this._isDisposed = true;
  10882. // Callback
  10883. if (this.onDispose) {
  10884. this.onDispose();
  10885. }
  10886. };
  10887. // Statics
  10888. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10889. AbstractMesh._BILLBOARDMODE_X = 1;
  10890. AbstractMesh._BILLBOARDMODE_Y = 2;
  10891. AbstractMesh._BILLBOARDMODE_Z = 4;
  10892. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10893. return AbstractMesh;
  10894. })(BABYLON.Node);
  10895. BABYLON.AbstractMesh = AbstractMesh;
  10896. })(BABYLON || (BABYLON = {}));
  10897. //# sourceMappingURL=babylon.abstractMesh.js.map
  10898. var BABYLON;
  10899. (function (BABYLON) {
  10900. var _InstancesBatch = (function () {
  10901. function _InstancesBatch() {
  10902. this.mustReturn = false;
  10903. this.visibleInstances = new Array();
  10904. this.renderSelf = new Array();
  10905. }
  10906. return _InstancesBatch;
  10907. })();
  10908. BABYLON._InstancesBatch = _InstancesBatch;
  10909. var Mesh = (function (_super) {
  10910. __extends(Mesh, _super);
  10911. /**
  10912. * @constructor
  10913. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10914. * @param {Scene} scene - The scene to add this mesh to.
  10915. * @param {Node} parent - The parent of this mesh, if it has one
  10916. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10917. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10918. * When false, achieved by calling a clone(), also passing False.
  10919. * This will make creation of children, recursive.
  10920. */
  10921. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10922. if (parent === void 0) { parent = null; }
  10923. _super.call(this, name, scene);
  10924. // Members
  10925. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10926. this.instances = new Array();
  10927. this._LODLevels = new Array();
  10928. this._onBeforeRenderCallbacks = new Array();
  10929. this._onAfterRenderCallbacks = new Array();
  10930. this._visibleInstances = {};
  10931. this._renderIdForInstances = new Array();
  10932. this._batchCache = new _InstancesBatch();
  10933. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10934. this._sideOrientation = Mesh._DEFAULTSIDE;
  10935. if (source) {
  10936. // Geometry
  10937. if (source._geometry) {
  10938. source._geometry.applyToMesh(this);
  10939. }
  10940. // Deep copy
  10941. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  10942. // Material
  10943. this.material = source.material;
  10944. if (!doNotCloneChildren) {
  10945. for (var index = 0; index < scene.meshes.length; index++) {
  10946. var mesh = scene.meshes[index];
  10947. if (mesh.parent === source) {
  10948. // doNotCloneChildren is always going to be False
  10949. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10950. }
  10951. }
  10952. }
  10953. for (index = 0; index < scene.particleSystems.length; index++) {
  10954. var system = scene.particleSystems[index];
  10955. if (system.emitter === source) {
  10956. system.clone(system.name, this);
  10957. }
  10958. }
  10959. this.computeWorldMatrix(true);
  10960. }
  10961. // Parent
  10962. if (parent !== null) {
  10963. this.parent = parent;
  10964. }
  10965. }
  10966. Object.defineProperty(Mesh, "FRONTSIDE", {
  10967. get: function () {
  10968. return Mesh._FRONTSIDE;
  10969. },
  10970. enumerable: true,
  10971. configurable: true
  10972. });
  10973. Object.defineProperty(Mesh, "BACKSIDE", {
  10974. get: function () {
  10975. return Mesh._BACKSIDE;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10981. get: function () {
  10982. return Mesh._DOUBLESIDE;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10988. get: function () {
  10989. return Mesh._DEFAULTSIDE;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10995. // Methods
  10996. get: function () {
  10997. return this._LODLevels.length > 0;
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Mesh.prototype._sortLODLevels = function () {
  11003. this._LODLevels.sort(function (a, b) {
  11004. if (a.distance < b.distance) {
  11005. return 1;
  11006. }
  11007. if (a.distance > b.distance) {
  11008. return -1;
  11009. }
  11010. return 0;
  11011. });
  11012. };
  11013. /**
  11014. * Add a mesh as LOD level triggered at the given distance.
  11015. * @param {number} distance - the distance from the center of the object to show this level
  11016. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  11017. * @return {BABYLON.Mesh} this mesh (for chaining)
  11018. */
  11019. Mesh.prototype.addLODLevel = function (distance, mesh) {
  11020. if (mesh && mesh._masterMesh) {
  11021. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  11022. return this;
  11023. }
  11024. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  11025. this._LODLevels.push(level);
  11026. if (mesh) {
  11027. mesh._masterMesh = this;
  11028. }
  11029. this._sortLODLevels();
  11030. return this;
  11031. };
  11032. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  11033. for (var index = 0; index < this._LODLevels.length; index++) {
  11034. var level = this._LODLevels[index];
  11035. if (level.distance === distance) {
  11036. return level.mesh;
  11037. }
  11038. }
  11039. return null;
  11040. };
  11041. /**
  11042. * Remove a mesh from the LOD array
  11043. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  11044. * @return {BABYLON.Mesh} this mesh (for chaining)
  11045. */
  11046. Mesh.prototype.removeLODLevel = function (mesh) {
  11047. for (var index = 0; index < this._LODLevels.length; index++) {
  11048. if (this._LODLevels[index].mesh === mesh) {
  11049. this._LODLevels.splice(index, 1);
  11050. if (mesh) {
  11051. mesh._masterMesh = null;
  11052. }
  11053. }
  11054. }
  11055. this._sortLODLevels();
  11056. return this;
  11057. };
  11058. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  11059. if (!this._LODLevels || this._LODLevels.length === 0) {
  11060. return this;
  11061. }
  11062. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  11063. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  11064. if (this.onLODLevelSelection) {
  11065. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  11066. }
  11067. return this;
  11068. }
  11069. for (var index = 0; index < this._LODLevels.length; index++) {
  11070. var level = this._LODLevels[index];
  11071. if (level.distance < distanceToCamera) {
  11072. if (level.mesh) {
  11073. level.mesh._preActivate();
  11074. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11075. }
  11076. if (this.onLODLevelSelection) {
  11077. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  11078. }
  11079. return level.mesh;
  11080. }
  11081. }
  11082. if (this.onLODLevelSelection) {
  11083. this.onLODLevelSelection(distanceToCamera, this, this);
  11084. }
  11085. return this;
  11086. };
  11087. Object.defineProperty(Mesh.prototype, "geometry", {
  11088. get: function () {
  11089. return this._geometry;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Mesh.prototype.getTotalVertices = function () {
  11095. if (!this._geometry) {
  11096. return 0;
  11097. }
  11098. return this._geometry.getTotalVertices();
  11099. };
  11100. Mesh.prototype.getVerticesData = function (kind) {
  11101. if (!this._geometry) {
  11102. return null;
  11103. }
  11104. return this._geometry.getVerticesData(kind);
  11105. };
  11106. Mesh.prototype.getVertexBuffer = function (kind) {
  11107. if (!this._geometry) {
  11108. return undefined;
  11109. }
  11110. return this._geometry.getVertexBuffer(kind);
  11111. };
  11112. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11113. if (!this._geometry) {
  11114. if (this._delayInfo) {
  11115. return this._delayInfo.indexOf(kind) !== -1;
  11116. }
  11117. return false;
  11118. }
  11119. return this._geometry.isVerticesDataPresent(kind);
  11120. };
  11121. Mesh.prototype.getVerticesDataKinds = function () {
  11122. if (!this._geometry) {
  11123. var result = [];
  11124. if (this._delayInfo) {
  11125. for (var kind in this._delayInfo) {
  11126. result.push(kind);
  11127. }
  11128. }
  11129. return result;
  11130. }
  11131. return this._geometry.getVerticesDataKinds();
  11132. };
  11133. Mesh.prototype.getTotalIndices = function () {
  11134. if (!this._geometry) {
  11135. return 0;
  11136. }
  11137. return this._geometry.getTotalIndices();
  11138. };
  11139. Mesh.prototype.getIndices = function () {
  11140. if (!this._geometry) {
  11141. return [];
  11142. }
  11143. return this._geometry.getIndices();
  11144. };
  11145. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11146. get: function () {
  11147. return this._masterMesh !== null && this._masterMesh !== undefined;
  11148. },
  11149. enumerable: true,
  11150. configurable: true
  11151. });
  11152. Mesh.prototype.isReady = function () {
  11153. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11154. return false;
  11155. }
  11156. return _super.prototype.isReady.call(this);
  11157. };
  11158. Mesh.prototype.isDisposed = function () {
  11159. return this._isDisposed;
  11160. };
  11161. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  11162. get: function () {
  11163. return this._sideOrientation;
  11164. },
  11165. set: function (sideO) {
  11166. this._sideOrientation = sideO;
  11167. },
  11168. enumerable: true,
  11169. configurable: true
  11170. });
  11171. // Methods
  11172. Mesh.prototype._preActivate = function () {
  11173. var sceneRenderId = this.getScene().getRenderId();
  11174. if (this._preActivateId === sceneRenderId) {
  11175. return;
  11176. }
  11177. this._preActivateId = sceneRenderId;
  11178. this._visibleInstances = null;
  11179. };
  11180. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11181. if (!this._visibleInstances) {
  11182. this._visibleInstances = {};
  11183. this._visibleInstances.defaultRenderId = renderId;
  11184. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11185. }
  11186. if (!this._visibleInstances[renderId]) {
  11187. this._visibleInstances[renderId] = new Array();
  11188. }
  11189. this._visibleInstances[renderId].push(instance);
  11190. };
  11191. Mesh.prototype.refreshBoundingInfo = function () {
  11192. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11193. if (data) {
  11194. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11195. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11196. }
  11197. if (this.subMeshes) {
  11198. for (var index = 0; index < this.subMeshes.length; index++) {
  11199. this.subMeshes[index].refreshBoundingInfo();
  11200. }
  11201. }
  11202. this._updateBoundingInfo();
  11203. };
  11204. Mesh.prototype._createGlobalSubMesh = function () {
  11205. var totalVertices = this.getTotalVertices();
  11206. if (!totalVertices || !this.getIndices()) {
  11207. return null;
  11208. }
  11209. this.releaseSubMeshes();
  11210. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11211. };
  11212. Mesh.prototype.subdivide = function (count) {
  11213. if (count < 1) {
  11214. return;
  11215. }
  11216. var totalIndices = this.getTotalIndices();
  11217. var subdivisionSize = (totalIndices / count) | 0;
  11218. var offset = 0;
  11219. while (subdivisionSize % 3 !== 0) {
  11220. subdivisionSize++;
  11221. }
  11222. this.releaseSubMeshes();
  11223. for (var index = 0; index < count; index++) {
  11224. if (offset >= totalIndices) {
  11225. break;
  11226. }
  11227. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11228. offset += subdivisionSize;
  11229. }
  11230. this.synchronizeInstances();
  11231. };
  11232. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11233. if (kind instanceof Array) {
  11234. var temp = data;
  11235. data = kind;
  11236. kind = temp;
  11237. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11238. }
  11239. if (!this._geometry) {
  11240. var vertexData = new BABYLON.VertexData();
  11241. vertexData.set(data, kind);
  11242. var scene = this.getScene();
  11243. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11244. }
  11245. else {
  11246. this._geometry.setVerticesData(kind, data, updatable, stride);
  11247. }
  11248. };
  11249. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11250. if (!this._geometry) {
  11251. return;
  11252. }
  11253. if (!makeItUnique) {
  11254. this._geometry.updateVerticesData(kind, data, updateExtends);
  11255. }
  11256. else {
  11257. this.makeGeometryUnique();
  11258. this.updateVerticesData(kind, data, updateExtends, false);
  11259. }
  11260. };
  11261. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11262. if (!this._geometry) {
  11263. return;
  11264. }
  11265. if (!makeItUnique) {
  11266. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11267. }
  11268. else {
  11269. this.makeGeometryUnique();
  11270. this.updateVerticesDataDirectly(kind, data, offset, false);
  11271. }
  11272. };
  11273. // Mesh positions update function :
  11274. // updates the mesh positions according to the positionFunction returned values.
  11275. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  11276. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  11277. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  11278. if (computeNormals === void 0) { computeNormals = true; }
  11279. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11280. positionFunction(positions);
  11281. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  11282. if (computeNormals) {
  11283. var indices = this.getIndices();
  11284. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11285. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  11286. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  11287. }
  11288. };
  11289. Mesh.prototype.makeGeometryUnique = function () {
  11290. if (!this._geometry) {
  11291. return;
  11292. }
  11293. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11294. geometry.applyToMesh(this);
  11295. };
  11296. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11297. if (!this._geometry) {
  11298. var vertexData = new BABYLON.VertexData();
  11299. vertexData.indices = indices;
  11300. var scene = this.getScene();
  11301. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11302. }
  11303. else {
  11304. this._geometry.setIndices(indices, totalVertices);
  11305. }
  11306. };
  11307. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11308. var engine = this.getScene().getEngine();
  11309. // Wireframe
  11310. var indexToBind;
  11311. switch (fillMode) {
  11312. case BABYLON.Material.PointFillMode:
  11313. indexToBind = null;
  11314. break;
  11315. case BABYLON.Material.WireFrameFillMode:
  11316. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11317. break;
  11318. default:
  11319. case BABYLON.Material.TriangleFillMode:
  11320. indexToBind = this._geometry.getIndexBuffer();
  11321. break;
  11322. }
  11323. // VBOs
  11324. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11325. };
  11326. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11327. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11328. return;
  11329. }
  11330. var engine = this.getScene().getEngine();
  11331. switch (fillMode) {
  11332. case BABYLON.Material.PointFillMode:
  11333. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11334. break;
  11335. case BABYLON.Material.WireFrameFillMode:
  11336. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11337. break;
  11338. default:
  11339. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11340. }
  11341. };
  11342. Mesh.prototype.registerBeforeRender = function (func) {
  11343. this._onBeforeRenderCallbacks.push(func);
  11344. };
  11345. Mesh.prototype.unregisterBeforeRender = function (func) {
  11346. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11347. if (index > -1) {
  11348. this._onBeforeRenderCallbacks.splice(index, 1);
  11349. }
  11350. };
  11351. Mesh.prototype.registerAfterRender = function (func) {
  11352. this._onAfterRenderCallbacks.push(func);
  11353. };
  11354. Mesh.prototype.unregisterAfterRender = function (func) {
  11355. var index = this._onAfterRenderCallbacks.indexOf(func);
  11356. if (index > -1) {
  11357. this._onAfterRenderCallbacks.splice(index, 1);
  11358. }
  11359. };
  11360. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11361. var scene = this.getScene();
  11362. this._batchCache.mustReturn = false;
  11363. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11364. this._batchCache.visibleInstances[subMeshId] = null;
  11365. if (this._visibleInstances) {
  11366. var currentRenderId = scene.getRenderId();
  11367. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11368. var selfRenderId = this._renderId;
  11369. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11370. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11371. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11372. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11373. }
  11374. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11375. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11376. this._batchCache.mustReturn = true;
  11377. return this._batchCache;
  11378. }
  11379. if (currentRenderId !== selfRenderId) {
  11380. this._batchCache.renderSelf[subMeshId] = false;
  11381. }
  11382. }
  11383. this._renderIdForInstances[subMeshId] = currentRenderId;
  11384. }
  11385. return this._batchCache;
  11386. };
  11387. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11388. var visibleInstances = batch.visibleInstances[subMesh._id];
  11389. var matricesCount = visibleInstances.length + 1;
  11390. var bufferSize = matricesCount * 16 * 4;
  11391. while (this._instancesBufferSize < bufferSize) {
  11392. this._instancesBufferSize *= 2;
  11393. }
  11394. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11395. if (this._worldMatricesInstancesBuffer) {
  11396. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11397. }
  11398. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11399. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11400. }
  11401. var offset = 0;
  11402. var instancesCount = 0;
  11403. var world = this.getWorldMatrix();
  11404. if (batch.renderSelf[subMesh._id]) {
  11405. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11406. offset += 16;
  11407. instancesCount++;
  11408. }
  11409. if (visibleInstances) {
  11410. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11411. var instance = visibleInstances[instanceIndex];
  11412. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11413. offset += 16;
  11414. instancesCount++;
  11415. }
  11416. }
  11417. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11418. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11419. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11420. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11421. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11422. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11423. this._draw(subMesh, fillMode, instancesCount);
  11424. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11425. };
  11426. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11427. var scene = this.getScene();
  11428. var engine = scene.getEngine();
  11429. if (hardwareInstancedRendering) {
  11430. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11431. }
  11432. else {
  11433. if (batch.renderSelf[subMesh._id]) {
  11434. // Draw
  11435. if (onBeforeDraw) {
  11436. onBeforeDraw(false, this.getWorldMatrix());
  11437. }
  11438. this._draw(subMesh, fillMode);
  11439. }
  11440. if (batch.visibleInstances[subMesh._id]) {
  11441. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11442. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11443. // World
  11444. var world = instance.getWorldMatrix();
  11445. if (onBeforeDraw) {
  11446. onBeforeDraw(true, world);
  11447. }
  11448. // Draw
  11449. this._draw(subMesh, fillMode);
  11450. }
  11451. }
  11452. }
  11453. };
  11454. Mesh.prototype.render = function (subMesh) {
  11455. var scene = this.getScene();
  11456. // Managing instances
  11457. var batch = this._getInstancesRenderList(subMesh._id);
  11458. if (batch.mustReturn) {
  11459. return;
  11460. }
  11461. // Checking geometry state
  11462. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11463. return;
  11464. }
  11465. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11466. this._onBeforeRenderCallbacks[callbackIndex](this);
  11467. }
  11468. var engine = scene.getEngine();
  11469. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11470. // Material
  11471. var effectiveMaterial = subMesh.getMaterial();
  11472. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11473. return;
  11474. }
  11475. // Outline - step 1
  11476. var savedDepthWrite = engine.getDepthWrite();
  11477. if (this.renderOutline) {
  11478. engine.setDepthWrite(false);
  11479. scene.getOutlineRenderer().render(subMesh, batch);
  11480. engine.setDepthWrite(savedDepthWrite);
  11481. }
  11482. effectiveMaterial._preBind();
  11483. var effect = effectiveMaterial.getEffect();
  11484. // Bind
  11485. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11486. this._bind(subMesh, effect, fillMode);
  11487. var world = this.getWorldMatrix();
  11488. effectiveMaterial.bind(world, this);
  11489. // Draw
  11490. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11491. if (isInstance) {
  11492. effectiveMaterial.bindOnlyWorldMatrix(world);
  11493. }
  11494. });
  11495. // Unbind
  11496. effectiveMaterial.unbind();
  11497. // Outline - step 2
  11498. if (this.renderOutline && savedDepthWrite) {
  11499. engine.setDepthWrite(true);
  11500. engine.setColorWrite(false);
  11501. scene.getOutlineRenderer().render(subMesh, batch);
  11502. engine.setColorWrite(true);
  11503. }
  11504. // Overlay
  11505. if (this.renderOverlay) {
  11506. var currentMode = engine.getAlphaMode();
  11507. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11508. scene.getOutlineRenderer().render(subMesh, batch, true);
  11509. engine.setAlphaMode(currentMode);
  11510. }
  11511. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11512. this._onAfterRenderCallbacks[callbackIndex](this);
  11513. }
  11514. };
  11515. Mesh.prototype.getEmittedParticleSystems = function () {
  11516. var results = new Array();
  11517. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11518. var particleSystem = this.getScene().particleSystems[index];
  11519. if (particleSystem.emitter === this) {
  11520. results.push(particleSystem);
  11521. }
  11522. }
  11523. return results;
  11524. };
  11525. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11526. var results = new Array();
  11527. var descendants = this.getDescendants();
  11528. descendants.push(this);
  11529. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11530. var particleSystem = this.getScene().particleSystems[index];
  11531. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11532. results.push(particleSystem);
  11533. }
  11534. }
  11535. return results;
  11536. };
  11537. Mesh.prototype.getChildren = function () {
  11538. var results = [];
  11539. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11540. var mesh = this.getScene().meshes[index];
  11541. if (mesh.parent === this) {
  11542. results.push(mesh);
  11543. }
  11544. }
  11545. return results;
  11546. };
  11547. Mesh.prototype._checkDelayState = function () {
  11548. var _this = this;
  11549. var that = this;
  11550. var scene = this.getScene();
  11551. if (this._geometry) {
  11552. this._geometry.load(scene);
  11553. }
  11554. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11555. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11556. scene._addPendingData(that);
  11557. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11558. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11559. if (data instanceof ArrayBuffer) {
  11560. _this._delayLoadingFunction(data, _this);
  11561. }
  11562. else {
  11563. _this._delayLoadingFunction(JSON.parse(data), _this);
  11564. }
  11565. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11566. scene._removePendingData(_this);
  11567. }, function () {
  11568. }, scene.database, getBinaryData);
  11569. }
  11570. };
  11571. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11572. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11573. return false;
  11574. }
  11575. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11576. return false;
  11577. }
  11578. this._checkDelayState();
  11579. return true;
  11580. };
  11581. Mesh.prototype.setMaterialByID = function (id) {
  11582. var materials = this.getScene().materials;
  11583. for (var index = 0; index < materials.length; index++) {
  11584. if (materials[index].id === id) {
  11585. this.material = materials[index];
  11586. return;
  11587. }
  11588. }
  11589. // Multi
  11590. var multiMaterials = this.getScene().multiMaterials;
  11591. for (index = 0; index < multiMaterials.length; index++) {
  11592. if (multiMaterials[index].id === id) {
  11593. this.material = multiMaterials[index];
  11594. return;
  11595. }
  11596. }
  11597. };
  11598. Mesh.prototype.getAnimatables = function () {
  11599. var results = [];
  11600. if (this.material) {
  11601. results.push(this.material);
  11602. }
  11603. if (this.skeleton) {
  11604. results.push(this.skeleton);
  11605. }
  11606. return results;
  11607. };
  11608. // Geometry
  11609. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11610. // Position
  11611. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11612. return;
  11613. }
  11614. this._resetPointsArrayCache();
  11615. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11616. var temp = [];
  11617. for (var index = 0; index < data.length; index += 3) {
  11618. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11619. }
  11620. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11621. // Normals
  11622. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11623. return;
  11624. }
  11625. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11626. temp = [];
  11627. for (index = 0; index < data.length; index += 3) {
  11628. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11629. }
  11630. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11631. };
  11632. // Cache
  11633. Mesh.prototype._resetPointsArrayCache = function () {
  11634. this._positions = null;
  11635. };
  11636. Mesh.prototype._generatePointsArray = function () {
  11637. if (this._positions)
  11638. return true;
  11639. this._positions = [];
  11640. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11641. if (!data) {
  11642. return false;
  11643. }
  11644. for (var index = 0; index < data.length; index += 3) {
  11645. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11646. }
  11647. return true;
  11648. };
  11649. // Clone
  11650. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11651. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11652. };
  11653. // Dispose
  11654. Mesh.prototype.dispose = function (doNotRecurse) {
  11655. if (this._geometry) {
  11656. this._geometry.releaseForMesh(this, true);
  11657. }
  11658. // Instances
  11659. if (this._worldMatricesInstancesBuffer) {
  11660. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11661. this._worldMatricesInstancesBuffer = null;
  11662. }
  11663. while (this.instances.length) {
  11664. this.instances[0].dispose();
  11665. }
  11666. _super.prototype.dispose.call(this, doNotRecurse);
  11667. };
  11668. // Geometric tools
  11669. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11670. var _this = this;
  11671. var scene = this.getScene();
  11672. var onload = function (img) {
  11673. // Getting height map data
  11674. var canvas = document.createElement("canvas");
  11675. var context = canvas.getContext("2d");
  11676. var heightMapWidth = img.width;
  11677. var heightMapHeight = img.height;
  11678. canvas.width = heightMapWidth;
  11679. canvas.height = heightMapHeight;
  11680. context.drawImage(img, 0, 0);
  11681. // Create VertexData from map data
  11682. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11683. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11684. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11685. //execute success callback, if set
  11686. if (onSuccess) {
  11687. onSuccess(_this);
  11688. }
  11689. };
  11690. BABYLON.Tools.LoadImage(url, onload, function () {
  11691. }, scene.database);
  11692. };
  11693. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11694. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11695. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11696. return;
  11697. }
  11698. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11699. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11700. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11701. var position = BABYLON.Vector3.Zero();
  11702. var normal = BABYLON.Vector3.Zero();
  11703. var uv = BABYLON.Vector2.Zero();
  11704. for (var index = 0; index < positions.length; index += 3) {
  11705. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11706. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11707. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11708. // Compute height
  11709. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11710. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11711. var pos = (u + v * heightMapWidth) * 4;
  11712. var r = buffer[pos] / 255.0;
  11713. var g = buffer[pos + 1] / 255.0;
  11714. var b = buffer[pos + 2] / 255.0;
  11715. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11716. normal.normalize();
  11717. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11718. position = position.add(normal);
  11719. position.toArray(positions, index);
  11720. }
  11721. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11722. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11723. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11724. };
  11725. Mesh.prototype.convertToFlatShadedMesh = function () {
  11726. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11727. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11728. var kinds = this.getVerticesDataKinds();
  11729. var vbs = [];
  11730. var data = [];
  11731. var newdata = [];
  11732. var updatableNormals = false;
  11733. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11734. var kind = kinds[kindIndex];
  11735. var vertexBuffer = this.getVertexBuffer(kind);
  11736. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11737. updatableNormals = vertexBuffer.isUpdatable();
  11738. kinds.splice(kindIndex, 1);
  11739. kindIndex--;
  11740. continue;
  11741. }
  11742. vbs[kind] = vertexBuffer;
  11743. data[kind] = vbs[kind].getData();
  11744. newdata[kind] = [];
  11745. }
  11746. // Save previous submeshes
  11747. var previousSubmeshes = this.subMeshes.slice(0);
  11748. var indices = this.getIndices();
  11749. var totalIndices = this.getTotalIndices();
  11750. for (var index = 0; index < totalIndices; index++) {
  11751. var vertexIndex = indices[index];
  11752. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11753. kind = kinds[kindIndex];
  11754. var stride = vbs[kind].getStrideSize();
  11755. for (var offset = 0; offset < stride; offset++) {
  11756. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11757. }
  11758. }
  11759. }
  11760. // Updating faces & normal
  11761. var normals = [];
  11762. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11763. for (index = 0; index < totalIndices; index += 3) {
  11764. indices[index] = index;
  11765. indices[index + 1] = index + 1;
  11766. indices[index + 2] = index + 2;
  11767. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11768. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11769. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11770. var p1p2 = p1.subtract(p2);
  11771. var p3p2 = p3.subtract(p2);
  11772. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11773. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11774. normals.push(normal.x);
  11775. normals.push(normal.y);
  11776. normals.push(normal.z);
  11777. }
  11778. }
  11779. this.setIndices(indices);
  11780. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11781. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11782. kind = kinds[kindIndex];
  11783. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11784. }
  11785. // Updating submeshes
  11786. this.releaseSubMeshes();
  11787. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11788. var previousOne = previousSubmeshes[submeshIndex];
  11789. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11790. }
  11791. this.synchronizeInstances();
  11792. };
  11793. // Instances
  11794. Mesh.prototype.createInstance = function (name) {
  11795. return new BABYLON.InstancedMesh(name, this);
  11796. };
  11797. Mesh.prototype.synchronizeInstances = function () {
  11798. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11799. var instance = this.instances[instanceIndex];
  11800. instance._syncSubMeshes();
  11801. }
  11802. };
  11803. /**
  11804. * Simplify the mesh according to the given array of settings.
  11805. * Function will return immediately and will simplify async.
  11806. * @param settings a collection of simplification settings.
  11807. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11808. * @param type the type of simplification to run.
  11809. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11810. */
  11811. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11812. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11813. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11814. this.getScene().simplificationQueue.addTask({
  11815. settings: settings,
  11816. parallelProcessing: parallelProcessing,
  11817. mesh: this,
  11818. simplificationType: simplificationType,
  11819. successCallback: successCallback
  11820. });
  11821. };
  11822. /**
  11823. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11824. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11825. * This should be used together with the simplification to avoid disappearing triangles.
  11826. * @param successCallback an optional success callback to be called after the optimization finished.
  11827. */
  11828. Mesh.prototype.optimizeIndices = function (successCallback) {
  11829. var _this = this;
  11830. var indices = this.getIndices();
  11831. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11832. var vectorPositions = [];
  11833. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11834. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11835. }
  11836. var dupes = [];
  11837. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11838. var realPos = vectorPositions.length - 1 - iteration;
  11839. var testedPosition = vectorPositions[realPos];
  11840. for (var j = 0; j < realPos; ++j) {
  11841. var againstPosition = vectorPositions[j];
  11842. if (testedPosition.equals(againstPosition)) {
  11843. dupes[realPos] = j;
  11844. break;
  11845. }
  11846. }
  11847. }, function () {
  11848. for (var i = 0; i < indices.length; ++i) {
  11849. indices[i] = dupes[indices[i]] || indices[i];
  11850. }
  11851. //indices are now reordered
  11852. var originalSubMeshes = _this.subMeshes.slice(0);
  11853. _this.setIndices(indices);
  11854. _this.subMeshes = originalSubMeshes;
  11855. if (successCallback) {
  11856. successCallback(_this);
  11857. }
  11858. });
  11859. };
  11860. // Statics
  11861. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  11862. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11863. if (ribbonInstance === void 0) { ribbonInstance = null; }
  11864. if (ribbonInstance) {
  11865. // positionFunction : ribbon case
  11866. // only pathArray and sideOrientation parameters are taken into account for positions update
  11867. var positionsOfRibbon = function (pathArray, sideOrientation) {
  11868. var positionFunction = function (positions) {
  11869. var minlg = pathArray[0].length;
  11870. var i = 0;
  11871. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  11872. for (var si = 1; si <= ns; si++) {
  11873. for (var p = 0; p < pathArray.length; p++) {
  11874. var path = pathArray[p];
  11875. var l = path.length;
  11876. minlg = (minlg < l) ? minlg : l;
  11877. var j = 0;
  11878. while (j < minlg) {
  11879. positions[i] = path[j].x;
  11880. positions[i + 1] = path[j].y;
  11881. positions[i + 2] = path[j].z;
  11882. j++;
  11883. i += 3;
  11884. }
  11885. }
  11886. }
  11887. };
  11888. return positionFunction;
  11889. };
  11890. var sideOrientation = ribbonInstance.sideOrientation;
  11891. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  11892. ribbonInstance.updateMeshPositions(positionFunction, true);
  11893. return ribbonInstance;
  11894. }
  11895. else {
  11896. var ribbon = new Mesh(name, scene);
  11897. ribbon.sideOrientation = sideOrientation;
  11898. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11899. vertexData.applyToMesh(ribbon, updatable);
  11900. return ribbon;
  11901. }
  11902. };
  11903. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  11904. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11905. var disc = new Mesh(name, scene);
  11906. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  11907. vertexData.applyToMesh(disc, updatable);
  11908. return disc;
  11909. };
  11910. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11911. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11912. var box = new Mesh(name, scene);
  11913. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11914. vertexData.applyToMesh(box, updatable);
  11915. return box;
  11916. };
  11917. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11918. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11919. var sphere = new Mesh(name, scene);
  11920. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11921. vertexData.applyToMesh(sphere, updatable);
  11922. return sphere;
  11923. };
  11924. // Cylinder and cone (Code inspired by SharpDX.org)
  11925. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11926. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11927. // subdivisions is a new parameter, we need to support old signature
  11928. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11929. if (scene !== undefined) {
  11930. updatable = scene;
  11931. }
  11932. scene = subdivisions;
  11933. subdivisions = 1;
  11934. }
  11935. var cylinder = new Mesh(name, scene);
  11936. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11937. vertexData.applyToMesh(cylinder, updatable);
  11938. return cylinder;
  11939. };
  11940. // Torus (Code from SharpDX.org)
  11941. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11942. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11943. var torus = new Mesh(name, scene);
  11944. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11945. vertexData.applyToMesh(torus, updatable);
  11946. return torus;
  11947. };
  11948. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11949. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11950. var torusKnot = new Mesh(name, scene);
  11951. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11952. vertexData.applyToMesh(torusKnot, updatable);
  11953. return torusKnot;
  11954. };
  11955. // Lines
  11956. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  11957. if (linesInstance === void 0) { linesInstance = null; }
  11958. if (linesInstance) {
  11959. var positionsOfLines = function (points) {
  11960. var positionFunction = function (positions) {
  11961. var i = 0;
  11962. for (var p = 0; p < points.length; p++) {
  11963. positions[i] = points[p].x;
  11964. positions[i + 1] = points[p].y;
  11965. positions[i + 2] = points[p].z;
  11966. i += 3;
  11967. }
  11968. };
  11969. return positionFunction;
  11970. };
  11971. var positionFunction = positionsOfLines(points);
  11972. linesInstance.updateMeshPositions(positionFunction, false);
  11973. return linesInstance;
  11974. }
  11975. // lines creation
  11976. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11977. var vertexData = BABYLON.VertexData.CreateLines(points);
  11978. vertexData.applyToMesh(lines, updatable);
  11979. return lines;
  11980. };
  11981. // Extrusion
  11982. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation, extrudedInstance) {
  11983. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11984. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11985. scale = scale || 1;
  11986. rotation = rotation || 0;
  11987. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation, extrudedInstance);
  11988. return extruded;
  11989. };
  11990. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation, extrudedInstance) {
  11991. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11992. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11993. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation, extrudedInstance);
  11994. return extrudedCustom;
  11995. };
  11996. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side, instance) {
  11997. // extrusion geometry
  11998. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, custom) {
  11999. var tangents = path3D.getTangents();
  12000. var normals = path3D.getNormals();
  12001. var binormals = path3D.getBinormals();
  12002. var distances = path3D.getDistances();
  12003. var angle = 0;
  12004. var returnScale = function (i, distance) {
  12005. return scale;
  12006. };
  12007. var returnRotation = function (i, distance) {
  12008. return rotation;
  12009. };
  12010. var rotate = custom ? rotateFunction : returnRotation;
  12011. var scl = custom ? scaleFunction : returnScale;
  12012. var index = 0;
  12013. for (var i = 0; i < curve.length; i++) {
  12014. var shapePath = new Array();
  12015. var angleStep = rotate(i, distances[i]);
  12016. var scaleRatio = scl(i, distances[i]);
  12017. for (var p = 0; p < shape.length; p++) {
  12018. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  12019. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  12020. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  12021. shapePath.push(rotated);
  12022. }
  12023. shapePaths[index] = shapePath;
  12024. angle += angleStep;
  12025. index++;
  12026. }
  12027. return shapePaths;
  12028. };
  12029. if (instance) {
  12030. var path3D = (instance.path3D).update(curve);
  12031. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, custom);
  12032. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  12033. return instance;
  12034. }
  12035. // extruded shape creation
  12036. var path3D = new BABYLON.Path3D(curve);
  12037. var newShapePaths = new Array();
  12038. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, custom);
  12039. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  12040. extrudedGeneric.pathArray = pathArray;
  12041. extrudedGeneric.path3D = path3D;
  12042. return extrudedGeneric;
  12043. };
  12044. // Plane & ground
  12045. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  12046. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12047. var plane = new Mesh(name, scene);
  12048. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  12049. vertexData.applyToMesh(plane, updatable);
  12050. return plane;
  12051. };
  12052. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  12053. var ground = new BABYLON.GroundMesh(name, scene);
  12054. ground._setReady(false);
  12055. ground._subdivisions = subdivisions;
  12056. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  12057. vertexData.applyToMesh(ground, updatable);
  12058. ground._setReady(true);
  12059. return ground;
  12060. };
  12061. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  12062. var tiledGround = new Mesh(name, scene);
  12063. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  12064. vertexData.applyToMesh(tiledGround, updatable);
  12065. return tiledGround;
  12066. };
  12067. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  12068. var ground = new BABYLON.GroundMesh(name, scene);
  12069. ground._subdivisions = subdivisions;
  12070. ground._setReady(false);
  12071. var onload = function (img) {
  12072. // Getting height map data
  12073. var canvas = document.createElement("canvas");
  12074. var context = canvas.getContext("2d");
  12075. var heightMapWidth = img.width;
  12076. var heightMapHeight = img.height;
  12077. canvas.width = heightMapWidth;
  12078. canvas.height = heightMapHeight;
  12079. context.drawImage(img, 0, 0);
  12080. // Create VertexData from map data
  12081. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  12082. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  12083. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  12084. vertexData.applyToMesh(ground, updatable);
  12085. ground._setReady(true);
  12086. //execute ready callback, if set
  12087. if (onReady) {
  12088. onReady(ground);
  12089. }
  12090. };
  12091. BABYLON.Tools.LoadImage(url, onload, function () {
  12092. }, scene.database);
  12093. return ground;
  12094. };
  12095. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, scene, updatable, sideOrientation, tubeInstance) {
  12096. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12097. if (tubeInstance === void 0) { tubeInstance = null; }
  12098. // tube geometry
  12099. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction) {
  12100. var tangents = path3D.getTangents();
  12101. var normals = path3D.getNormals();
  12102. var distances = path3D.getDistances();
  12103. var pi2 = Math.PI * 2;
  12104. var step = pi2 / tessellation;
  12105. var returnRadius = function (i, distance) { return radius; };
  12106. var radiusFunctionFinal = radiusFunction || returnRadius;
  12107. var circlePath;
  12108. var rad;
  12109. var normal;
  12110. var rotated;
  12111. var rotationMatrix;
  12112. var index = 0;
  12113. for (var i = 0; i < path.length; i++) {
  12114. rad = radiusFunctionFinal(i, distances[i]); // current radius
  12115. circlePath = Array(); // current circle array
  12116. normal = normals[i]; // current normal
  12117. for (var ang = 0; ang < pi2; ang += step) {
  12118. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  12119. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  12120. circlePath.push(rotated);
  12121. }
  12122. circlePaths[index] = circlePath;
  12123. index++;
  12124. }
  12125. return circlePaths;
  12126. };
  12127. if (tubeInstance) {
  12128. var path3D = (tubeInstance.path3D).update(path);
  12129. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction);
  12130. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  12131. return tubeInstance;
  12132. }
  12133. // tube creation
  12134. var path3D = new BABYLON.Path3D(path);
  12135. var newPathArray = new Array();
  12136. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction);
  12137. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  12138. tube.pathArray = pathArray;
  12139. tube.path3D = path3D;
  12140. tube.tessellation = tessellation;
  12141. return tube;
  12142. };
  12143. // Decals
  12144. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  12145. if (angle === void 0) { angle = 0; }
  12146. var indices = sourceMesh.getIndices();
  12147. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12148. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12149. // Getting correct rotation
  12150. if (!normal) {
  12151. var target = new BABYLON.Vector3(0, 0, 1);
  12152. var camera = sourceMesh.getScene().activeCamera;
  12153. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  12154. normal = camera.globalPosition.subtract(cameraWorldTarget);
  12155. }
  12156. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  12157. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  12158. var pitch = Math.atan2(normal.y, len);
  12159. // Matrix
  12160. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  12161. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  12162. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  12163. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  12164. var vertexData = new BABYLON.VertexData();
  12165. vertexData.indices = [];
  12166. vertexData.positions = [];
  12167. vertexData.normals = [];
  12168. vertexData.uvs = [];
  12169. var currentVertexDataIndex = 0;
  12170. var extractDecalVector3 = function (indexId) {
  12171. var vertexId = indices[indexId];
  12172. var result = new BABYLON.PositionNormalVertex();
  12173. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  12174. // Send vector to decal local world
  12175. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  12176. // Get normal
  12177. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  12178. return result;
  12179. };
  12180. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  12181. var clip = function (vertices, axis) {
  12182. if (vertices.length === 0) {
  12183. return vertices;
  12184. }
  12185. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  12186. var clipVertices = function (v0, v1) {
  12187. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  12188. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  12189. };
  12190. var result = new Array();
  12191. for (var index = 0; index < vertices.length; index += 3) {
  12192. var v1Out;
  12193. var v2Out;
  12194. var v3Out;
  12195. var total = 0;
  12196. var nV1, nV2, nV3, nV4;
  12197. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  12198. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  12199. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  12200. v1Out = d1 > 0;
  12201. v2Out = d2 > 0;
  12202. v3Out = d3 > 0;
  12203. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  12204. switch (total) {
  12205. case 0:
  12206. result.push(vertices[index]);
  12207. result.push(vertices[index + 1]);
  12208. result.push(vertices[index + 2]);
  12209. break;
  12210. case 1:
  12211. if (v1Out) {
  12212. nV1 = vertices[index + 1];
  12213. nV2 = vertices[index + 2];
  12214. nV3 = clipVertices(vertices[index], nV1);
  12215. nV4 = clipVertices(vertices[index], nV2);
  12216. }
  12217. if (v2Out) {
  12218. nV1 = vertices[index];
  12219. nV2 = vertices[index + 2];
  12220. nV3 = clipVertices(vertices[index + 1], nV1);
  12221. nV4 = clipVertices(vertices[index + 1], nV2);
  12222. result.push(nV3);
  12223. result.push(nV2.clone());
  12224. result.push(nV1.clone());
  12225. result.push(nV2.clone());
  12226. result.push(nV3.clone());
  12227. result.push(nV4);
  12228. break;
  12229. }
  12230. if (v3Out) {
  12231. nV1 = vertices[index];
  12232. nV2 = vertices[index + 1];
  12233. nV3 = clipVertices(vertices[index + 2], nV1);
  12234. nV4 = clipVertices(vertices[index + 2], nV2);
  12235. }
  12236. result.push(nV1.clone());
  12237. result.push(nV2.clone());
  12238. result.push(nV3);
  12239. result.push(nV4);
  12240. result.push(nV3.clone());
  12241. result.push(nV2.clone());
  12242. break;
  12243. case 2:
  12244. if (!v1Out) {
  12245. nV1 = vertices[index].clone();
  12246. nV2 = clipVertices(nV1, vertices[index + 1]);
  12247. nV3 = clipVertices(nV1, vertices[index + 2]);
  12248. result.push(nV1);
  12249. result.push(nV2);
  12250. result.push(nV3);
  12251. }
  12252. if (!v2Out) {
  12253. nV1 = vertices[index + 1].clone();
  12254. nV2 = clipVertices(nV1, vertices[index + 2]);
  12255. nV3 = clipVertices(nV1, vertices[index]);
  12256. result.push(nV1);
  12257. result.push(nV2);
  12258. result.push(nV3);
  12259. }
  12260. if (!v3Out) {
  12261. nV1 = vertices[index + 2].clone();
  12262. nV2 = clipVertices(nV1, vertices[index]);
  12263. nV3 = clipVertices(nV1, vertices[index + 1]);
  12264. result.push(nV1);
  12265. result.push(nV2);
  12266. result.push(nV3);
  12267. }
  12268. break;
  12269. case 3:
  12270. break;
  12271. }
  12272. }
  12273. return result;
  12274. };
  12275. for (var index = 0; index < indices.length; index += 3) {
  12276. var faceVertices = new Array();
  12277. faceVertices.push(extractDecalVector3(index));
  12278. faceVertices.push(extractDecalVector3(index + 1));
  12279. faceVertices.push(extractDecalVector3(index + 2));
  12280. // Clip
  12281. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12282. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12283. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12284. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12285. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12286. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12287. if (faceVertices.length === 0) {
  12288. continue;
  12289. }
  12290. // Add UVs and get back to world
  12291. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  12292. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12293. var vertex = faceVertices[vIndex];
  12294. vertexData.indices.push(currentVertexDataIndex);
  12295. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  12296. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12297. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12298. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12299. currentVertexDataIndex++;
  12300. }
  12301. }
  12302. // Return mesh
  12303. var decal = new Mesh(name, sourceMesh.getScene());
  12304. vertexData.applyToMesh(decal);
  12305. decal.position = position.clone();
  12306. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  12307. return decal;
  12308. };
  12309. // Tools
  12310. Mesh.MinMax = function (meshes) {
  12311. var minVector = null;
  12312. var maxVector = null;
  12313. for (var i in meshes) {
  12314. var mesh = meshes[i];
  12315. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12316. if (!minVector) {
  12317. minVector = boundingBox.minimumWorld;
  12318. maxVector = boundingBox.maximumWorld;
  12319. continue;
  12320. }
  12321. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12322. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12323. }
  12324. return {
  12325. min: minVector,
  12326. max: maxVector
  12327. };
  12328. };
  12329. Mesh.Center = function (meshesOrMinMaxVector) {
  12330. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12331. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12332. };
  12333. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  12334. if (disposeSource === void 0) { disposeSource = true; }
  12335. var source = meshes[0];
  12336. var material = source.material;
  12337. var scene = source.getScene();
  12338. if (!allow32BitsIndices) {
  12339. var totalVertices = 0;
  12340. for (var index = 0; index < meshes.length; index++) {
  12341. totalVertices += meshes[index].getTotalVertices();
  12342. if (totalVertices > 65536) {
  12343. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12344. return null;
  12345. }
  12346. }
  12347. }
  12348. // Merge
  12349. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  12350. vertexData.transform(source.getWorldMatrix());
  12351. for (index = 1; index < meshes.length; index++) {
  12352. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  12353. otherVertexData.transform(meshes[index].getWorldMatrix());
  12354. vertexData.merge(otherVertexData);
  12355. }
  12356. var newMesh = new Mesh(source.name + "_merged", scene);
  12357. vertexData.applyToMesh(newMesh);
  12358. // Setting properties
  12359. newMesh.material = material;
  12360. newMesh.checkCollisions = source.checkCollisions;
  12361. // Cleaning
  12362. if (disposeSource) {
  12363. for (index = 0; index < meshes.length; index++) {
  12364. meshes[index].dispose();
  12365. }
  12366. }
  12367. return newMesh;
  12368. };
  12369. // Consts
  12370. Mesh._FRONTSIDE = 0;
  12371. Mesh._BACKSIDE = 1;
  12372. Mesh._DOUBLESIDE = 2;
  12373. Mesh._DEFAULTSIDE = 0;
  12374. return Mesh;
  12375. })(BABYLON.AbstractMesh);
  12376. BABYLON.Mesh = Mesh;
  12377. })(BABYLON || (BABYLON = {}));
  12378. //# sourceMappingURL=babylon.mesh.js.map
  12379. var BABYLON;
  12380. (function (BABYLON) {
  12381. var GroundMesh = (function (_super) {
  12382. __extends(GroundMesh, _super);
  12383. function GroundMesh(name, scene) {
  12384. _super.call(this, name, scene);
  12385. this.generateOctree = false;
  12386. this._worldInverse = new BABYLON.Matrix();
  12387. }
  12388. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12389. get: function () {
  12390. return this._subdivisions;
  12391. },
  12392. enumerable: true,
  12393. configurable: true
  12394. });
  12395. GroundMesh.prototype.optimize = function (chunksCount) {
  12396. this.subdivide(this._subdivisions);
  12397. this.createOrUpdateSubmeshesOctree(32);
  12398. };
  12399. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12400. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12401. this.getWorldMatrix().invertToRef(this._worldInverse);
  12402. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12403. var pickInfo = this.intersects(ray);
  12404. if (pickInfo.hit) {
  12405. return pickInfo.pickedPoint.y;
  12406. }
  12407. return 0;
  12408. };
  12409. return GroundMesh;
  12410. })(BABYLON.Mesh);
  12411. BABYLON.GroundMesh = GroundMesh;
  12412. })(BABYLON || (BABYLON = {}));
  12413. //# sourceMappingURL=babylon.groundMesh.js.map
  12414. var BABYLON;
  12415. (function (BABYLON) {
  12416. /**
  12417. * Creates an instance based on a source mesh.
  12418. */
  12419. var InstancedMesh = (function (_super) {
  12420. __extends(InstancedMesh, _super);
  12421. function InstancedMesh(name, source) {
  12422. _super.call(this, name, source.getScene());
  12423. source.instances.push(this);
  12424. this._sourceMesh = source;
  12425. this.position.copyFrom(source.position);
  12426. this.rotation.copyFrom(source.rotation);
  12427. this.scaling.copyFrom(source.scaling);
  12428. if (source.rotationQuaternion) {
  12429. this.rotationQuaternion = source.rotationQuaternion.clone();
  12430. }
  12431. this.infiniteDistance = source.infiniteDistance;
  12432. this.setPivotMatrix(source.getPivotMatrix());
  12433. this.refreshBoundingInfo();
  12434. this._syncSubMeshes();
  12435. }
  12436. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12437. // Methods
  12438. get: function () {
  12439. return this._sourceMesh.receiveShadows;
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. Object.defineProperty(InstancedMesh.prototype, "material", {
  12445. get: function () {
  12446. return this._sourceMesh.material;
  12447. },
  12448. enumerable: true,
  12449. configurable: true
  12450. });
  12451. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12452. get: function () {
  12453. return this._sourceMesh.visibility;
  12454. },
  12455. enumerable: true,
  12456. configurable: true
  12457. });
  12458. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12459. get: function () {
  12460. return this._sourceMesh.skeleton;
  12461. },
  12462. enumerable: true,
  12463. configurable: true
  12464. });
  12465. InstancedMesh.prototype.getTotalVertices = function () {
  12466. return this._sourceMesh.getTotalVertices();
  12467. };
  12468. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12469. get: function () {
  12470. return this._sourceMesh;
  12471. },
  12472. enumerable: true,
  12473. configurable: true
  12474. });
  12475. InstancedMesh.prototype.getVerticesData = function (kind) {
  12476. return this._sourceMesh.getVerticesData(kind);
  12477. };
  12478. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12479. return this._sourceMesh.isVerticesDataPresent(kind);
  12480. };
  12481. InstancedMesh.prototype.getIndices = function () {
  12482. return this._sourceMesh.getIndices();
  12483. };
  12484. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12485. get: function () {
  12486. return this._sourceMesh._positions;
  12487. },
  12488. enumerable: true,
  12489. configurable: true
  12490. });
  12491. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12492. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12493. if (data) {
  12494. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12495. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12496. }
  12497. this._updateBoundingInfo();
  12498. };
  12499. InstancedMesh.prototype._preActivate = function () {
  12500. if (this._currentLOD) {
  12501. this._currentLOD._preActivate();
  12502. }
  12503. };
  12504. InstancedMesh.prototype._activate = function (renderId) {
  12505. if (this._currentLOD) {
  12506. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12507. }
  12508. };
  12509. InstancedMesh.prototype.getLOD = function (camera) {
  12510. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12511. if (this._currentLOD === this.sourceMesh) {
  12512. return this;
  12513. }
  12514. return this._currentLOD;
  12515. };
  12516. InstancedMesh.prototype._syncSubMeshes = function () {
  12517. this.releaseSubMeshes();
  12518. if (this._sourceMesh.subMeshes) {
  12519. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12520. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12521. }
  12522. }
  12523. };
  12524. InstancedMesh.prototype._generatePointsArray = function () {
  12525. return this._sourceMesh._generatePointsArray();
  12526. };
  12527. // Clone
  12528. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12529. var result = this._sourceMesh.createInstance(name);
  12530. // Deep copy
  12531. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12532. // Bounding info
  12533. this.refreshBoundingInfo();
  12534. // Parent
  12535. if (newParent) {
  12536. result.parent = newParent;
  12537. }
  12538. if (!doNotCloneChildren) {
  12539. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12540. var mesh = this.getScene().meshes[index];
  12541. if (mesh.parent === this) {
  12542. mesh.clone(mesh.name, result);
  12543. }
  12544. }
  12545. }
  12546. result.computeWorldMatrix(true);
  12547. return result;
  12548. };
  12549. // Dispoe
  12550. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12551. // Remove from mesh
  12552. var index = this._sourceMesh.instances.indexOf(this);
  12553. this._sourceMesh.instances.splice(index, 1);
  12554. _super.prototype.dispose.call(this, doNotRecurse);
  12555. };
  12556. return InstancedMesh;
  12557. })(BABYLON.AbstractMesh);
  12558. BABYLON.InstancedMesh = InstancedMesh;
  12559. })(BABYLON || (BABYLON = {}));
  12560. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12561. (function (BABYLON) {
  12562. var SubMesh = (function () {
  12563. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12564. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12565. this.materialIndex = materialIndex;
  12566. this.verticesStart = verticesStart;
  12567. this.verticesCount = verticesCount;
  12568. this.indexStart = indexStart;
  12569. this.indexCount = indexCount;
  12570. this._renderId = 0;
  12571. this._mesh = mesh;
  12572. this._renderingMesh = renderingMesh || mesh;
  12573. mesh.subMeshes.push(this);
  12574. this._id = mesh.subMeshes.length - 1;
  12575. if (createBoundingBox) {
  12576. this.refreshBoundingInfo();
  12577. mesh.computeWorldMatrix(true);
  12578. }
  12579. }
  12580. SubMesh.prototype.getBoundingInfo = function () {
  12581. return this._boundingInfo;
  12582. };
  12583. SubMesh.prototype.getMesh = function () {
  12584. return this._mesh;
  12585. };
  12586. SubMesh.prototype.getRenderingMesh = function () {
  12587. return this._renderingMesh;
  12588. };
  12589. SubMesh.prototype.getMaterial = function () {
  12590. var rootMaterial = this._renderingMesh.material;
  12591. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12592. var multiMaterial = rootMaterial;
  12593. return multiMaterial.getSubMaterial(this.materialIndex);
  12594. }
  12595. if (!rootMaterial) {
  12596. return this._mesh.getScene().defaultMaterial;
  12597. }
  12598. return rootMaterial;
  12599. };
  12600. // Methods
  12601. SubMesh.prototype.refreshBoundingInfo = function () {
  12602. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12603. if (!data) {
  12604. this._boundingInfo = this._mesh._boundingInfo;
  12605. return;
  12606. }
  12607. var indices = this._renderingMesh.getIndices();
  12608. var extend;
  12609. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12610. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12611. }
  12612. else {
  12613. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12614. }
  12615. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12616. };
  12617. SubMesh.prototype._checkCollision = function (collider) {
  12618. return this._boundingInfo._checkCollision(collider);
  12619. };
  12620. SubMesh.prototype.updateBoundingInfo = function (world) {
  12621. if (!this._boundingInfo) {
  12622. this.refreshBoundingInfo();
  12623. }
  12624. this._boundingInfo._update(world);
  12625. };
  12626. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12627. return this._boundingInfo.isInFrustum(frustumPlanes);
  12628. };
  12629. SubMesh.prototype.render = function () {
  12630. this._renderingMesh.render(this);
  12631. };
  12632. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12633. if (!this._linesIndexBuffer) {
  12634. var linesIndices = [];
  12635. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12636. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12637. }
  12638. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12639. this.linesIndexCount = linesIndices.length;
  12640. }
  12641. return this._linesIndexBuffer;
  12642. };
  12643. SubMesh.prototype.canIntersects = function (ray) {
  12644. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12645. };
  12646. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12647. var intersectInfo = null;
  12648. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12649. var p0 = positions[indices[index]];
  12650. var p1 = positions[indices[index + 1]];
  12651. var p2 = positions[indices[index + 2]];
  12652. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12653. if (currentIntersectInfo) {
  12654. if (currentIntersectInfo.distance < 0) {
  12655. continue;
  12656. }
  12657. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12658. intersectInfo = currentIntersectInfo;
  12659. intersectInfo.faceId = index / 3;
  12660. if (fastCheck) {
  12661. break;
  12662. }
  12663. }
  12664. }
  12665. }
  12666. return intersectInfo;
  12667. };
  12668. // Clone
  12669. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12670. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12671. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12672. return result;
  12673. };
  12674. // Dispose
  12675. SubMesh.prototype.dispose = function () {
  12676. if (this._linesIndexBuffer) {
  12677. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12678. this._linesIndexBuffer = null;
  12679. }
  12680. // Remove from mesh
  12681. var index = this._mesh.subMeshes.indexOf(this);
  12682. this._mesh.subMeshes.splice(index, 1);
  12683. };
  12684. // Statics
  12685. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12686. var minVertexIndex = Number.MAX_VALUE;
  12687. var maxVertexIndex = -Number.MAX_VALUE;
  12688. renderingMesh = renderingMesh || mesh;
  12689. var indices = renderingMesh.getIndices();
  12690. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12691. var vertexIndex = indices[index];
  12692. if (vertexIndex < minVertexIndex)
  12693. minVertexIndex = vertexIndex;
  12694. if (vertexIndex > maxVertexIndex)
  12695. maxVertexIndex = vertexIndex;
  12696. }
  12697. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12698. };
  12699. return SubMesh;
  12700. })();
  12701. BABYLON.SubMesh = SubMesh;
  12702. })(BABYLON || (BABYLON = {}));
  12703. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12704. (function (BABYLON) {
  12705. var BaseTexture = (function () {
  12706. function BaseTexture(scene) {
  12707. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12708. this.hasAlpha = false;
  12709. this.getAlphaFromRGB = false;
  12710. this.level = 1;
  12711. this.isCube = false;
  12712. this.isRenderTarget = false;
  12713. this.animations = new Array();
  12714. this.coordinatesIndex = 0;
  12715. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12716. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12717. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12718. this.anisotropicFilteringLevel = 4;
  12719. this._scene = scene;
  12720. this._scene.textures.push(this);
  12721. }
  12722. BaseTexture.prototype.getScene = function () {
  12723. return this._scene;
  12724. };
  12725. BaseTexture.prototype.getTextureMatrix = function () {
  12726. return null;
  12727. };
  12728. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12729. return null;
  12730. };
  12731. BaseTexture.prototype.getInternalTexture = function () {
  12732. return this._texture;
  12733. };
  12734. BaseTexture.prototype.isReady = function () {
  12735. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12736. return true;
  12737. }
  12738. if (this._texture) {
  12739. return this._texture.isReady;
  12740. }
  12741. return false;
  12742. };
  12743. BaseTexture.prototype.getSize = function () {
  12744. if (this._texture._width) {
  12745. return { width: this._texture._width, height: this._texture._height };
  12746. }
  12747. if (this._texture._size) {
  12748. return { width: this._texture._size, height: this._texture._size };
  12749. }
  12750. return { width: 0, height: 0 };
  12751. };
  12752. BaseTexture.prototype.getBaseSize = function () {
  12753. if (!this.isReady())
  12754. return { width: 0, height: 0 };
  12755. if (this._texture._size) {
  12756. return { width: this._texture._size, height: this._texture._size };
  12757. }
  12758. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12759. };
  12760. BaseTexture.prototype.scale = function (ratio) {
  12761. };
  12762. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12763. get: function () {
  12764. return false;
  12765. },
  12766. enumerable: true,
  12767. configurable: true
  12768. });
  12769. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12770. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12771. for (var index = 0; index < texturesCache.length; index++) {
  12772. var texturesCacheEntry = texturesCache[index];
  12773. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12774. texturesCache.splice(index, 1);
  12775. return;
  12776. }
  12777. }
  12778. };
  12779. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12780. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12781. for (var index = 0; index < texturesCache.length; index++) {
  12782. var texturesCacheEntry = texturesCache[index];
  12783. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12784. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12785. texturesCacheEntry.references++;
  12786. return texturesCacheEntry;
  12787. }
  12788. }
  12789. }
  12790. return null;
  12791. };
  12792. BaseTexture.prototype.delayLoad = function () {
  12793. };
  12794. BaseTexture.prototype.releaseInternalTexture = function () {
  12795. if (!this._texture) {
  12796. return;
  12797. }
  12798. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12799. this._texture.references--;
  12800. // Final reference ?
  12801. if (this._texture.references === 0) {
  12802. var index = texturesCache.indexOf(this._texture);
  12803. texturesCache.splice(index, 1);
  12804. this._scene.getEngine()._releaseTexture(this._texture);
  12805. delete this._texture;
  12806. }
  12807. };
  12808. BaseTexture.prototype.clone = function () {
  12809. return null;
  12810. };
  12811. BaseTexture.prototype.dispose = function () {
  12812. // Remove from scene
  12813. var index = this._scene.textures.indexOf(this);
  12814. if (index >= 0) {
  12815. this._scene.textures.splice(index, 1);
  12816. }
  12817. if (this._texture === undefined) {
  12818. return;
  12819. }
  12820. this.releaseInternalTexture();
  12821. // Callback
  12822. if (this.onDispose) {
  12823. this.onDispose();
  12824. }
  12825. };
  12826. return BaseTexture;
  12827. })();
  12828. BABYLON.BaseTexture = BaseTexture;
  12829. })(BABYLON || (BABYLON = {}));
  12830. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12831. (function (BABYLON) {
  12832. var RenderingGroup = (function () {
  12833. function RenderingGroup(index, scene) {
  12834. this.index = index;
  12835. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12836. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12837. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12838. this._scene = scene;
  12839. }
  12840. RenderingGroup.prototype.render = function (customRenderFunction) {
  12841. if (customRenderFunction) {
  12842. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12843. return true;
  12844. }
  12845. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12846. return false;
  12847. }
  12848. var engine = this._scene.getEngine();
  12849. // Opaque
  12850. var subIndex;
  12851. var submesh;
  12852. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12853. submesh = this._opaqueSubMeshes.data[subIndex];
  12854. submesh.render();
  12855. }
  12856. // Alpha test
  12857. engine.setAlphaTesting(true);
  12858. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12859. submesh = this._alphaTestSubMeshes.data[subIndex];
  12860. submesh.render();
  12861. }
  12862. engine.setAlphaTesting(false);
  12863. // Transparent
  12864. if (this._transparentSubMeshes.length) {
  12865. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12866. submesh = this._transparentSubMeshes.data[subIndex];
  12867. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12868. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12869. }
  12870. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12871. sortedArray.sort(function (a, b) {
  12872. // Alpha index first
  12873. if (a._alphaIndex > b._alphaIndex) {
  12874. return 1;
  12875. }
  12876. if (a._alphaIndex < b._alphaIndex) {
  12877. return -1;
  12878. }
  12879. // Then distance to camera
  12880. if (a._distanceToCamera < b._distanceToCamera) {
  12881. return 1;
  12882. }
  12883. if (a._distanceToCamera > b._distanceToCamera) {
  12884. return -1;
  12885. }
  12886. return 0;
  12887. });
  12888. // Rendering
  12889. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12890. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12891. submesh = sortedArray[subIndex];
  12892. submesh.render();
  12893. }
  12894. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12895. }
  12896. return true;
  12897. };
  12898. RenderingGroup.prototype.prepare = function () {
  12899. this._opaqueSubMeshes.reset();
  12900. this._transparentSubMeshes.reset();
  12901. this._alphaTestSubMeshes.reset();
  12902. };
  12903. RenderingGroup.prototype.dispatch = function (subMesh) {
  12904. var material = subMesh.getMaterial();
  12905. var mesh = subMesh.getMesh();
  12906. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12907. this._transparentSubMeshes.push(subMesh);
  12908. }
  12909. else if (material.needAlphaTesting()) {
  12910. this._alphaTestSubMeshes.push(subMesh);
  12911. }
  12912. else {
  12913. this._opaqueSubMeshes.push(subMesh); // Opaque
  12914. }
  12915. };
  12916. return RenderingGroup;
  12917. })();
  12918. BABYLON.RenderingGroup = RenderingGroup;
  12919. })(BABYLON || (BABYLON = {}));
  12920. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12921. (function (BABYLON) {
  12922. var RenderingManager = (function () {
  12923. function RenderingManager(scene) {
  12924. this._renderingGroups = new Array();
  12925. this._scene = scene;
  12926. }
  12927. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12928. if (this._scene._activeParticleSystems.length === 0) {
  12929. return;
  12930. }
  12931. // Particles
  12932. var beforeParticlesDate = BABYLON.Tools.Now;
  12933. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12934. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12935. if (particleSystem.renderingGroupId !== index) {
  12936. continue;
  12937. }
  12938. this._clearDepthBuffer();
  12939. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12940. this._scene._activeParticles += particleSystem.render();
  12941. }
  12942. }
  12943. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12944. };
  12945. RenderingManager.prototype._renderSprites = function (index) {
  12946. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12947. return;
  12948. }
  12949. // Sprites
  12950. var beforeSpritessDate = BABYLON.Tools.Now;
  12951. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12952. var spriteManager = this._scene.spriteManagers[id];
  12953. if (spriteManager.renderingGroupId === index) {
  12954. this._clearDepthBuffer();
  12955. spriteManager.render();
  12956. }
  12957. }
  12958. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12959. };
  12960. RenderingManager.prototype._clearDepthBuffer = function () {
  12961. if (this._depthBufferAlreadyCleaned) {
  12962. return;
  12963. }
  12964. this._scene.getEngine().clear(0, false, true);
  12965. this._depthBufferAlreadyCleaned = true;
  12966. };
  12967. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12968. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12969. this._depthBufferAlreadyCleaned = false;
  12970. var renderingGroup = this._renderingGroups[index];
  12971. var needToStepBack = false;
  12972. if (renderingGroup) {
  12973. this._clearDepthBuffer();
  12974. if (!renderingGroup.render(customRenderFunction)) {
  12975. this._renderingGroups.splice(index, 1);
  12976. needToStepBack = true;
  12977. }
  12978. }
  12979. if (renderSprites) {
  12980. this._renderSprites(index);
  12981. }
  12982. if (renderParticles) {
  12983. this._renderParticles(index, activeMeshes);
  12984. }
  12985. if (needToStepBack) {
  12986. index--;
  12987. }
  12988. }
  12989. };
  12990. RenderingManager.prototype.reset = function () {
  12991. for (var index in this._renderingGroups) {
  12992. var renderingGroup = this._renderingGroups[index];
  12993. renderingGroup.prepare();
  12994. }
  12995. };
  12996. RenderingManager.prototype.dispatch = function (subMesh) {
  12997. var mesh = subMesh.getMesh();
  12998. var renderingGroupId = mesh.renderingGroupId || 0;
  12999. if (!this._renderingGroups[renderingGroupId]) {
  13000. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13001. }
  13002. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13003. };
  13004. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13005. return RenderingManager;
  13006. })();
  13007. BABYLON.RenderingManager = RenderingManager;
  13008. })(BABYLON || (BABYLON = {}));
  13009. //# sourceMappingURL=babylon.renderingManager.js.map
  13010. var BABYLON;
  13011. (function (BABYLON) {
  13012. var Texture = (function (_super) {
  13013. __extends(Texture, _super);
  13014. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  13015. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13016. if (onLoad === void 0) { onLoad = null; }
  13017. if (onError === void 0) { onError = null; }
  13018. if (buffer === void 0) { buffer = null; }
  13019. if (deleteBuffer === void 0) { deleteBuffer = false; }
  13020. _super.call(this, scene);
  13021. this.uOffset = 0;
  13022. this.vOffset = 0;
  13023. this.uScale = 1.0;
  13024. this.vScale = 1.0;
  13025. this.uAng = 0;
  13026. this.vAng = 0;
  13027. this.wAng = 0;
  13028. this.name = url;
  13029. this.url = url;
  13030. this._noMipmap = noMipmap;
  13031. this._invertY = invertY;
  13032. this._samplingMode = samplingMode;
  13033. this._buffer = buffer;
  13034. this._deleteBuffer = deleteBuffer;
  13035. if (!url) {
  13036. return;
  13037. }
  13038. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  13039. if (!this._texture) {
  13040. if (!scene.useDelayedTextureLoading) {
  13041. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  13042. if (deleteBuffer) {
  13043. delete this._buffer;
  13044. }
  13045. }
  13046. else {
  13047. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13048. }
  13049. }
  13050. }
  13051. Texture.prototype.delayLoad = function () {
  13052. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13053. return;
  13054. }
  13055. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13056. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  13057. if (!this._texture) {
  13058. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  13059. if (this._deleteBuffer) {
  13060. delete this._buffer;
  13061. }
  13062. }
  13063. };
  13064. Texture.prototype.updateSamplingMode = function (samplingMode) {
  13065. if (!this._texture) {
  13066. return;
  13067. }
  13068. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  13069. };
  13070. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  13071. x -= this.uOffset + 0.5;
  13072. y -= this.vOffset + 0.5;
  13073. z -= 0.5;
  13074. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  13075. t.x *= this.uScale;
  13076. t.y *= this.vScale;
  13077. t.x += 0.5;
  13078. t.y += 0.5;
  13079. t.z += 0.5;
  13080. };
  13081. Texture.prototype.getTextureMatrix = function () {
  13082. 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) {
  13083. return this._cachedTextureMatrix;
  13084. }
  13085. this._cachedUOffset = this.uOffset;
  13086. this._cachedVOffset = this.vOffset;
  13087. this._cachedUScale = this.uScale;
  13088. this._cachedVScale = this.vScale;
  13089. this._cachedUAng = this.uAng;
  13090. this._cachedVAng = this.vAng;
  13091. this._cachedWAng = this.wAng;
  13092. if (!this._cachedTextureMatrix) {
  13093. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13094. this._rowGenerationMatrix = new BABYLON.Matrix();
  13095. this._t0 = BABYLON.Vector3.Zero();
  13096. this._t1 = BABYLON.Vector3.Zero();
  13097. this._t2 = BABYLON.Vector3.Zero();
  13098. }
  13099. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  13100. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  13101. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  13102. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  13103. this._t1.subtractInPlace(this._t0);
  13104. this._t2.subtractInPlace(this._t0);
  13105. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13106. this._cachedTextureMatrix.m[0] = this._t1.x;
  13107. this._cachedTextureMatrix.m[1] = this._t1.y;
  13108. this._cachedTextureMatrix.m[2] = this._t1.z;
  13109. this._cachedTextureMatrix.m[4] = this._t2.x;
  13110. this._cachedTextureMatrix.m[5] = this._t2.y;
  13111. this._cachedTextureMatrix.m[6] = this._t2.z;
  13112. this._cachedTextureMatrix.m[8] = this._t0.x;
  13113. this._cachedTextureMatrix.m[9] = this._t0.y;
  13114. this._cachedTextureMatrix.m[10] = this._t0.z;
  13115. return this._cachedTextureMatrix;
  13116. };
  13117. Texture.prototype.getReflectionTextureMatrix = function () {
  13118. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  13119. return this._cachedTextureMatrix;
  13120. }
  13121. if (!this._cachedTextureMatrix) {
  13122. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13123. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  13124. }
  13125. this._cachedCoordinatesMode = this.coordinatesMode;
  13126. switch (this.coordinatesMode) {
  13127. case Texture.SPHERICAL_MODE:
  13128. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13129. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  13130. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  13131. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  13132. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  13133. break;
  13134. case Texture.PLANAR_MODE:
  13135. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13136. this._cachedTextureMatrix[0] = this.uScale;
  13137. this._cachedTextureMatrix[5] = this.vScale;
  13138. this._cachedTextureMatrix[12] = this.uOffset;
  13139. this._cachedTextureMatrix[13] = this.vOffset;
  13140. break;
  13141. case Texture.PROJECTION_MODE:
  13142. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  13143. this._projectionModeMatrix.m[0] = 0.5;
  13144. this._projectionModeMatrix.m[5] = -0.5;
  13145. this._projectionModeMatrix.m[10] = 0.0;
  13146. this._projectionModeMatrix.m[12] = 0.5;
  13147. this._projectionModeMatrix.m[13] = 0.5;
  13148. this._projectionModeMatrix.m[14] = 1.0;
  13149. this._projectionModeMatrix.m[15] = 1.0;
  13150. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  13151. break;
  13152. default:
  13153. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13154. break;
  13155. }
  13156. return this._cachedTextureMatrix;
  13157. };
  13158. Texture.prototype.clone = function () {
  13159. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  13160. // Base texture
  13161. newTexture.hasAlpha = this.hasAlpha;
  13162. newTexture.level = this.level;
  13163. newTexture.wrapU = this.wrapU;
  13164. newTexture.wrapV = this.wrapV;
  13165. newTexture.coordinatesIndex = this.coordinatesIndex;
  13166. newTexture.coordinatesMode = this.coordinatesMode;
  13167. // Texture
  13168. newTexture.uOffset = this.uOffset;
  13169. newTexture.vOffset = this.vOffset;
  13170. newTexture.uScale = this.uScale;
  13171. newTexture.vScale = this.vScale;
  13172. newTexture.uAng = this.uAng;
  13173. newTexture.vAng = this.vAng;
  13174. newTexture.wAng = this.wAng;
  13175. return newTexture;
  13176. };
  13177. // Statics
  13178. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  13179. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13180. if (onLoad === void 0) { onLoad = null; }
  13181. if (onError === void 0) { onError = null; }
  13182. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  13183. };
  13184. // Constants
  13185. Texture.NEAREST_SAMPLINGMODE = 1;
  13186. Texture.BILINEAR_SAMPLINGMODE = 2;
  13187. Texture.TRILINEAR_SAMPLINGMODE = 3;
  13188. Texture.EXPLICIT_MODE = 0;
  13189. Texture.SPHERICAL_MODE = 1;
  13190. Texture.PLANAR_MODE = 2;
  13191. Texture.CUBIC_MODE = 3;
  13192. Texture.PROJECTION_MODE = 4;
  13193. Texture.SKYBOX_MODE = 5;
  13194. Texture.CLAMP_ADDRESSMODE = 0;
  13195. Texture.WRAP_ADDRESSMODE = 1;
  13196. Texture.MIRROR_ADDRESSMODE = 2;
  13197. return Texture;
  13198. })(BABYLON.BaseTexture);
  13199. BABYLON.Texture = Texture;
  13200. })(BABYLON || (BABYLON = {}));
  13201. //# sourceMappingURL=babylon.texture.js.map
  13202. var BABYLON;
  13203. (function (BABYLON) {
  13204. var CubeTexture = (function (_super) {
  13205. __extends(CubeTexture, _super);
  13206. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  13207. _super.call(this, scene);
  13208. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  13209. this.name = rootUrl;
  13210. this.url = rootUrl;
  13211. this._noMipmap = noMipmap;
  13212. this.hasAlpha = false;
  13213. this._texture = this._getFromCache(rootUrl, noMipmap);
  13214. if (!extensions) {
  13215. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  13216. }
  13217. this._extensions = extensions;
  13218. if (!this._texture) {
  13219. if (!scene.useDelayedTextureLoading) {
  13220. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  13221. }
  13222. else {
  13223. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13224. }
  13225. }
  13226. this.isCube = true;
  13227. this._textureMatrix = BABYLON.Matrix.Identity();
  13228. }
  13229. CubeTexture.prototype.clone = function () {
  13230. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  13231. // Base texture
  13232. newTexture.level = this.level;
  13233. newTexture.wrapU = this.wrapU;
  13234. newTexture.wrapV = this.wrapV;
  13235. newTexture.coordinatesIndex = this.coordinatesIndex;
  13236. newTexture.coordinatesMode = this.coordinatesMode;
  13237. return newTexture;
  13238. };
  13239. // Methods
  13240. CubeTexture.prototype.delayLoad = function () {
  13241. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13242. return;
  13243. }
  13244. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13245. this._texture = this._getFromCache(this.url, this._noMipmap);
  13246. if (!this._texture) {
  13247. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13248. }
  13249. };
  13250. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13251. return this._textureMatrix;
  13252. };
  13253. return CubeTexture;
  13254. })(BABYLON.BaseTexture);
  13255. BABYLON.CubeTexture = CubeTexture;
  13256. })(BABYLON || (BABYLON = {}));
  13257. //# sourceMappingURL=babylon.cubeTexture.js.map
  13258. var BABYLON;
  13259. (function (BABYLON) {
  13260. var RenderTargetTexture = (function (_super) {
  13261. __extends(RenderTargetTexture, _super);
  13262. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13263. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13264. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13265. _super.call(this, null, scene, !generateMipMaps);
  13266. this.renderList = new Array();
  13267. this.renderParticles = true;
  13268. this.renderSprites = false;
  13269. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13270. this._currentRefreshId = -1;
  13271. this._refreshRate = 1;
  13272. this.name = name;
  13273. this.isRenderTarget = true;
  13274. this._size = size;
  13275. this._generateMipMaps = generateMipMaps;
  13276. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13277. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13278. // Rendering groups
  13279. this._renderingManager = new BABYLON.RenderingManager(scene);
  13280. }
  13281. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13282. this._currentRefreshId = -1;
  13283. };
  13284. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13285. get: function () {
  13286. return this._refreshRate;
  13287. },
  13288. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13289. set: function (value) {
  13290. this._refreshRate = value;
  13291. this.resetRefreshCounter();
  13292. },
  13293. enumerable: true,
  13294. configurable: true
  13295. });
  13296. RenderTargetTexture.prototype._shouldRender = function () {
  13297. if (this._currentRefreshId === -1) {
  13298. this._currentRefreshId = 1;
  13299. return true;
  13300. }
  13301. if (this.refreshRate === this._currentRefreshId) {
  13302. this._currentRefreshId = 1;
  13303. return true;
  13304. }
  13305. this._currentRefreshId++;
  13306. return false;
  13307. };
  13308. RenderTargetTexture.prototype.isReady = function () {
  13309. if (!this.getScene().renderTargetsEnabled) {
  13310. return false;
  13311. }
  13312. return _super.prototype.isReady.call(this);
  13313. };
  13314. RenderTargetTexture.prototype.getRenderSize = function () {
  13315. return this._size;
  13316. };
  13317. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13318. get: function () {
  13319. return true;
  13320. },
  13321. enumerable: true,
  13322. configurable: true
  13323. });
  13324. RenderTargetTexture.prototype.scale = function (ratio) {
  13325. var newSize = this._size * ratio;
  13326. this.resize(newSize, this._generateMipMaps);
  13327. };
  13328. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13329. this.releaseInternalTexture();
  13330. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13331. };
  13332. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13333. var scene = this.getScene();
  13334. var engine = scene.getEngine();
  13335. if (this._waitingRenderList) {
  13336. this.renderList = [];
  13337. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13338. var id = this._waitingRenderList[index];
  13339. this.renderList.push(scene.getMeshByID(id));
  13340. }
  13341. delete this._waitingRenderList;
  13342. }
  13343. if (this.renderList && this.renderList.length === 0) {
  13344. return;
  13345. }
  13346. // Bind
  13347. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13348. engine.bindFramebuffer(this._texture);
  13349. }
  13350. this._renderingManager.reset();
  13351. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13352. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13353. var mesh = currentRenderList[meshIndex];
  13354. if (mesh) {
  13355. if (!mesh.isReady()) {
  13356. // Reset _currentRefreshId
  13357. this.resetRefreshCounter();
  13358. continue;
  13359. }
  13360. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13361. mesh._activate(scene.getRenderId());
  13362. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13363. var subMesh = mesh.subMeshes[subIndex];
  13364. scene._activeIndices += subMesh.indexCount;
  13365. this._renderingManager.dispatch(subMesh);
  13366. }
  13367. }
  13368. }
  13369. }
  13370. if (this.onBeforeRender) {
  13371. this.onBeforeRender();
  13372. }
  13373. // Clear
  13374. if (this.onClear) {
  13375. this.onClear(engine);
  13376. }
  13377. else {
  13378. engine.clear(scene.clearColor, true, true);
  13379. }
  13380. if (!this._doNotChangeAspectRatio) {
  13381. scene.updateTransformMatrix(true);
  13382. }
  13383. // Render
  13384. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13385. if (useCameraPostProcess) {
  13386. scene.postProcessManager._finalizeFrame(false, this._texture);
  13387. }
  13388. if (!this._doNotChangeAspectRatio) {
  13389. scene.updateTransformMatrix(true);
  13390. }
  13391. if (this.onAfterRender) {
  13392. this.onAfterRender();
  13393. }
  13394. // Dump ?
  13395. if (dumpForDebug) {
  13396. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13397. }
  13398. // Unbind
  13399. engine.unBindFramebuffer(this._texture);
  13400. if (this.onAfterUnbind) {
  13401. this.onAfterUnbind();
  13402. }
  13403. };
  13404. RenderTargetTexture.prototype.clone = function () {
  13405. var textureSize = this.getSize();
  13406. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13407. // Base texture
  13408. newTexture.hasAlpha = this.hasAlpha;
  13409. newTexture.level = this.level;
  13410. // RenderTarget Texture
  13411. newTexture.coordinatesMode = this.coordinatesMode;
  13412. newTexture.renderList = this.renderList.slice(0);
  13413. return newTexture;
  13414. };
  13415. return RenderTargetTexture;
  13416. })(BABYLON.Texture);
  13417. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13418. })(BABYLON || (BABYLON = {}));
  13419. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13420. var BABYLON;
  13421. (function (BABYLON) {
  13422. var ProceduralTexture = (function (_super) {
  13423. __extends(ProceduralTexture, _super);
  13424. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13425. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13426. _super.call(this, null, scene, !generateMipMaps);
  13427. this._currentRefreshId = -1;
  13428. this._refreshRate = 1;
  13429. this._vertexDeclaration = [2];
  13430. this._vertexStrideSize = 2 * 4;
  13431. this._uniforms = new Array();
  13432. this._samplers = new Array();
  13433. this._textures = new Array();
  13434. this._floats = new Array();
  13435. this._floatsArrays = {};
  13436. this._colors3 = new Array();
  13437. this._colors4 = new Array();
  13438. this._vectors2 = new Array();
  13439. this._vectors3 = new Array();
  13440. this._matrices = new Array();
  13441. this._fallbackTextureUsed = false;
  13442. scene._proceduralTextures.push(this);
  13443. this.name = name;
  13444. this.isRenderTarget = true;
  13445. this._size = size;
  13446. this._generateMipMaps = generateMipMaps;
  13447. this.setFragment(fragment);
  13448. this._fallbackTexture = fallbackTexture;
  13449. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13450. // VBO
  13451. var vertices = [];
  13452. vertices.push(1, 1);
  13453. vertices.push(-1, 1);
  13454. vertices.push(-1, -1);
  13455. vertices.push(1, -1);
  13456. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13457. // Indices
  13458. var indices = [];
  13459. indices.push(0);
  13460. indices.push(1);
  13461. indices.push(2);
  13462. indices.push(0);
  13463. indices.push(2);
  13464. indices.push(3);
  13465. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13466. }
  13467. ProceduralTexture.prototype.reset = function () {
  13468. if (this._effect === undefined) {
  13469. return;
  13470. }
  13471. var engine = this.getScene().getEngine();
  13472. engine._releaseEffect(this._effect);
  13473. };
  13474. ProceduralTexture.prototype.isReady = function () {
  13475. var _this = this;
  13476. var engine = this.getScene().getEngine();
  13477. var shaders;
  13478. if (!this._fragment) {
  13479. return false;
  13480. }
  13481. if (this._fallbackTextureUsed) {
  13482. return true;
  13483. }
  13484. if (this._fragment.fragmentElement !== undefined) {
  13485. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13486. }
  13487. else {
  13488. shaders = { vertex: "procedural", fragment: this._fragment };
  13489. }
  13490. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13491. _this.releaseInternalTexture();
  13492. if (_this._fallbackTexture) {
  13493. _this._texture = _this._fallbackTexture._texture;
  13494. _this._texture.references++;
  13495. }
  13496. _this._fallbackTextureUsed = true;
  13497. });
  13498. return this._effect.isReady();
  13499. };
  13500. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13501. this._currentRefreshId = -1;
  13502. };
  13503. ProceduralTexture.prototype.setFragment = function (fragment) {
  13504. this._fragment = fragment;
  13505. };
  13506. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13507. get: function () {
  13508. return this._refreshRate;
  13509. },
  13510. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13511. set: function (value) {
  13512. this._refreshRate = value;
  13513. this.resetRefreshCounter();
  13514. },
  13515. enumerable: true,
  13516. configurable: true
  13517. });
  13518. ProceduralTexture.prototype._shouldRender = function () {
  13519. if (!this.isReady() || !this._texture) {
  13520. return false;
  13521. }
  13522. if (this._fallbackTextureUsed) {
  13523. return false;
  13524. }
  13525. if (this._currentRefreshId === -1) {
  13526. this._currentRefreshId = 1;
  13527. return true;
  13528. }
  13529. if (this.refreshRate === this._currentRefreshId) {
  13530. this._currentRefreshId = 1;
  13531. return true;
  13532. }
  13533. this._currentRefreshId++;
  13534. return false;
  13535. };
  13536. ProceduralTexture.prototype.getRenderSize = function () {
  13537. return this._size;
  13538. };
  13539. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13540. if (this._fallbackTextureUsed) {
  13541. return;
  13542. }
  13543. this.releaseInternalTexture();
  13544. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13545. };
  13546. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13547. if (this._uniforms.indexOf(uniformName) === -1) {
  13548. this._uniforms.push(uniformName);
  13549. }
  13550. };
  13551. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13552. if (this._samplers.indexOf(name) === -1) {
  13553. this._samplers.push(name);
  13554. }
  13555. this._textures[name] = texture;
  13556. return this;
  13557. };
  13558. ProceduralTexture.prototype.setFloat = function (name, value) {
  13559. this._checkUniform(name);
  13560. this._floats[name] = value;
  13561. return this;
  13562. };
  13563. ProceduralTexture.prototype.setFloats = function (name, value) {
  13564. this._checkUniform(name);
  13565. this._floatsArrays[name] = value;
  13566. return this;
  13567. };
  13568. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13569. this._checkUniform(name);
  13570. this._colors3[name] = value;
  13571. return this;
  13572. };
  13573. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13574. this._checkUniform(name);
  13575. this._colors4[name] = value;
  13576. return this;
  13577. };
  13578. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13579. this._checkUniform(name);
  13580. this._vectors2[name] = value;
  13581. return this;
  13582. };
  13583. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13584. this._checkUniform(name);
  13585. this._vectors3[name] = value;
  13586. return this;
  13587. };
  13588. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13589. this._checkUniform(name);
  13590. this._matrices[name] = value;
  13591. return this;
  13592. };
  13593. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13594. var scene = this.getScene();
  13595. var engine = scene.getEngine();
  13596. engine.bindFramebuffer(this._texture);
  13597. // Clear
  13598. engine.clear(scene.clearColor, true, true);
  13599. // Render
  13600. engine.enableEffect(this._effect);
  13601. engine.setState(false);
  13602. for (var name in this._textures) {
  13603. this._effect.setTexture(name, this._textures[name]);
  13604. }
  13605. for (name in this._floats) {
  13606. this._effect.setFloat(name, this._floats[name]);
  13607. }
  13608. for (name in this._floatsArrays) {
  13609. this._effect.setArray(name, this._floatsArrays[name]);
  13610. }
  13611. for (name in this._colors3) {
  13612. this._effect.setColor3(name, this._colors3[name]);
  13613. }
  13614. for (name in this._colors4) {
  13615. var color = this._colors4[name];
  13616. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13617. }
  13618. for (name in this._vectors2) {
  13619. this._effect.setVector2(name, this._vectors2[name]);
  13620. }
  13621. for (name in this._vectors3) {
  13622. this._effect.setVector3(name, this._vectors3[name]);
  13623. }
  13624. for (name in this._matrices) {
  13625. this._effect.setMatrix(name, this._matrices[name]);
  13626. }
  13627. // VBOs
  13628. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13629. // Draw order
  13630. engine.draw(true, 0, 6);
  13631. // Unbind
  13632. engine.unBindFramebuffer(this._texture);
  13633. };
  13634. ProceduralTexture.prototype.clone = function () {
  13635. var textureSize = this.getSize();
  13636. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13637. // Base texture
  13638. newTexture.hasAlpha = this.hasAlpha;
  13639. newTexture.level = this.level;
  13640. // RenderTarget Texture
  13641. newTexture.coordinatesMode = this.coordinatesMode;
  13642. return newTexture;
  13643. };
  13644. ProceduralTexture.prototype.dispose = function () {
  13645. var index = this.getScene()._proceduralTextures.indexOf(this);
  13646. if (index >= 0) {
  13647. this.getScene()._proceduralTextures.splice(index, 1);
  13648. }
  13649. _super.prototype.dispose.call(this);
  13650. };
  13651. return ProceduralTexture;
  13652. })(BABYLON.Texture);
  13653. BABYLON.ProceduralTexture = ProceduralTexture;
  13654. })(BABYLON || (BABYLON = {}));
  13655. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13656. var BABYLON;
  13657. (function (BABYLON) {
  13658. var WoodProceduralTexture = (function (_super) {
  13659. __extends(WoodProceduralTexture, _super);
  13660. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13661. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13662. this._ampScale = 100.0;
  13663. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13664. this.updateShaderUniforms();
  13665. this.refreshRate = 0;
  13666. }
  13667. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13668. this.setFloat("ampScale", this._ampScale);
  13669. this.setColor3("woodColor", this._woodColor);
  13670. };
  13671. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13672. get: function () {
  13673. return this._ampScale;
  13674. },
  13675. set: function (value) {
  13676. this._ampScale = value;
  13677. this.updateShaderUniforms();
  13678. },
  13679. enumerable: true,
  13680. configurable: true
  13681. });
  13682. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13683. get: function () {
  13684. return this._woodColor;
  13685. },
  13686. set: function (value) {
  13687. this._woodColor = value;
  13688. this.updateShaderUniforms();
  13689. },
  13690. enumerable: true,
  13691. configurable: true
  13692. });
  13693. return WoodProceduralTexture;
  13694. })(BABYLON.ProceduralTexture);
  13695. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13696. var FireProceduralTexture = (function (_super) {
  13697. __extends(FireProceduralTexture, _super);
  13698. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13699. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13700. this._time = 0.0;
  13701. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13702. this._autoGenerateTime = true;
  13703. this._alphaThreshold = 0.5;
  13704. this._fireColors = FireProceduralTexture.RedFireColors;
  13705. this.updateShaderUniforms();
  13706. this.refreshRate = 1;
  13707. }
  13708. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13709. this.setFloat("time", this._time);
  13710. this.setVector2("speed", this._speed);
  13711. this.setColor3("c1", this._fireColors[0]);
  13712. this.setColor3("c2", this._fireColors[1]);
  13713. this.setColor3("c3", this._fireColors[2]);
  13714. this.setColor3("c4", this._fireColors[3]);
  13715. this.setColor3("c5", this._fireColors[4]);
  13716. this.setColor3("c6", this._fireColors[5]);
  13717. this.setFloat("alphaThreshold", this._alphaThreshold);
  13718. };
  13719. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13720. if (this._autoGenerateTime) {
  13721. this._time += this.getScene().getAnimationRatio() * 0.03;
  13722. this.updateShaderUniforms();
  13723. }
  13724. _super.prototype.render.call(this, useCameraPostProcess);
  13725. };
  13726. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13727. get: function () {
  13728. return [
  13729. new BABYLON.Color3(0.5, 0.0, 1.0),
  13730. new BABYLON.Color3(0.9, 0.0, 1.0),
  13731. new BABYLON.Color3(0.2, 0.0, 1.0),
  13732. new BABYLON.Color3(1.0, 0.9, 1.0),
  13733. new BABYLON.Color3(0.1, 0.1, 1.0),
  13734. new BABYLON.Color3(0.9, 0.9, 1.0)
  13735. ];
  13736. },
  13737. enumerable: true,
  13738. configurable: true
  13739. });
  13740. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13741. get: function () {
  13742. return [
  13743. new BABYLON.Color3(0.5, 1.0, 0.0),
  13744. new BABYLON.Color3(0.5, 1.0, 0.0),
  13745. new BABYLON.Color3(0.3, 0.4, 0.0),
  13746. new BABYLON.Color3(0.5, 1.0, 0.0),
  13747. new BABYLON.Color3(0.2, 0.0, 0.0),
  13748. new BABYLON.Color3(0.5, 1.0, 0.0)
  13749. ];
  13750. },
  13751. enumerable: true,
  13752. configurable: true
  13753. });
  13754. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13755. get: function () {
  13756. return [
  13757. new BABYLON.Color3(0.5, 0.0, 0.1),
  13758. new BABYLON.Color3(0.9, 0.0, 0.0),
  13759. new BABYLON.Color3(0.2, 0.0, 0.0),
  13760. new BABYLON.Color3(1.0, 0.9, 0.0),
  13761. new BABYLON.Color3(0.1, 0.1, 0.1),
  13762. new BABYLON.Color3(0.9, 0.9, 0.9)
  13763. ];
  13764. },
  13765. enumerable: true,
  13766. configurable: true
  13767. });
  13768. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13769. get: function () {
  13770. return [
  13771. new BABYLON.Color3(0.1, 0.0, 0.5),
  13772. new BABYLON.Color3(0.0, 0.0, 0.5),
  13773. new BABYLON.Color3(0.1, 0.0, 0.2),
  13774. new BABYLON.Color3(0.0, 0.0, 1.0),
  13775. new BABYLON.Color3(0.1, 0.2, 0.3),
  13776. new BABYLON.Color3(0.0, 0.2, 0.9)
  13777. ];
  13778. },
  13779. enumerable: true,
  13780. configurable: true
  13781. });
  13782. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13783. get: function () {
  13784. return this._fireColors;
  13785. },
  13786. set: function (value) {
  13787. this._fireColors = value;
  13788. this.updateShaderUniforms();
  13789. },
  13790. enumerable: true,
  13791. configurable: true
  13792. });
  13793. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13794. get: function () {
  13795. return this._time;
  13796. },
  13797. set: function (value) {
  13798. this._time = value;
  13799. this.updateShaderUniforms();
  13800. },
  13801. enumerable: true,
  13802. configurable: true
  13803. });
  13804. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13805. get: function () {
  13806. return this._speed;
  13807. },
  13808. set: function (value) {
  13809. this._speed = value;
  13810. this.updateShaderUniforms();
  13811. },
  13812. enumerable: true,
  13813. configurable: true
  13814. });
  13815. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13816. get: function () {
  13817. return this._alphaThreshold;
  13818. },
  13819. set: function (value) {
  13820. this._alphaThreshold = value;
  13821. this.updateShaderUniforms();
  13822. },
  13823. enumerable: true,
  13824. configurable: true
  13825. });
  13826. return FireProceduralTexture;
  13827. })(BABYLON.ProceduralTexture);
  13828. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13829. var CloudProceduralTexture = (function (_super) {
  13830. __extends(CloudProceduralTexture, _super);
  13831. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13832. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13833. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13834. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13835. this.updateShaderUniforms();
  13836. this.refreshRate = 0;
  13837. }
  13838. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13839. this.setColor3("skyColor", this._skyColor);
  13840. this.setColor3("cloudColor", this._cloudColor);
  13841. };
  13842. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13843. get: function () {
  13844. return this._skyColor;
  13845. },
  13846. set: function (value) {
  13847. this._skyColor = value;
  13848. this.updateShaderUniforms();
  13849. },
  13850. enumerable: true,
  13851. configurable: true
  13852. });
  13853. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13854. get: function () {
  13855. return this._cloudColor;
  13856. },
  13857. set: function (value) {
  13858. this._cloudColor = value;
  13859. this.updateShaderUniforms();
  13860. },
  13861. enumerable: true,
  13862. configurable: true
  13863. });
  13864. return CloudProceduralTexture;
  13865. })(BABYLON.ProceduralTexture);
  13866. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13867. var GrassProceduralTexture = (function (_super) {
  13868. __extends(GrassProceduralTexture, _super);
  13869. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13870. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13871. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13872. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13873. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13874. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13875. this._grassColors = [
  13876. new BABYLON.Color3(0.29, 0.38, 0.02),
  13877. new BABYLON.Color3(0.36, 0.49, 0.09),
  13878. new BABYLON.Color3(0.51, 0.6, 0.28)
  13879. ];
  13880. this.updateShaderUniforms();
  13881. this.refreshRate = 0;
  13882. }
  13883. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13884. this.setColor3("herb1Color", this._grassColors[0]);
  13885. this.setColor3("herb2Color", this._grassColors[1]);
  13886. this.setColor3("herb3Color", this._grassColors[2]);
  13887. this.setColor3("groundColor", this._groundColor);
  13888. };
  13889. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13890. get: function () {
  13891. return this._grassColors;
  13892. },
  13893. set: function (value) {
  13894. this._grassColors = value;
  13895. this.updateShaderUniforms();
  13896. },
  13897. enumerable: true,
  13898. configurable: true
  13899. });
  13900. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13901. get: function () {
  13902. return this._groundColor;
  13903. },
  13904. set: function (value) {
  13905. this.groundColor = value;
  13906. this.updateShaderUniforms();
  13907. },
  13908. enumerable: true,
  13909. configurable: true
  13910. });
  13911. return GrassProceduralTexture;
  13912. })(BABYLON.ProceduralTexture);
  13913. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13914. var RoadProceduralTexture = (function (_super) {
  13915. __extends(RoadProceduralTexture, _super);
  13916. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13917. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13918. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13919. this.updateShaderUniforms();
  13920. this.refreshRate = 0;
  13921. }
  13922. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13923. this.setColor3("roadColor", this._roadColor);
  13924. };
  13925. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13926. get: function () {
  13927. return this._roadColor;
  13928. },
  13929. set: function (value) {
  13930. this._roadColor = value;
  13931. this.updateShaderUniforms();
  13932. },
  13933. enumerable: true,
  13934. configurable: true
  13935. });
  13936. return RoadProceduralTexture;
  13937. })(BABYLON.ProceduralTexture);
  13938. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13939. var BrickProceduralTexture = (function (_super) {
  13940. __extends(BrickProceduralTexture, _super);
  13941. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13942. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13943. this._numberOfBricksHeight = 15;
  13944. this._numberOfBricksWidth = 5;
  13945. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13946. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13947. this.updateShaderUniforms();
  13948. this.refreshRate = 0;
  13949. }
  13950. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13951. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13952. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13953. this.setColor3("brickColor", this._brickColor);
  13954. this.setColor3("jointColor", this._jointColor);
  13955. };
  13956. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13957. get: function () {
  13958. return this._numberOfBricksHeight;
  13959. },
  13960. set: function (value) {
  13961. this._numberOfBricksHeight = value;
  13962. this.updateShaderUniforms();
  13963. },
  13964. enumerable: true,
  13965. configurable: true
  13966. });
  13967. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13968. get: function () {
  13969. return this._numberOfBricksWidth;
  13970. },
  13971. set: function (value) {
  13972. this._numberOfBricksHeight = value;
  13973. this.updateShaderUniforms();
  13974. },
  13975. enumerable: true,
  13976. configurable: true
  13977. });
  13978. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13979. get: function () {
  13980. return this._jointColor;
  13981. },
  13982. set: function (value) {
  13983. this._jointColor = value;
  13984. this.updateShaderUniforms();
  13985. },
  13986. enumerable: true,
  13987. configurable: true
  13988. });
  13989. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13990. get: function () {
  13991. return this._brickColor;
  13992. },
  13993. set: function (value) {
  13994. this._brickColor = value;
  13995. this.updateShaderUniforms();
  13996. },
  13997. enumerable: true,
  13998. configurable: true
  13999. });
  14000. return BrickProceduralTexture;
  14001. })(BABYLON.ProceduralTexture);
  14002. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  14003. var MarbleProceduralTexture = (function (_super) {
  14004. __extends(MarbleProceduralTexture, _super);
  14005. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  14006. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  14007. this._numberOfTilesHeight = 3;
  14008. this._numberOfTilesWidth = 3;
  14009. this._amplitude = 9.0;
  14010. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  14011. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  14012. this.updateShaderUniforms();
  14013. this.refreshRate = 0;
  14014. }
  14015. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  14016. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  14017. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  14018. this.setFloat("amplitude", this._amplitude);
  14019. this.setColor3("marbleColor", this._marbleColor);
  14020. this.setColor3("jointColor", this._jointColor);
  14021. };
  14022. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  14023. get: function () {
  14024. return this._numberOfTilesHeight;
  14025. },
  14026. set: function (value) {
  14027. this._numberOfTilesHeight = value;
  14028. this.updateShaderUniforms();
  14029. },
  14030. enumerable: true,
  14031. configurable: true
  14032. });
  14033. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  14034. get: function () {
  14035. return this._numberOfTilesWidth;
  14036. },
  14037. set: function (value) {
  14038. this._numberOfTilesWidth = value;
  14039. this.updateShaderUniforms();
  14040. },
  14041. enumerable: true,
  14042. configurable: true
  14043. });
  14044. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  14045. get: function () {
  14046. return this._jointColor;
  14047. },
  14048. set: function (value) {
  14049. this._jointColor = value;
  14050. this.updateShaderUniforms();
  14051. },
  14052. enumerable: true,
  14053. configurable: true
  14054. });
  14055. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  14056. get: function () {
  14057. return this._marbleColor;
  14058. },
  14059. set: function (value) {
  14060. this._marbleColor = value;
  14061. this.updateShaderUniforms();
  14062. },
  14063. enumerable: true,
  14064. configurable: true
  14065. });
  14066. return MarbleProceduralTexture;
  14067. })(BABYLON.ProceduralTexture);
  14068. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  14069. })(BABYLON || (BABYLON = {}));
  14070. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  14071. var BABYLON;
  14072. (function (BABYLON) {
  14073. var CustomProceduralTexture = (function (_super) {
  14074. __extends(CustomProceduralTexture, _super);
  14075. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  14076. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  14077. this._animate = true;
  14078. this._time = 0;
  14079. this._texturePath = texturePath;
  14080. //Try to load json
  14081. this.loadJson(texturePath);
  14082. this.refreshRate = 1;
  14083. }
  14084. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  14085. var _this = this;
  14086. var that = this;
  14087. function noConfigFile() {
  14088. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  14089. try {
  14090. that.setFragment(that._texturePath);
  14091. }
  14092. catch (ex) {
  14093. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  14094. }
  14095. }
  14096. var configFileUrl = jsonUrl + "/config.json";
  14097. var xhr = new XMLHttpRequest();
  14098. xhr.open("GET", configFileUrl, true);
  14099. xhr.addEventListener("load", function () {
  14100. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14101. try {
  14102. _this._config = JSON.parse(xhr.response);
  14103. _this.updateShaderUniforms();
  14104. _this.updateTextures();
  14105. _this.setFragment(_this._texturePath + "/custom");
  14106. _this._animate = _this._config.animate;
  14107. _this.refreshRate = _this._config.refreshrate;
  14108. }
  14109. catch (ex) {
  14110. noConfigFile();
  14111. }
  14112. }
  14113. else {
  14114. noConfigFile();
  14115. }
  14116. }, false);
  14117. xhr.addEventListener("error", function () {
  14118. noConfigFile();
  14119. }, false);
  14120. try {
  14121. xhr.send();
  14122. }
  14123. catch (ex) {
  14124. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  14125. }
  14126. };
  14127. CustomProceduralTexture.prototype.isReady = function () {
  14128. if (!_super.prototype.isReady.call(this)) {
  14129. return false;
  14130. }
  14131. for (var name in this._textures) {
  14132. var texture = this._textures[name];
  14133. if (!texture.isReady()) {
  14134. return false;
  14135. }
  14136. }
  14137. return true;
  14138. };
  14139. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  14140. if (this._animate) {
  14141. this._time += this.getScene().getAnimationRatio() * 0.03;
  14142. this.updateShaderUniforms();
  14143. }
  14144. _super.prototype.render.call(this, useCameraPostProcess);
  14145. };
  14146. CustomProceduralTexture.prototype.updateTextures = function () {
  14147. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  14148. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  14149. }
  14150. };
  14151. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  14152. if (this._config) {
  14153. for (var j = 0; j < this._config.uniforms.length; j++) {
  14154. var uniform = this._config.uniforms[j];
  14155. switch (uniform.type) {
  14156. case "float":
  14157. this.setFloat(uniform.name, uniform.value);
  14158. break;
  14159. case "color3":
  14160. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  14161. break;
  14162. case "color4":
  14163. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  14164. break;
  14165. case "vector2":
  14166. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  14167. break;
  14168. case "vector3":
  14169. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  14170. break;
  14171. }
  14172. }
  14173. }
  14174. this.setFloat("time", this._time);
  14175. };
  14176. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  14177. get: function () {
  14178. return this._animate;
  14179. },
  14180. set: function (value) {
  14181. this._animate = value;
  14182. },
  14183. enumerable: true,
  14184. configurable: true
  14185. });
  14186. return CustomProceduralTexture;
  14187. })(BABYLON.ProceduralTexture);
  14188. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  14189. })(BABYLON || (BABYLON = {}));
  14190. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  14191. var BABYLON;
  14192. (function (BABYLON) {
  14193. var MirrorTexture = (function (_super) {
  14194. __extends(MirrorTexture, _super);
  14195. function MirrorTexture(name, size, scene, generateMipMaps) {
  14196. var _this = this;
  14197. _super.call(this, name, size, scene, generateMipMaps, true);
  14198. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  14199. this._transformMatrix = BABYLON.Matrix.Zero();
  14200. this._mirrorMatrix = BABYLON.Matrix.Zero();
  14201. this.onBeforeRender = function () {
  14202. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  14203. _this._savedViewMatrix = scene.getViewMatrix();
  14204. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  14205. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  14206. scene.clipPlane = _this.mirrorPlane;
  14207. scene.getEngine().cullBackFaces = false;
  14208. };
  14209. this.onAfterRender = function () {
  14210. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  14211. scene.getEngine().cullBackFaces = true;
  14212. delete scene.clipPlane;
  14213. };
  14214. }
  14215. MirrorTexture.prototype.clone = function () {
  14216. var textureSize = this.getSize();
  14217. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14218. // Base texture
  14219. newTexture.hasAlpha = this.hasAlpha;
  14220. newTexture.level = this.level;
  14221. // Mirror Texture
  14222. newTexture.mirrorPlane = this.mirrorPlane.clone();
  14223. newTexture.renderList = this.renderList.slice(0);
  14224. return newTexture;
  14225. };
  14226. return MirrorTexture;
  14227. })(BABYLON.RenderTargetTexture);
  14228. BABYLON.MirrorTexture = MirrorTexture;
  14229. })(BABYLON || (BABYLON = {}));
  14230. //# sourceMappingURL=babylon.mirrorTexture.js.map
  14231. var BABYLON;
  14232. (function (BABYLON) {
  14233. var DynamicTexture = (function (_super) {
  14234. __extends(DynamicTexture, _super);
  14235. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  14236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14237. _super.call(this, null, scene, !generateMipMaps);
  14238. this.name = name;
  14239. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14240. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14241. this._generateMipMaps = generateMipMaps;
  14242. if (options.getContext) {
  14243. this._canvas = options;
  14244. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14245. }
  14246. else {
  14247. this._canvas = document.createElement("canvas");
  14248. if (options.width) {
  14249. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14250. }
  14251. else {
  14252. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14253. }
  14254. }
  14255. var textureSize = this.getSize();
  14256. this._canvas.width = textureSize.width;
  14257. this._canvas.height = textureSize.height;
  14258. this._context = this._canvas.getContext("2d");
  14259. }
  14260. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14261. get: function () {
  14262. return true;
  14263. },
  14264. enumerable: true,
  14265. configurable: true
  14266. });
  14267. DynamicTexture.prototype.scale = function (ratio) {
  14268. var textureSize = this.getSize();
  14269. textureSize.width *= ratio;
  14270. textureSize.height *= ratio;
  14271. this._canvas.width = textureSize.width;
  14272. this._canvas.height = textureSize.height;
  14273. this.releaseInternalTexture();
  14274. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14275. };
  14276. DynamicTexture.prototype.getContext = function () {
  14277. return this._context;
  14278. };
  14279. DynamicTexture.prototype.clear = function () {
  14280. var size = this.getSize();
  14281. this._context.fillRect(0, 0, size.width, size.height);
  14282. };
  14283. DynamicTexture.prototype.update = function (invertY) {
  14284. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14285. };
  14286. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14287. if (update === void 0) { update = true; }
  14288. var size = this.getSize();
  14289. if (clearColor) {
  14290. this._context.fillStyle = clearColor;
  14291. this._context.fillRect(0, 0, size.width, size.height);
  14292. }
  14293. this._context.font = font;
  14294. if (x === null) {
  14295. var textSize = this._context.measureText(text);
  14296. x = (size.width - textSize.width) / 2;
  14297. }
  14298. this._context.fillStyle = color;
  14299. this._context.fillText(text, x, y);
  14300. if (update) {
  14301. this.update(invertY);
  14302. }
  14303. };
  14304. DynamicTexture.prototype.clone = function () {
  14305. var textureSize = this.getSize();
  14306. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14307. // Base texture
  14308. newTexture.hasAlpha = this.hasAlpha;
  14309. newTexture.level = this.level;
  14310. // Dynamic Texture
  14311. newTexture.wrapU = this.wrapU;
  14312. newTexture.wrapV = this.wrapV;
  14313. return newTexture;
  14314. };
  14315. return DynamicTexture;
  14316. })(BABYLON.Texture);
  14317. BABYLON.DynamicTexture = DynamicTexture;
  14318. })(BABYLON || (BABYLON = {}));
  14319. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14320. var BABYLON;
  14321. (function (BABYLON) {
  14322. var VideoTexture = (function (_super) {
  14323. __extends(VideoTexture, _super);
  14324. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14325. var _this = this;
  14326. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14327. _super.call(this, null, scene, !generateMipMaps, invertY);
  14328. this._autoLaunch = true;
  14329. this.name = name;
  14330. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14331. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14332. var requiredWidth = size.width || size;
  14333. var requiredHeight = size.height || size;
  14334. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14335. var textureSize = this.getSize();
  14336. this.video = document.createElement("video");
  14337. this.video.width = textureSize.width;
  14338. this.video.height = textureSize.height;
  14339. this.video.autoplay = false;
  14340. this.video.loop = true;
  14341. this.video.addEventListener("canplaythrough", function () {
  14342. if (_this._texture) {
  14343. _this._texture.isReady = true;
  14344. }
  14345. });
  14346. urls.forEach(function (url) {
  14347. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14348. var source = document.createElement("source");
  14349. source.src = url;
  14350. _this.video.appendChild(source);
  14351. });
  14352. this._lastUpdate = BABYLON.Tools.Now;
  14353. }
  14354. VideoTexture.prototype.update = function () {
  14355. if (this._autoLaunch) {
  14356. this._autoLaunch = false;
  14357. this.video.play();
  14358. }
  14359. var now = BABYLON.Tools.Now;
  14360. if (now - this._lastUpdate < 15) {
  14361. return false;
  14362. }
  14363. this._lastUpdate = now;
  14364. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14365. return true;
  14366. };
  14367. return VideoTexture;
  14368. })(BABYLON.Texture);
  14369. BABYLON.VideoTexture = VideoTexture;
  14370. })(BABYLON || (BABYLON = {}));
  14371. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14372. (function (BABYLON) {
  14373. var EffectFallbacks = (function () {
  14374. function EffectFallbacks() {
  14375. this._defines = {};
  14376. this._currentRank = 32;
  14377. this._maxRank = -1;
  14378. }
  14379. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14380. if (!this._defines[rank]) {
  14381. if (rank < this._currentRank) {
  14382. this._currentRank = rank;
  14383. }
  14384. if (rank > this._maxRank) {
  14385. this._maxRank = rank;
  14386. }
  14387. this._defines[rank] = new Array();
  14388. }
  14389. this._defines[rank].push(define);
  14390. };
  14391. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14392. get: function () {
  14393. return this._currentRank <= this._maxRank;
  14394. },
  14395. enumerable: true,
  14396. configurable: true
  14397. });
  14398. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14399. var currentFallbacks = this._defines[this._currentRank];
  14400. for (var index = 0; index < currentFallbacks.length; index++) {
  14401. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14402. }
  14403. this._currentRank++;
  14404. return currentDefines;
  14405. };
  14406. return EffectFallbacks;
  14407. })();
  14408. BABYLON.EffectFallbacks = EffectFallbacks;
  14409. var Effect = (function () {
  14410. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14411. var _this = this;
  14412. this._isReady = false;
  14413. this._compilationError = "";
  14414. this._valueCache = [];
  14415. this._engine = engine;
  14416. this.name = baseName;
  14417. this.defines = defines;
  14418. this._uniformsNames = uniformsNames.concat(samplers);
  14419. this._samplers = samplers;
  14420. this._attributesNames = attributesNames;
  14421. this.onError = onError;
  14422. this.onCompiled = onCompiled;
  14423. var vertexSource;
  14424. var fragmentSource;
  14425. if (baseName.vertexElement) {
  14426. vertexSource = document.getElementById(baseName.vertexElement);
  14427. if (!vertexSource) {
  14428. vertexSource = baseName.vertexElement;
  14429. }
  14430. }
  14431. else {
  14432. vertexSource = baseName.vertex || baseName;
  14433. }
  14434. if (baseName.fragmentElement) {
  14435. fragmentSource = document.getElementById(baseName.fragmentElement);
  14436. if (!fragmentSource) {
  14437. fragmentSource = baseName.fragmentElement;
  14438. }
  14439. }
  14440. else {
  14441. fragmentSource = baseName.fragment || baseName;
  14442. }
  14443. this._loadVertexShader(vertexSource, function (vertexCode) {
  14444. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14445. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14446. });
  14447. });
  14448. }
  14449. // Properties
  14450. Effect.prototype.isReady = function () {
  14451. return this._isReady;
  14452. };
  14453. Effect.prototype.getProgram = function () {
  14454. return this._program;
  14455. };
  14456. Effect.prototype.getAttributesNames = function () {
  14457. return this._attributesNames;
  14458. };
  14459. Effect.prototype.getAttributeLocation = function (index) {
  14460. return this._attributes[index];
  14461. };
  14462. Effect.prototype.getAttributeLocationByName = function (name) {
  14463. var index = this._attributesNames.indexOf(name);
  14464. return this._attributes[index];
  14465. };
  14466. Effect.prototype.getAttributesCount = function () {
  14467. return this._attributes.length;
  14468. };
  14469. Effect.prototype.getUniformIndex = function (uniformName) {
  14470. return this._uniformsNames.indexOf(uniformName);
  14471. };
  14472. Effect.prototype.getUniform = function (uniformName) {
  14473. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14474. };
  14475. Effect.prototype.getSamplers = function () {
  14476. return this._samplers;
  14477. };
  14478. Effect.prototype.getCompilationError = function () {
  14479. return this._compilationError;
  14480. };
  14481. // Methods
  14482. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14483. // DOM element ?
  14484. if (vertex instanceof HTMLElement) {
  14485. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14486. callback(vertexCode);
  14487. return;
  14488. }
  14489. // Is in local store ?
  14490. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14491. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14492. return;
  14493. }
  14494. var vertexShaderUrl;
  14495. if (vertex[0] === ".") {
  14496. vertexShaderUrl = vertex;
  14497. }
  14498. else {
  14499. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14500. }
  14501. // Vertex shader
  14502. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14503. };
  14504. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14505. // DOM element ?
  14506. if (fragment instanceof HTMLElement) {
  14507. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14508. callback(fragmentCode);
  14509. return;
  14510. }
  14511. // Is in local store ?
  14512. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14513. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14514. return;
  14515. }
  14516. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14517. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14518. return;
  14519. }
  14520. var fragmentShaderUrl;
  14521. if (fragment[0] === ".") {
  14522. fragmentShaderUrl = fragment;
  14523. }
  14524. else {
  14525. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14526. }
  14527. // Fragment shader
  14528. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14529. };
  14530. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14531. try {
  14532. var engine = this._engine;
  14533. if (!engine.getCaps().highPrecisionShaderSupported) {
  14534. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14535. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14536. }
  14537. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14538. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14539. this._attributes = engine.getAttributes(this._program, attributesNames);
  14540. for (var index = 0; index < this._samplers.length; index++) {
  14541. var sampler = this.getUniform(this._samplers[index]);
  14542. if (sampler == null) {
  14543. this._samplers.splice(index, 1);
  14544. index--;
  14545. }
  14546. }
  14547. engine.bindSamplers(this);
  14548. this._isReady = true;
  14549. if (this.onCompiled) {
  14550. this.onCompiled(this);
  14551. }
  14552. }
  14553. catch (e) {
  14554. // Is it a problem with precision?
  14555. if (e.message.indexOf("highp") !== -1) {
  14556. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14557. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14558. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14559. return;
  14560. }
  14561. // Let's go through fallbacks then
  14562. if (fallbacks && fallbacks.isMoreFallbacks) {
  14563. defines = fallbacks.reduce(defines);
  14564. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14565. }
  14566. else {
  14567. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14568. BABYLON.Tools.Error("Defines: " + defines);
  14569. BABYLON.Tools.Error("Error: " + e.message);
  14570. this._compilationError = e.message;
  14571. if (this.onError) {
  14572. this.onError(this, this._compilationError);
  14573. }
  14574. }
  14575. }
  14576. };
  14577. Effect.prototype._bindTexture = function (channel, texture) {
  14578. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14579. };
  14580. Effect.prototype.setTexture = function (channel, texture) {
  14581. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14582. };
  14583. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14584. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14585. };
  14586. //public _cacheMatrix(uniformName, matrix) {
  14587. // if (!this._valueCache[uniformName]) {
  14588. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14589. // }
  14590. // for (var index = 0; index < 16; index++) {
  14591. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14592. // }
  14593. //};
  14594. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14595. if (!this._valueCache[uniformName]) {
  14596. this._valueCache[uniformName] = [x, y];
  14597. return;
  14598. }
  14599. this._valueCache[uniformName][0] = x;
  14600. this._valueCache[uniformName][1] = y;
  14601. };
  14602. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14603. if (!this._valueCache[uniformName]) {
  14604. this._valueCache[uniformName] = [x, y, z];
  14605. return;
  14606. }
  14607. this._valueCache[uniformName][0] = x;
  14608. this._valueCache[uniformName][1] = y;
  14609. this._valueCache[uniformName][2] = z;
  14610. };
  14611. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14612. if (!this._valueCache[uniformName]) {
  14613. this._valueCache[uniformName] = [x, y, z, w];
  14614. return;
  14615. }
  14616. this._valueCache[uniformName][0] = x;
  14617. this._valueCache[uniformName][1] = y;
  14618. this._valueCache[uniformName][2] = z;
  14619. this._valueCache[uniformName][3] = w;
  14620. };
  14621. Effect.prototype.setArray = function (uniformName, array) {
  14622. this._engine.setArray(this.getUniform(uniformName), array);
  14623. return this;
  14624. };
  14625. Effect.prototype.setArray2 = function (uniformName, array) {
  14626. this._engine.setArray2(this.getUniform(uniformName), array);
  14627. return this;
  14628. };
  14629. Effect.prototype.setArray3 = function (uniformName, array) {
  14630. this._engine.setArray3(this.getUniform(uniformName), array);
  14631. return this;
  14632. };
  14633. Effect.prototype.setArray4 = function (uniformName, array) {
  14634. this._engine.setArray4(this.getUniform(uniformName), array);
  14635. return this;
  14636. };
  14637. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14638. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14639. return this;
  14640. };
  14641. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14642. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14643. // return;
  14644. //this._cacheMatrix(uniformName, matrix);
  14645. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14646. return this;
  14647. };
  14648. Effect.prototype.setFloat = function (uniformName, value) {
  14649. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14650. return this;
  14651. this._valueCache[uniformName] = value;
  14652. this._engine.setFloat(this.getUniform(uniformName), value);
  14653. return this;
  14654. };
  14655. Effect.prototype.setBool = function (uniformName, bool) {
  14656. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14657. return this;
  14658. this._valueCache[uniformName] = bool;
  14659. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14660. return this;
  14661. };
  14662. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14663. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14664. return this;
  14665. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14666. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14667. return this;
  14668. };
  14669. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14670. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14671. return this;
  14672. this._cacheFloat2(uniformName, x, y);
  14673. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14674. return this;
  14675. };
  14676. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14677. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14678. return this;
  14679. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14680. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14681. return this;
  14682. };
  14683. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14684. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14685. return this;
  14686. this._cacheFloat3(uniformName, x, y, z);
  14687. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14688. return this;
  14689. };
  14690. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14691. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14692. return this;
  14693. this._cacheFloat4(uniformName, x, y, z, w);
  14694. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14695. return this;
  14696. };
  14697. Effect.prototype.setColor3 = function (uniformName, color3) {
  14698. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14699. return this;
  14700. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14701. this._engine.setColor3(this.getUniform(uniformName), color3);
  14702. return this;
  14703. };
  14704. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14705. 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)
  14706. return this;
  14707. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14708. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14709. return this;
  14710. };
  14711. // Statics
  14712. 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}",
  14713. 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}",
  14714. 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}",
  14715. 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}",
  14716. 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}",
  14717. 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}",
  14718. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14719. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14720. 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}",
  14721. 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}",
  14722. 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}",
  14723. 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}",
  14724. 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}",
  14725. 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}",
  14726. 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}",
  14727. 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}",
  14728. 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}",
  14729. 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}",
  14730. 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}",
  14731. 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}",
  14732. 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}",
  14733. 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}",
  14734. 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}",
  14735. 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}",
  14736. 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}",
  14737. 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}",
  14738. 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}",
  14739. 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}",
  14740. 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}",
  14741. 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}",
  14742. 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}",
  14743. 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}",
  14744. 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}",
  14745. 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}",
  14746. 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}",
  14747. 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}",
  14748. 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}",
  14749. 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}",
  14750. 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}",
  14751. 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}",
  14752. 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}",
  14753. 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}",
  14754. 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}",
  14755. 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}",
  14756. 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}",
  14757. 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}",
  14758. 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}",
  14759. 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}",
  14760. };
  14761. return Effect;
  14762. })();
  14763. BABYLON.Effect = Effect;
  14764. })(BABYLON || (BABYLON = {}));
  14765. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14766. (function (BABYLON) {
  14767. var Material = (function () {
  14768. function Material(name, scene, doNotAdd) {
  14769. this.name = name;
  14770. this.checkReadyOnEveryCall = true;
  14771. this.checkReadyOnlyOnce = false;
  14772. this.state = "";
  14773. this.alpha = 1.0;
  14774. this.backFaceCulling = true;
  14775. this._wasPreviouslyReady = false;
  14776. this._fillMode = Material.TriangleFillMode;
  14777. this.pointSize = 1.0;
  14778. this.zOffset = 0;
  14779. this.id = name;
  14780. this._scene = scene;
  14781. if (!doNotAdd) {
  14782. scene.materials.push(this);
  14783. }
  14784. }
  14785. Object.defineProperty(Material, "TriangleFillMode", {
  14786. get: function () {
  14787. return Material._TriangleFillMode;
  14788. },
  14789. enumerable: true,
  14790. configurable: true
  14791. });
  14792. Object.defineProperty(Material, "WireFrameFillMode", {
  14793. get: function () {
  14794. return Material._WireFrameFillMode;
  14795. },
  14796. enumerable: true,
  14797. configurable: true
  14798. });
  14799. Object.defineProperty(Material, "PointFillMode", {
  14800. get: function () {
  14801. return Material._PointFillMode;
  14802. },
  14803. enumerable: true,
  14804. configurable: true
  14805. });
  14806. Object.defineProperty(Material.prototype, "wireframe", {
  14807. get: function () {
  14808. return this._fillMode === Material.WireFrameFillMode;
  14809. },
  14810. set: function (value) {
  14811. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14812. },
  14813. enumerable: true,
  14814. configurable: true
  14815. });
  14816. Object.defineProperty(Material.prototype, "pointsCloud", {
  14817. get: function () {
  14818. return this._fillMode === Material.PointFillMode;
  14819. },
  14820. set: function (value) {
  14821. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14822. },
  14823. enumerable: true,
  14824. configurable: true
  14825. });
  14826. Object.defineProperty(Material.prototype, "fillMode", {
  14827. get: function () {
  14828. return this._fillMode;
  14829. },
  14830. set: function (value) {
  14831. this._fillMode = value;
  14832. },
  14833. enumerable: true,
  14834. configurable: true
  14835. });
  14836. Material.prototype.isReady = function (mesh, useInstances) {
  14837. return true;
  14838. };
  14839. Material.prototype.getEffect = function () {
  14840. return this._effect;
  14841. };
  14842. Material.prototype.getScene = function () {
  14843. return this._scene;
  14844. };
  14845. Material.prototype.needAlphaBlending = function () {
  14846. return (this.alpha < 1.0);
  14847. };
  14848. Material.prototype.needAlphaTesting = function () {
  14849. return false;
  14850. };
  14851. Material.prototype.getAlphaTestTexture = function () {
  14852. return null;
  14853. };
  14854. Material.prototype.trackCreation = function (onCompiled, onError) {
  14855. };
  14856. Material.prototype._preBind = function () {
  14857. var engine = this._scene.getEngine();
  14858. engine.enableEffect(this._effect);
  14859. engine.setState(this.backFaceCulling, this.zOffset);
  14860. };
  14861. Material.prototype.bind = function (world, mesh) {
  14862. this._scene._cachedMaterial = this;
  14863. if (this.onBind) {
  14864. this.onBind(this, mesh);
  14865. }
  14866. };
  14867. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14868. };
  14869. Material.prototype.unbind = function () {
  14870. };
  14871. Material.prototype.dispose = function (forceDisposeEffect) {
  14872. // Remove from scene
  14873. var index = this._scene.materials.indexOf(this);
  14874. this._scene.materials.splice(index, 1);
  14875. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14876. if (forceDisposeEffect && this._effect) {
  14877. this._scene.getEngine()._releaseEffect(this._effect);
  14878. this._effect = null;
  14879. }
  14880. // Callback
  14881. if (this.onDispose) {
  14882. this.onDispose();
  14883. }
  14884. };
  14885. Material._TriangleFillMode = 0;
  14886. Material._WireFrameFillMode = 1;
  14887. Material._PointFillMode = 2;
  14888. return Material;
  14889. })();
  14890. BABYLON.Material = Material;
  14891. })(BABYLON || (BABYLON = {}));
  14892. //# sourceMappingURL=babylon.material.js.map
  14893. var BABYLON;
  14894. (function (BABYLON) {
  14895. var maxSimultaneousLights = 4;
  14896. var FresnelParameters = (function () {
  14897. function FresnelParameters() {
  14898. this.isEnabled = true;
  14899. this.leftColor = BABYLON.Color3.White();
  14900. this.rightColor = BABYLON.Color3.Black();
  14901. this.bias = 0;
  14902. this.power = 1;
  14903. }
  14904. return FresnelParameters;
  14905. })();
  14906. BABYLON.FresnelParameters = FresnelParameters;
  14907. var StandardMaterial = (function (_super) {
  14908. __extends(StandardMaterial, _super);
  14909. function StandardMaterial(name, scene) {
  14910. var _this = this;
  14911. _super.call(this, name, scene);
  14912. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14913. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14914. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14915. this.specularPower = 64;
  14916. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14917. this.useAlphaFromDiffuseTexture = false;
  14918. this.useSpecularOverAlpha = true;
  14919. this.fogEnabled = true;
  14920. this._cachedDefines = null;
  14921. this._renderTargets = new BABYLON.SmartArray(16);
  14922. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14923. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14924. this._scaledDiffuse = new BABYLON.Color3();
  14925. this._scaledSpecular = new BABYLON.Color3();
  14926. this.getRenderTargetTextures = function () {
  14927. _this._renderTargets.reset();
  14928. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14929. _this._renderTargets.push(_this.reflectionTexture);
  14930. }
  14931. return _this._renderTargets;
  14932. };
  14933. }
  14934. StandardMaterial.prototype.needAlphaBlending = function () {
  14935. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14936. };
  14937. StandardMaterial.prototype.needAlphaTesting = function () {
  14938. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  14939. };
  14940. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14941. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14942. };
  14943. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14944. return this.diffuseTexture;
  14945. };
  14946. // Methods
  14947. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14948. if (this.checkReadyOnlyOnce) {
  14949. if (this._wasPreviouslyReady) {
  14950. }
  14951. }
  14952. var scene = this.getScene();
  14953. if (!this.checkReadyOnEveryCall) {
  14954. if (this._renderId === scene.getRenderId()) {
  14955. }
  14956. }
  14957. var engine = scene.getEngine();
  14958. var defines = [];
  14959. var fallbacks = new BABYLON.EffectFallbacks();
  14960. var needNormals = false;
  14961. var needUVs = false;
  14962. // Textures
  14963. if (scene.texturesEnabled) {
  14964. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14965. if (!this.diffuseTexture.isReady()) {
  14966. return false;
  14967. }
  14968. else {
  14969. needUVs = true;
  14970. defines.push("#define DIFFUSE");
  14971. }
  14972. }
  14973. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14974. if (!this.ambientTexture.isReady()) {
  14975. return false;
  14976. }
  14977. else {
  14978. needUVs = true;
  14979. defines.push("#define AMBIENT");
  14980. }
  14981. }
  14982. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14983. if (!this.opacityTexture.isReady()) {
  14984. return false;
  14985. }
  14986. else {
  14987. needUVs = true;
  14988. defines.push("#define OPACITY");
  14989. if (this.opacityTexture.getAlphaFromRGB) {
  14990. defines.push("#define OPACITYRGB");
  14991. }
  14992. }
  14993. }
  14994. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14995. if (!this.reflectionTexture.isReady()) {
  14996. return false;
  14997. }
  14998. else {
  14999. needNormals = true;
  15000. needUVs = true;
  15001. defines.push("#define REFLECTION");
  15002. fallbacks.addFallback(0, "REFLECTION");
  15003. }
  15004. }
  15005. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15006. if (!this.emissiveTexture.isReady()) {
  15007. return false;
  15008. }
  15009. else {
  15010. needUVs = true;
  15011. defines.push("#define EMISSIVE");
  15012. }
  15013. }
  15014. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15015. if (!this.specularTexture.isReady()) {
  15016. return false;
  15017. }
  15018. else {
  15019. needUVs = true;
  15020. defines.push("#define SPECULAR");
  15021. fallbacks.addFallback(0, "SPECULAR");
  15022. }
  15023. }
  15024. }
  15025. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  15026. if (!this.bumpTexture.isReady()) {
  15027. return false;
  15028. }
  15029. else {
  15030. needUVs = true;
  15031. defines.push("#define BUMP");
  15032. fallbacks.addFallback(0, "BUMP");
  15033. }
  15034. }
  15035. // Effect
  15036. if (this.useSpecularOverAlpha) {
  15037. defines.push("#define SPECULAROVERALPHA");
  15038. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  15039. }
  15040. if (scene.clipPlane) {
  15041. defines.push("#define CLIPPLANE");
  15042. }
  15043. if (engine.getAlphaTesting()) {
  15044. defines.push("#define ALPHATEST");
  15045. }
  15046. if (this._shouldUseAlphaFromDiffuseTexture()) {
  15047. defines.push("#define ALPHAFROMDIFFUSE");
  15048. }
  15049. // Point size
  15050. if (this.pointsCloud || scene.forcePointsCloud) {
  15051. defines.push("#define POINTSIZE");
  15052. }
  15053. // Fog
  15054. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15055. defines.push("#define FOG");
  15056. fallbacks.addFallback(1, "FOG");
  15057. }
  15058. var shadowsActivated = false;
  15059. var lightIndex = 0;
  15060. if (scene.lightsEnabled) {
  15061. for (var index = 0; index < scene.lights.length; index++) {
  15062. var light = scene.lights[index];
  15063. if (!light.isEnabled()) {
  15064. continue;
  15065. }
  15066. // Excluded check
  15067. if (light._excludedMeshesIds.length > 0) {
  15068. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  15069. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  15070. if (excludedMesh) {
  15071. light.excludedMeshes.push(excludedMesh);
  15072. }
  15073. }
  15074. light._excludedMeshesIds = [];
  15075. }
  15076. // Included check
  15077. if (light._includedOnlyMeshesIds.length > 0) {
  15078. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  15079. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  15080. if (includedOnlyMesh) {
  15081. light.includedOnlyMeshes.push(includedOnlyMesh);
  15082. }
  15083. }
  15084. light._includedOnlyMeshesIds = [];
  15085. }
  15086. if (!light.canAffectMesh(mesh)) {
  15087. continue;
  15088. }
  15089. needNormals = true;
  15090. defines.push("#define LIGHT" + lightIndex);
  15091. if (lightIndex > 0) {
  15092. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  15093. }
  15094. var type;
  15095. if (light instanceof BABYLON.SpotLight) {
  15096. type = "#define SPOTLIGHT" + lightIndex;
  15097. }
  15098. else if (light instanceof BABYLON.HemisphericLight) {
  15099. type = "#define HEMILIGHT" + lightIndex;
  15100. }
  15101. else {
  15102. type = "#define POINTDIRLIGHT" + lightIndex;
  15103. }
  15104. defines.push(type);
  15105. if (lightIndex > 0) {
  15106. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  15107. }
  15108. // Shadows
  15109. if (scene.shadowsEnabled) {
  15110. var shadowGenerator = light.getShadowGenerator();
  15111. if (mesh && mesh.receiveShadows && shadowGenerator) {
  15112. defines.push("#define SHADOW" + lightIndex);
  15113. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  15114. if (!shadowsActivated) {
  15115. defines.push("#define SHADOWS");
  15116. shadowsActivated = true;
  15117. }
  15118. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  15119. defines.push("#define SHADOWVSM" + lightIndex);
  15120. if (lightIndex > 0) {
  15121. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  15122. }
  15123. }
  15124. if (shadowGenerator.usePoissonSampling) {
  15125. defines.push("#define SHADOWPCF" + lightIndex);
  15126. if (lightIndex > 0) {
  15127. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  15128. }
  15129. }
  15130. }
  15131. }
  15132. lightIndex++;
  15133. if (lightIndex === maxSimultaneousLights)
  15134. break;
  15135. }
  15136. }
  15137. if (StandardMaterial.FresnelEnabled) {
  15138. // Fresnel
  15139. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15140. var fresnelRank = 1;
  15141. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15142. defines.push("#define DIFFUSEFRESNEL");
  15143. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  15144. fresnelRank++;
  15145. }
  15146. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15147. defines.push("#define OPACITYFRESNEL");
  15148. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  15149. fresnelRank++;
  15150. }
  15151. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15152. defines.push("#define REFLECTIONFRESNEL");
  15153. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  15154. fresnelRank++;
  15155. }
  15156. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15157. defines.push("#define EMISSIVEFRESNEL");
  15158. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  15159. fresnelRank++;
  15160. }
  15161. needNormals = true;
  15162. defines.push("#define FRESNEL");
  15163. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  15164. }
  15165. }
  15166. // Attribs
  15167. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15168. if (mesh) {
  15169. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15170. attribs.push(BABYLON.VertexBuffer.NormalKind);
  15171. defines.push("#define NORMAL");
  15172. }
  15173. if (needUVs) {
  15174. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15175. attribs.push(BABYLON.VertexBuffer.UVKind);
  15176. defines.push("#define UV1");
  15177. }
  15178. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15179. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15180. defines.push("#define UV2");
  15181. }
  15182. }
  15183. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15184. attribs.push(BABYLON.VertexBuffer.ColorKind);
  15185. defines.push("#define VERTEXCOLOR");
  15186. if (mesh.hasVertexAlpha) {
  15187. defines.push("#define VERTEXALPHA");
  15188. }
  15189. }
  15190. if (mesh.useBones) {
  15191. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15192. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15193. defines.push("#define BONES");
  15194. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15195. defines.push("#define BONES4");
  15196. fallbacks.addFallback(0, "BONES4");
  15197. }
  15198. // Instances
  15199. if (useInstances) {
  15200. defines.push("#define INSTANCES");
  15201. attribs.push("world0");
  15202. attribs.push("world1");
  15203. attribs.push("world2");
  15204. attribs.push("world3");
  15205. }
  15206. }
  15207. // Get correct effect
  15208. var join = defines.join("\n");
  15209. if (this._cachedDefines !== join) {
  15210. this._cachedDefines = join;
  15211. scene.resetCachedMaterial();
  15212. // Legacy browser patch
  15213. var shaderName = "default";
  15214. if (!scene.getEngine().getCaps().standardDerivatives) {
  15215. shaderName = "legacydefault";
  15216. }
  15217. 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);
  15218. }
  15219. if (!this._effect.isReady()) {
  15220. return false;
  15221. }
  15222. this._renderId = scene.getRenderId();
  15223. this._wasPreviouslyReady = true;
  15224. return true;
  15225. };
  15226. StandardMaterial.prototype.unbind = function () {
  15227. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  15228. this._effect.setTexture("reflection2DSampler", null);
  15229. }
  15230. };
  15231. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  15232. this._effect.setMatrix("world", world);
  15233. };
  15234. StandardMaterial.prototype.bind = function (world, mesh) {
  15235. var scene = this.getScene();
  15236. // Matrices
  15237. this.bindOnlyWorldMatrix(world);
  15238. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  15239. // Bones
  15240. if (mesh && mesh.useBones) {
  15241. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15242. }
  15243. if (scene.getCachedMaterial() !== this) {
  15244. if (StandardMaterial.FresnelEnabled) {
  15245. // Fresnel
  15246. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15247. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15248. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15249. }
  15250. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15251. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15252. }
  15253. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15254. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15255. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15256. }
  15257. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15258. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15259. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15260. }
  15261. }
  15262. // Textures
  15263. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15264. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15265. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15266. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15267. }
  15268. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15269. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15270. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15271. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15272. }
  15273. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15274. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15275. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15276. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15277. }
  15278. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15279. if (this.reflectionTexture.isCube) {
  15280. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15281. }
  15282. else {
  15283. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15284. }
  15285. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15286. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15287. }
  15288. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15289. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15290. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15291. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15292. }
  15293. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15294. this._effect.setTexture("specularSampler", this.specularTexture);
  15295. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15296. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15297. }
  15298. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15299. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15300. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15301. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15302. }
  15303. // Clip plane
  15304. if (scene.clipPlane) {
  15305. var clipPlane = scene.clipPlane;
  15306. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15307. }
  15308. // Point size
  15309. if (this.pointsCloud) {
  15310. this._effect.setFloat("pointSize", this.pointSize);
  15311. }
  15312. // Colors
  15313. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15314. // Scaling down color according to emissive
  15315. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15316. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15317. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15318. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15319. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15320. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15321. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15322. }
  15323. // Scaling down color according to emissive
  15324. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15325. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15326. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15327. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15328. if (scene.lightsEnabled) {
  15329. var lightIndex = 0;
  15330. for (var index = 0; index < scene.lights.length; index++) {
  15331. var light = scene.lights[index];
  15332. if (!light.isEnabled()) {
  15333. continue;
  15334. }
  15335. if (!light.canAffectMesh(mesh)) {
  15336. continue;
  15337. }
  15338. if (light instanceof BABYLON.PointLight) {
  15339. // Point Light
  15340. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15341. }
  15342. else if (light instanceof BABYLON.DirectionalLight) {
  15343. // Directional Light
  15344. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15345. }
  15346. else if (light instanceof BABYLON.SpotLight) {
  15347. // Spot Light
  15348. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15349. }
  15350. else if (light instanceof BABYLON.HemisphericLight) {
  15351. // Hemispheric Light
  15352. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15353. }
  15354. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15355. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15356. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15357. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15358. // Shadows
  15359. if (scene.shadowsEnabled) {
  15360. var shadowGenerator = light.getShadowGenerator();
  15361. if (mesh.receiveShadows && shadowGenerator) {
  15362. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15363. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15364. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15365. }
  15366. }
  15367. lightIndex++;
  15368. if (lightIndex === maxSimultaneousLights)
  15369. break;
  15370. }
  15371. }
  15372. // View
  15373. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15374. this._effect.setMatrix("view", scene.getViewMatrix());
  15375. }
  15376. // Fog
  15377. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15378. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15379. this._effect.setColor3("vFogColor", scene.fogColor);
  15380. }
  15381. _super.prototype.bind.call(this, world, mesh);
  15382. };
  15383. StandardMaterial.prototype.getAnimatables = function () {
  15384. var results = [];
  15385. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15386. results.push(this.diffuseTexture);
  15387. }
  15388. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15389. results.push(this.ambientTexture);
  15390. }
  15391. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15392. results.push(this.opacityTexture);
  15393. }
  15394. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15395. results.push(this.reflectionTexture);
  15396. }
  15397. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15398. results.push(this.emissiveTexture);
  15399. }
  15400. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15401. results.push(this.specularTexture);
  15402. }
  15403. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15404. results.push(this.bumpTexture);
  15405. }
  15406. return results;
  15407. };
  15408. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15409. if (this.diffuseTexture) {
  15410. this.diffuseTexture.dispose();
  15411. }
  15412. if (this.ambientTexture) {
  15413. this.ambientTexture.dispose();
  15414. }
  15415. if (this.opacityTexture) {
  15416. this.opacityTexture.dispose();
  15417. }
  15418. if (this.reflectionTexture) {
  15419. this.reflectionTexture.dispose();
  15420. }
  15421. if (this.emissiveTexture) {
  15422. this.emissiveTexture.dispose();
  15423. }
  15424. if (this.specularTexture) {
  15425. this.specularTexture.dispose();
  15426. }
  15427. if (this.bumpTexture) {
  15428. this.bumpTexture.dispose();
  15429. }
  15430. _super.prototype.dispose.call(this, forceDisposeEffect);
  15431. };
  15432. StandardMaterial.prototype.clone = function (name) {
  15433. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15434. // Base material
  15435. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15436. newStandardMaterial.alpha = this.alpha;
  15437. newStandardMaterial.fillMode = this.fillMode;
  15438. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15439. // Standard material
  15440. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15441. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15442. }
  15443. if (this.ambientTexture && this.ambientTexture.clone) {
  15444. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15445. }
  15446. if (this.opacityTexture && this.opacityTexture.clone) {
  15447. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15448. }
  15449. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15450. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15451. }
  15452. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15453. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15454. }
  15455. if (this.specularTexture && this.specularTexture.clone) {
  15456. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15457. }
  15458. if (this.bumpTexture && this.bumpTexture.clone) {
  15459. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15460. }
  15461. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15462. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15463. newStandardMaterial.specularColor = this.specularColor.clone();
  15464. newStandardMaterial.specularPower = this.specularPower;
  15465. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15466. return newStandardMaterial;
  15467. };
  15468. // Statics
  15469. // Flags used to enable or disable a type of texture for all Standard Materials
  15470. StandardMaterial.DiffuseTextureEnabled = true;
  15471. StandardMaterial.AmbientTextureEnabled = true;
  15472. StandardMaterial.OpacityTextureEnabled = true;
  15473. StandardMaterial.ReflectionTextureEnabled = true;
  15474. StandardMaterial.EmissiveTextureEnabled = true;
  15475. StandardMaterial.SpecularTextureEnabled = true;
  15476. StandardMaterial.BumpTextureEnabled = true;
  15477. StandardMaterial.FresnelEnabled = true;
  15478. return StandardMaterial;
  15479. })(BABYLON.Material);
  15480. BABYLON.StandardMaterial = StandardMaterial;
  15481. })(BABYLON || (BABYLON = {}));
  15482. //# sourceMappingURL=babylon.standardMaterial.js.map
  15483. var BABYLON;
  15484. (function (BABYLON) {
  15485. var MultiMaterial = (function (_super) {
  15486. __extends(MultiMaterial, _super);
  15487. function MultiMaterial(name, scene) {
  15488. _super.call(this, name, scene, true);
  15489. this.subMaterials = new Array();
  15490. scene.multiMaterials.push(this);
  15491. }
  15492. // Properties
  15493. MultiMaterial.prototype.getSubMaterial = function (index) {
  15494. if (index < 0 || index >= this.subMaterials.length) {
  15495. return this.getScene().defaultMaterial;
  15496. }
  15497. return this.subMaterials[index];
  15498. };
  15499. // Methods
  15500. MultiMaterial.prototype.isReady = function (mesh) {
  15501. for (var index = 0; index < this.subMaterials.length; index++) {
  15502. var subMaterial = this.subMaterials[index];
  15503. if (subMaterial) {
  15504. if (!this.subMaterials[index].isReady(mesh)) {
  15505. return false;
  15506. }
  15507. }
  15508. }
  15509. return true;
  15510. };
  15511. return MultiMaterial;
  15512. })(BABYLON.Material);
  15513. BABYLON.MultiMaterial = MultiMaterial;
  15514. })(BABYLON || (BABYLON = {}));
  15515. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15516. (function (BABYLON) {
  15517. var Database = (function () {
  15518. function Database(urlToScene, callbackManifestChecked) {
  15519. // Handling various flavors of prefixed version of IndexedDB
  15520. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15521. this.callbackManifestChecked = callbackManifestChecked;
  15522. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15523. this.db = null;
  15524. this.enableSceneOffline = false;
  15525. this.enableTexturesOffline = false;
  15526. this.manifestVersionFound = 0;
  15527. this.mustUpdateRessources = false;
  15528. this.hasReachedQuota = false;
  15529. this.checkManifestFile();
  15530. }
  15531. Database.prototype.checkManifestFile = function () {
  15532. var _this = this;
  15533. function noManifestFile() {
  15534. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15535. that.enableSceneOffline = false;
  15536. that.enableTexturesOffline = false;
  15537. that.callbackManifestChecked(false);
  15538. }
  15539. var that = this;
  15540. var manifestURL = this.currentSceneUrl + ".manifest";
  15541. var xhr = new XMLHttpRequest();
  15542. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15543. xhr.open("GET", manifestURLTimeStamped, true);
  15544. xhr.addEventListener("load", function () {
  15545. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15546. try {
  15547. var manifestFile = JSON.parse(xhr.response);
  15548. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15549. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15550. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15551. _this.manifestVersionFound = manifestFile.version;
  15552. }
  15553. if (_this.callbackManifestChecked) {
  15554. _this.callbackManifestChecked(true);
  15555. }
  15556. }
  15557. catch (ex) {
  15558. noManifestFile();
  15559. }
  15560. }
  15561. else {
  15562. noManifestFile();
  15563. }
  15564. }, false);
  15565. xhr.addEventListener("error", function (event) {
  15566. noManifestFile();
  15567. }, false);
  15568. try {
  15569. xhr.send();
  15570. }
  15571. catch (ex) {
  15572. BABYLON.Tools.Error("Error on XHR send request.");
  15573. that.callbackManifestChecked(false);
  15574. }
  15575. };
  15576. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15577. var _this = this;
  15578. function handleError() {
  15579. that.isSupported = false;
  15580. if (errorCallback)
  15581. errorCallback();
  15582. }
  15583. var that = this;
  15584. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15585. // Your browser doesn't support IndexedDB
  15586. this.isSupported = false;
  15587. if (errorCallback)
  15588. errorCallback();
  15589. }
  15590. else {
  15591. // If the DB hasn't been opened or created yet
  15592. if (!this.db) {
  15593. this.hasReachedQuota = false;
  15594. this.isSupported = true;
  15595. var request = this.idbFactory.open("babylonjs", 1);
  15596. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15597. request.onerror = function (event) {
  15598. handleError();
  15599. };
  15600. // executes when a version change transaction cannot complete due to other active transactions
  15601. request.onblocked = function (event) {
  15602. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15603. handleError();
  15604. };
  15605. // DB has been opened successfully
  15606. request.onsuccess = function (event) {
  15607. _this.db = request.result;
  15608. successCallback();
  15609. };
  15610. // Initialization of the DB. Creating Scenes & Textures stores
  15611. request.onupgradeneeded = function (event) {
  15612. _this.db = (event.target).result;
  15613. try {
  15614. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15615. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15616. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15617. }
  15618. catch (ex) {
  15619. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15620. handleError();
  15621. }
  15622. };
  15623. }
  15624. else {
  15625. if (successCallback)
  15626. successCallback();
  15627. }
  15628. }
  15629. };
  15630. Database.prototype.loadImageFromDB = function (url, image) {
  15631. var _this = this;
  15632. var completeURL = Database.ReturnFullUrlLocation(url);
  15633. var saveAndLoadImage = function () {
  15634. if (!_this.hasReachedQuota && _this.db !== null) {
  15635. // the texture is not yet in the DB, let's try to save it
  15636. _this._saveImageIntoDBAsync(completeURL, image);
  15637. }
  15638. else {
  15639. image.src = url;
  15640. }
  15641. };
  15642. if (!this.mustUpdateRessources) {
  15643. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15644. }
  15645. else {
  15646. saveAndLoadImage();
  15647. }
  15648. };
  15649. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15650. if (this.isSupported && this.db !== null) {
  15651. var texture;
  15652. var transaction = this.db.transaction(["textures"]);
  15653. transaction.onabort = function (event) {
  15654. image.src = url;
  15655. };
  15656. transaction.oncomplete = function (event) {
  15657. var blobTextureURL;
  15658. if (texture) {
  15659. var URL = window.URL || window.webkitURL;
  15660. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15661. image.onerror = function () {
  15662. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15663. image.src = url;
  15664. };
  15665. image.src = blobTextureURL;
  15666. }
  15667. else {
  15668. notInDBCallback();
  15669. }
  15670. };
  15671. var getRequest = transaction.objectStore("textures").get(url);
  15672. getRequest.onsuccess = function (event) {
  15673. texture = (event.target).result;
  15674. };
  15675. getRequest.onerror = function (event) {
  15676. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15677. image.src = url;
  15678. };
  15679. }
  15680. else {
  15681. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15682. image.src = url;
  15683. }
  15684. };
  15685. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15686. var _this = this;
  15687. if (this.isSupported) {
  15688. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15689. var generateBlobUrl = function () {
  15690. var blobTextureURL;
  15691. if (blob) {
  15692. var URL = window.URL || window.webkitURL;
  15693. try {
  15694. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15695. }
  15696. catch (ex) {
  15697. blobTextureURL = URL.createObjectURL(blob);
  15698. }
  15699. }
  15700. image.src = blobTextureURL;
  15701. };
  15702. if (Database.isUASupportingBlobStorage) {
  15703. var xhr = new XMLHttpRequest(), blob;
  15704. xhr.open("GET", url, true);
  15705. xhr.responseType = "blob";
  15706. xhr.addEventListener("load", function () {
  15707. if (xhr.status === 200) {
  15708. // Blob as response (XHR2)
  15709. blob = xhr.response;
  15710. var transaction = _this.db.transaction(["textures"], "readwrite");
  15711. // the transaction could abort because of a QuotaExceededError error
  15712. transaction.onabort = function (event) {
  15713. try {
  15714. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15715. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15716. this.hasReachedQuota = true;
  15717. }
  15718. }
  15719. catch (ex) {
  15720. }
  15721. generateBlobUrl();
  15722. };
  15723. transaction.oncomplete = function (event) {
  15724. generateBlobUrl();
  15725. };
  15726. var newTexture = { textureUrl: url, data: blob };
  15727. try {
  15728. // Put the blob into the dabase
  15729. var addRequest = transaction.objectStore("textures").put(newTexture);
  15730. addRequest.onsuccess = function (event) {
  15731. };
  15732. addRequest.onerror = function (event) {
  15733. generateBlobUrl();
  15734. };
  15735. }
  15736. catch (ex) {
  15737. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15738. if (ex.code === 25) {
  15739. Database.isUASupportingBlobStorage = false;
  15740. }
  15741. image.src = url;
  15742. }
  15743. }
  15744. else {
  15745. image.src = url;
  15746. }
  15747. }, false);
  15748. xhr.addEventListener("error", function (event) {
  15749. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15750. image.src = url;
  15751. }, false);
  15752. xhr.send();
  15753. }
  15754. else {
  15755. image.src = url;
  15756. }
  15757. }
  15758. else {
  15759. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15760. image.src = url;
  15761. }
  15762. };
  15763. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15764. var _this = this;
  15765. var updateVersion = function (event) {
  15766. // the version is not yet in the DB or we need to update it
  15767. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15768. };
  15769. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15770. };
  15771. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15772. var _this = this;
  15773. if (this.isSupported) {
  15774. var version;
  15775. try {
  15776. var transaction = this.db.transaction(["versions"]);
  15777. transaction.oncomplete = function (event) {
  15778. if (version) {
  15779. // If the version in the JSON file is > than the version in DB
  15780. if (_this.manifestVersionFound > version.data) {
  15781. _this.mustUpdateRessources = true;
  15782. updateInDBCallback();
  15783. }
  15784. else {
  15785. callback(version.data);
  15786. }
  15787. }
  15788. else {
  15789. _this.mustUpdateRessources = true;
  15790. updateInDBCallback();
  15791. }
  15792. };
  15793. transaction.onabort = function (event) {
  15794. callback(-1);
  15795. };
  15796. var getRequest = transaction.objectStore("versions").get(url);
  15797. getRequest.onsuccess = function (event) {
  15798. version = (event.target).result;
  15799. };
  15800. getRequest.onerror = function (event) {
  15801. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15802. callback(-1);
  15803. };
  15804. }
  15805. catch (ex) {
  15806. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15807. callback(-1);
  15808. }
  15809. }
  15810. else {
  15811. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15812. callback(-1);
  15813. }
  15814. };
  15815. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15816. var _this = this;
  15817. if (this.isSupported && !this.hasReachedQuota) {
  15818. try {
  15819. // Open a transaction to the database
  15820. var transaction = this.db.transaction(["versions"], "readwrite");
  15821. // the transaction could abort because of a QuotaExceededError error
  15822. transaction.onabort = function (event) {
  15823. try {
  15824. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15825. _this.hasReachedQuota = true;
  15826. }
  15827. }
  15828. catch (ex) {
  15829. }
  15830. callback(-1);
  15831. };
  15832. transaction.oncomplete = function (event) {
  15833. callback(_this.manifestVersionFound);
  15834. };
  15835. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15836. // Put the scene into the database
  15837. var addRequest = transaction.objectStore("versions").put(newVersion);
  15838. addRequest.onsuccess = function (event) {
  15839. };
  15840. addRequest.onerror = function (event) {
  15841. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15842. };
  15843. }
  15844. catch (ex) {
  15845. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15846. callback(-1);
  15847. }
  15848. }
  15849. else {
  15850. callback(-1);
  15851. }
  15852. };
  15853. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15854. var _this = this;
  15855. var completeUrl = Database.ReturnFullUrlLocation(url);
  15856. var saveAndLoadFile = function (event) {
  15857. // the scene is not yet in the DB, let's try to save it
  15858. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15859. };
  15860. this._checkVersionFromDB(completeUrl, function (version) {
  15861. if (version !== -1) {
  15862. if (!_this.mustUpdateRessources) {
  15863. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15864. }
  15865. else {
  15866. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15867. }
  15868. }
  15869. else {
  15870. errorCallback();
  15871. }
  15872. });
  15873. };
  15874. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15875. if (this.isSupported) {
  15876. var targetStore;
  15877. if (url.indexOf(".babylon") !== -1) {
  15878. targetStore = "scenes";
  15879. }
  15880. else {
  15881. targetStore = "textures";
  15882. }
  15883. var file;
  15884. var transaction = this.db.transaction([targetStore]);
  15885. transaction.oncomplete = function (event) {
  15886. if (file) {
  15887. callback(file.data);
  15888. }
  15889. else {
  15890. notInDBCallback();
  15891. }
  15892. };
  15893. transaction.onabort = function (event) {
  15894. notInDBCallback();
  15895. };
  15896. var getRequest = transaction.objectStore(targetStore).get(url);
  15897. getRequest.onsuccess = function (event) {
  15898. file = (event.target).result;
  15899. };
  15900. getRequest.onerror = function (event) {
  15901. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15902. notInDBCallback();
  15903. };
  15904. }
  15905. else {
  15906. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15907. callback();
  15908. }
  15909. };
  15910. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15911. var _this = this;
  15912. if (this.isSupported) {
  15913. var targetStore;
  15914. if (url.indexOf(".babylon") !== -1) {
  15915. targetStore = "scenes";
  15916. }
  15917. else {
  15918. targetStore = "textures";
  15919. }
  15920. // Create XHR
  15921. var xhr = new XMLHttpRequest(), fileData;
  15922. xhr.open("GET", url, true);
  15923. if (useArrayBuffer) {
  15924. xhr.responseType = "arraybuffer";
  15925. }
  15926. xhr.onprogress = progressCallback;
  15927. xhr.addEventListener("load", function () {
  15928. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15929. // Blob as response (XHR2)
  15930. //fileData = xhr.responseText;
  15931. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15932. if (!_this.hasReachedQuota) {
  15933. // Open a transaction to the database
  15934. var transaction = _this.db.transaction([targetStore], "readwrite");
  15935. // the transaction could abort because of a QuotaExceededError error
  15936. transaction.onabort = function (event) {
  15937. try {
  15938. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15939. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15940. this.hasReachedQuota = true;
  15941. }
  15942. }
  15943. catch (ex) {
  15944. }
  15945. callback(fileData);
  15946. };
  15947. transaction.oncomplete = function (event) {
  15948. callback(fileData);
  15949. };
  15950. var newFile;
  15951. if (targetStore === "scenes") {
  15952. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15953. }
  15954. else {
  15955. newFile = { textureUrl: url, data: fileData };
  15956. }
  15957. try {
  15958. // Put the scene into the database
  15959. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15960. addRequest.onsuccess = function (event) {
  15961. };
  15962. addRequest.onerror = function (event) {
  15963. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15964. };
  15965. }
  15966. catch (ex) {
  15967. callback(fileData);
  15968. }
  15969. }
  15970. else {
  15971. callback(fileData);
  15972. }
  15973. }
  15974. else {
  15975. callback();
  15976. }
  15977. }, false);
  15978. xhr.addEventListener("error", function (event) {
  15979. BABYLON.Tools.Error("error on XHR request.");
  15980. callback();
  15981. }, false);
  15982. xhr.send();
  15983. }
  15984. else {
  15985. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15986. callback();
  15987. }
  15988. };
  15989. Database.isUASupportingBlobStorage = true;
  15990. Database.parseURL = function (url) {
  15991. var a = document.createElement('a');
  15992. a.href = url;
  15993. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15994. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15995. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15996. return absLocation;
  15997. };
  15998. Database.ReturnFullUrlLocation = function (url) {
  15999. if (url.indexOf("http:/") === -1) {
  16000. return (BABYLON.Database.parseURL(window.location.href) + url);
  16001. }
  16002. else {
  16003. return url;
  16004. }
  16005. };
  16006. return Database;
  16007. })();
  16008. BABYLON.Database = Database;
  16009. })(BABYLON || (BABYLON = {}));
  16010. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  16011. (function (BABYLON) {
  16012. var SpriteManager = (function () {
  16013. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  16014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16015. this.name = name;
  16016. this.cellSize = cellSize;
  16017. this.sprites = new Array();
  16018. this.renderingGroupId = 0;
  16019. this.fogEnabled = true;
  16020. this._vertexDeclaration = [4, 4, 4, 4];
  16021. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  16022. this._capacity = capacity;
  16023. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  16024. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16025. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16026. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  16027. this._scene = scene;
  16028. this._scene.spriteManagers.push(this);
  16029. // VBO
  16030. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16031. var indices = [];
  16032. var index = 0;
  16033. for (var count = 0; count < capacity; count++) {
  16034. indices.push(index);
  16035. indices.push(index + 1);
  16036. indices.push(index + 2);
  16037. indices.push(index);
  16038. indices.push(index + 2);
  16039. indices.push(index + 3);
  16040. index += 4;
  16041. }
  16042. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16043. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16044. // Effects
  16045. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  16046. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  16047. }
  16048. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  16049. var arrayOffset = index * 16;
  16050. if (offsetX === 0)
  16051. offsetX = this._epsilon;
  16052. else if (offsetX === 1)
  16053. offsetX = 1 - this._epsilon;
  16054. if (offsetY === 0)
  16055. offsetY = this._epsilon;
  16056. else if (offsetY === 1)
  16057. offsetY = 1 - this._epsilon;
  16058. this._vertices[arrayOffset] = sprite.position.x;
  16059. this._vertices[arrayOffset + 1] = sprite.position.y;
  16060. this._vertices[arrayOffset + 2] = sprite.position.z;
  16061. this._vertices[arrayOffset + 3] = sprite.angle;
  16062. this._vertices[arrayOffset + 4] = sprite.width;
  16063. this._vertices[arrayOffset + 5] = sprite.height;
  16064. this._vertices[arrayOffset + 6] = offsetX;
  16065. this._vertices[arrayOffset + 7] = offsetY;
  16066. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  16067. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  16068. var offset = (sprite.cellIndex / rowSize) >> 0;
  16069. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  16070. this._vertices[arrayOffset + 11] = offset;
  16071. // Color
  16072. this._vertices[arrayOffset + 12] = sprite.color.r;
  16073. this._vertices[arrayOffset + 13] = sprite.color.g;
  16074. this._vertices[arrayOffset + 14] = sprite.color.b;
  16075. this._vertices[arrayOffset + 15] = sprite.color.a;
  16076. };
  16077. SpriteManager.prototype.render = function () {
  16078. // Check
  16079. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  16080. return;
  16081. var engine = this._scene.getEngine();
  16082. var baseSize = this._spriteTexture.getBaseSize();
  16083. // Sprites
  16084. var deltaTime = engine.getDeltaTime();
  16085. var max = Math.min(this._capacity, this.sprites.length);
  16086. var rowSize = baseSize.width / this.cellSize;
  16087. var offset = 0;
  16088. for (var index = 0; index < max; index++) {
  16089. var sprite = this.sprites[index];
  16090. if (!sprite) {
  16091. continue;
  16092. }
  16093. sprite._animate(deltaTime);
  16094. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  16095. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  16096. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  16097. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  16098. }
  16099. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16100. // Render
  16101. var effect = this._effectBase;
  16102. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16103. effect = this._effectFog;
  16104. }
  16105. engine.enableEffect(effect);
  16106. var viewMatrix = this._scene.getViewMatrix();
  16107. effect.setTexture("diffuseSampler", this._spriteTexture);
  16108. effect.setMatrix("view", viewMatrix);
  16109. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16110. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  16111. // Fog
  16112. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16113. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  16114. effect.setColor3("vFogColor", this._scene.fogColor);
  16115. }
  16116. // VBOs
  16117. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16118. // Draw order
  16119. engine.setDepthFunctionToLessOrEqual();
  16120. effect.setBool("alphaTest", true);
  16121. engine.setColorWrite(false);
  16122. engine.draw(true, 0, max * 6);
  16123. engine.setColorWrite(true);
  16124. effect.setBool("alphaTest", false);
  16125. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16126. engine.draw(true, 0, max * 6);
  16127. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16128. };
  16129. SpriteManager.prototype.dispose = function () {
  16130. if (this._vertexBuffer) {
  16131. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16132. this._vertexBuffer = null;
  16133. }
  16134. if (this._indexBuffer) {
  16135. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16136. this._indexBuffer = null;
  16137. }
  16138. if (this._spriteTexture) {
  16139. this._spriteTexture.dispose();
  16140. this._spriteTexture = null;
  16141. }
  16142. // Remove from scene
  16143. var index = this._scene.spriteManagers.indexOf(this);
  16144. this._scene.spriteManagers.splice(index, 1);
  16145. // Callback
  16146. if (this.onDispose) {
  16147. this.onDispose();
  16148. }
  16149. };
  16150. return SpriteManager;
  16151. })();
  16152. BABYLON.SpriteManager = SpriteManager;
  16153. })(BABYLON || (BABYLON = {}));
  16154. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  16155. (function (BABYLON) {
  16156. var Sprite = (function () {
  16157. function Sprite(name, manager) {
  16158. this.name = name;
  16159. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16160. this.width = 1.0;
  16161. this.height = 1.0;
  16162. this.angle = 0;
  16163. this.cellIndex = 0;
  16164. this.invertU = 0;
  16165. this.invertV = 0;
  16166. this.animations = new Array();
  16167. this._animationStarted = false;
  16168. this._loopAnimation = false;
  16169. this._fromIndex = 0;
  16170. this._toIndex = 0;
  16171. this._delay = 0;
  16172. this._direction = 1;
  16173. this._frameCount = 0;
  16174. this._time = 0;
  16175. this._manager = manager;
  16176. this._manager.sprites.push(this);
  16177. this.position = BABYLON.Vector3.Zero();
  16178. }
  16179. Object.defineProperty(Sprite.prototype, "size", {
  16180. get: function () {
  16181. return this.width;
  16182. },
  16183. set: function (value) {
  16184. this.width = value;
  16185. this.height = value;
  16186. },
  16187. enumerable: true,
  16188. configurable: true
  16189. });
  16190. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  16191. this._fromIndex = from;
  16192. this._toIndex = to;
  16193. this._loopAnimation = loop;
  16194. this._delay = delay;
  16195. this._animationStarted = true;
  16196. this._direction = from < to ? 1 : -1;
  16197. this.cellIndex = from;
  16198. this._time = 0;
  16199. };
  16200. Sprite.prototype.stopAnimation = function () {
  16201. this._animationStarted = false;
  16202. };
  16203. Sprite.prototype._animate = function (deltaTime) {
  16204. if (!this._animationStarted)
  16205. return;
  16206. this._time += deltaTime;
  16207. if (this._time > this._delay) {
  16208. this._time = this._time % this._delay;
  16209. this.cellIndex += this._direction;
  16210. if (this.cellIndex == this._toIndex) {
  16211. if (this._loopAnimation) {
  16212. this.cellIndex = this._fromIndex;
  16213. }
  16214. else {
  16215. this._animationStarted = false;
  16216. if (this.disposeWhenFinishedAnimating) {
  16217. this.dispose();
  16218. }
  16219. }
  16220. }
  16221. }
  16222. };
  16223. Sprite.prototype.dispose = function () {
  16224. for (var i = 0; i < this._manager.sprites.length; i++) {
  16225. if (this._manager.sprites[i] == this) {
  16226. this._manager.sprites.splice(i, 1);
  16227. }
  16228. }
  16229. };
  16230. return Sprite;
  16231. })();
  16232. BABYLON.Sprite = Sprite;
  16233. })(BABYLON || (BABYLON = {}));
  16234. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  16235. (function (BABYLON) {
  16236. var Layer = (function () {
  16237. function Layer(name, imgUrl, scene, isBackground, color) {
  16238. this.name = name;
  16239. this._vertexDeclaration = [2];
  16240. this._vertexStrideSize = 2 * 4;
  16241. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16242. this.isBackground = isBackground === undefined ? true : isBackground;
  16243. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16244. this._scene = scene;
  16245. this._scene.layers.push(this);
  16246. // VBO
  16247. var vertices = [];
  16248. vertices.push(1, 1);
  16249. vertices.push(-1, 1);
  16250. vertices.push(-1, -1);
  16251. vertices.push(1, -1);
  16252. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16253. // Indices
  16254. var indices = [];
  16255. indices.push(0);
  16256. indices.push(1);
  16257. indices.push(2);
  16258. indices.push(0);
  16259. indices.push(2);
  16260. indices.push(3);
  16261. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16262. // Effects
  16263. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16264. }
  16265. Layer.prototype.render = function () {
  16266. // Check
  16267. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16268. return;
  16269. var engine = this._scene.getEngine();
  16270. // Render
  16271. engine.enableEffect(this._effect);
  16272. engine.setState(false);
  16273. // Texture
  16274. this._effect.setTexture("textureSampler", this.texture);
  16275. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16276. // Color
  16277. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16278. // VBOs
  16279. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16280. // Draw order
  16281. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16282. engine.draw(true, 0, 6);
  16283. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16284. };
  16285. Layer.prototype.dispose = function () {
  16286. if (this._vertexBuffer) {
  16287. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16288. this._vertexBuffer = null;
  16289. }
  16290. if (this._indexBuffer) {
  16291. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16292. this._indexBuffer = null;
  16293. }
  16294. if (this.texture) {
  16295. this.texture.dispose();
  16296. this.texture = null;
  16297. }
  16298. // Remove from scene
  16299. var index = this._scene.layers.indexOf(this);
  16300. this._scene.layers.splice(index, 1);
  16301. // Callback
  16302. if (this.onDispose) {
  16303. this.onDispose();
  16304. }
  16305. };
  16306. return Layer;
  16307. })();
  16308. BABYLON.Layer = Layer;
  16309. })(BABYLON || (BABYLON = {}));
  16310. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16311. (function (BABYLON) {
  16312. var Particle = (function () {
  16313. function Particle() {
  16314. this.position = BABYLON.Vector3.Zero();
  16315. this.direction = BABYLON.Vector3.Zero();
  16316. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16317. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16318. this.lifeTime = 1.0;
  16319. this.age = 0;
  16320. this.size = 0;
  16321. this.angle = 0;
  16322. this.angularSpeed = 0;
  16323. }
  16324. Particle.prototype.copyTo = function (other) {
  16325. other.position.copyFrom(this.position);
  16326. other.direction.copyFrom(this.direction);
  16327. other.color.copyFrom(this.color);
  16328. other.colorStep.copyFrom(this.colorStep);
  16329. other.lifeTime = this.lifeTime;
  16330. other.age = this.age;
  16331. other.size = this.size;
  16332. other.angle = this.angle;
  16333. other.angularSpeed = this.angularSpeed;
  16334. };
  16335. return Particle;
  16336. })();
  16337. BABYLON.Particle = Particle;
  16338. })(BABYLON || (BABYLON = {}));
  16339. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16340. (function (BABYLON) {
  16341. var randomNumber = function (min, max) {
  16342. if (min === max) {
  16343. return (min);
  16344. }
  16345. var random = Math.random();
  16346. return ((random * (max - min)) + min);
  16347. };
  16348. var ParticleSystem = (function () {
  16349. function ParticleSystem(name, capacity, scene, customEffect) {
  16350. var _this = this;
  16351. this.name = name;
  16352. this.renderingGroupId = 0;
  16353. this.emitter = null;
  16354. this.emitRate = 10;
  16355. this.manualEmitCount = -1;
  16356. this.updateSpeed = 0.01;
  16357. this.targetStopDuration = 0;
  16358. this.disposeOnStop = false;
  16359. this.minEmitPower = 1;
  16360. this.maxEmitPower = 1;
  16361. this.minLifeTime = 1;
  16362. this.maxLifeTime = 1;
  16363. this.minSize = 1;
  16364. this.maxSize = 1;
  16365. this.minAngularSpeed = 0;
  16366. this.maxAngularSpeed = 0;
  16367. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16368. this.forceDepthWrite = false;
  16369. this.gravity = BABYLON.Vector3.Zero();
  16370. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16371. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16372. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16373. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16374. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16375. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16376. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16377. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16378. this.particles = new Array();
  16379. this._vertexDeclaration = [3, 4, 4];
  16380. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16381. this._stockParticles = new Array();
  16382. this._newPartsExcess = 0;
  16383. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16384. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16385. this._scaledDirection = BABYLON.Vector3.Zero();
  16386. this._scaledGravity = BABYLON.Vector3.Zero();
  16387. this._currentRenderId = -1;
  16388. this._started = false;
  16389. this._stopped = false;
  16390. this._actualFrame = 0;
  16391. this.id = name;
  16392. this._capacity = capacity;
  16393. this._scene = scene;
  16394. this._customEffect = customEffect;
  16395. scene.particleSystems.push(this);
  16396. // VBO
  16397. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16398. var indices = [];
  16399. var index = 0;
  16400. for (var count = 0; count < capacity; count++) {
  16401. indices.push(index);
  16402. indices.push(index + 1);
  16403. indices.push(index + 2);
  16404. indices.push(index);
  16405. indices.push(index + 2);
  16406. indices.push(index + 3);
  16407. index += 4;
  16408. }
  16409. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16410. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16411. // Default behaviors
  16412. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16413. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16414. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16415. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16416. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16417. };
  16418. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16419. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16420. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16421. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16422. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16423. };
  16424. this.updateFunction = function (particles) {
  16425. for (var index = 0; index < particles.length; index++) {
  16426. var particle = particles[index];
  16427. particle.age += _this._scaledUpdateSpeed;
  16428. if (particle.age >= particle.lifeTime) {
  16429. _this.recycleParticle(particle);
  16430. index--;
  16431. continue;
  16432. }
  16433. else {
  16434. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16435. particle.color.addInPlace(_this._scaledColorStep);
  16436. if (particle.color.a < 0)
  16437. particle.color.a = 0;
  16438. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16439. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16440. particle.position.addInPlace(_this._scaledDirection);
  16441. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16442. particle.direction.addInPlace(_this._scaledGravity);
  16443. }
  16444. }
  16445. };
  16446. }
  16447. ParticleSystem.prototype.recycleParticle = function (particle) {
  16448. var lastParticle = this.particles.pop();
  16449. if (lastParticle !== particle) {
  16450. lastParticle.copyTo(particle);
  16451. this._stockParticles.push(lastParticle);
  16452. }
  16453. };
  16454. ParticleSystem.prototype.getCapacity = function () {
  16455. return this._capacity;
  16456. };
  16457. ParticleSystem.prototype.isAlive = function () {
  16458. return this._alive;
  16459. };
  16460. ParticleSystem.prototype.isStarted = function () {
  16461. return this._started;
  16462. };
  16463. ParticleSystem.prototype.start = function () {
  16464. this._started = true;
  16465. this._stopped = false;
  16466. this._actualFrame = 0;
  16467. };
  16468. ParticleSystem.prototype.stop = function () {
  16469. this._stopped = true;
  16470. };
  16471. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16472. var offset = index * 11;
  16473. this._vertices[offset] = particle.position.x;
  16474. this._vertices[offset + 1] = particle.position.y;
  16475. this._vertices[offset + 2] = particle.position.z;
  16476. this._vertices[offset + 3] = particle.color.r;
  16477. this._vertices[offset + 4] = particle.color.g;
  16478. this._vertices[offset + 5] = particle.color.b;
  16479. this._vertices[offset + 6] = particle.color.a;
  16480. this._vertices[offset + 7] = particle.angle;
  16481. this._vertices[offset + 8] = particle.size;
  16482. this._vertices[offset + 9] = offsetX;
  16483. this._vertices[offset + 10] = offsetY;
  16484. };
  16485. ParticleSystem.prototype._update = function (newParticles) {
  16486. // Update current
  16487. this._alive = this.particles.length > 0;
  16488. this.updateFunction(this.particles);
  16489. // Add new ones
  16490. var worldMatrix;
  16491. if (this.emitter.position) {
  16492. worldMatrix = this.emitter.getWorldMatrix();
  16493. }
  16494. else {
  16495. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16496. }
  16497. for (var index = 0; index < newParticles; index++) {
  16498. if (this.particles.length === this._capacity) {
  16499. break;
  16500. }
  16501. if (this._stockParticles.length !== 0) {
  16502. var particle = this._stockParticles.pop();
  16503. particle.age = 0;
  16504. }
  16505. else {
  16506. particle = new BABYLON.Particle();
  16507. }
  16508. this.particles.push(particle);
  16509. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16510. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16511. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16512. particle.size = randomNumber(this.minSize, this.maxSize);
  16513. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16514. this.startPositionFunction(worldMatrix, particle.position);
  16515. var step = randomNumber(0, 1.0);
  16516. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16517. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16518. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16519. }
  16520. };
  16521. ParticleSystem.prototype._getEffect = function () {
  16522. if (this._customEffect) {
  16523. return this._customEffect;
  16524. }
  16525. ;
  16526. var defines = [];
  16527. if (this._scene.clipPlane) {
  16528. defines.push("#define CLIPPLANE");
  16529. }
  16530. // Effect
  16531. var join = defines.join("\n");
  16532. if (this._cachedDefines !== join) {
  16533. this._cachedDefines = join;
  16534. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16535. }
  16536. return this._effect;
  16537. };
  16538. ParticleSystem.prototype.animate = function () {
  16539. if (!this._started)
  16540. return;
  16541. var effect = this._getEffect();
  16542. // Check
  16543. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16544. return;
  16545. if (this._currentRenderId === this._scene.getRenderId()) {
  16546. return;
  16547. }
  16548. this._currentRenderId = this._scene.getRenderId();
  16549. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16550. // determine the number of particles we need to create
  16551. var emitCout;
  16552. if (this.manualEmitCount > -1) {
  16553. emitCout = this.manualEmitCount;
  16554. this.manualEmitCount = 0;
  16555. }
  16556. else {
  16557. emitCout = this.emitRate;
  16558. }
  16559. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16560. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16561. if (this._newPartsExcess > 1.0) {
  16562. newParticles += this._newPartsExcess >> 0;
  16563. this._newPartsExcess -= this._newPartsExcess >> 0;
  16564. }
  16565. this._alive = false;
  16566. if (!this._stopped) {
  16567. this._actualFrame += this._scaledUpdateSpeed;
  16568. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16569. this.stop();
  16570. }
  16571. else {
  16572. newParticles = 0;
  16573. }
  16574. this._update(newParticles);
  16575. // Stopped?
  16576. if (this._stopped) {
  16577. if (!this._alive) {
  16578. this._started = false;
  16579. if (this.disposeOnStop) {
  16580. this._scene._toBeDisposed.push(this);
  16581. }
  16582. }
  16583. }
  16584. // Update VBO
  16585. var offset = 0;
  16586. for (var index = 0; index < this.particles.length; index++) {
  16587. var particle = this.particles[index];
  16588. this._appendParticleVertex(offset++, particle, 0, 0);
  16589. this._appendParticleVertex(offset++, particle, 1, 0);
  16590. this._appendParticleVertex(offset++, particle, 1, 1);
  16591. this._appendParticleVertex(offset++, particle, 0, 1);
  16592. }
  16593. var engine = this._scene.getEngine();
  16594. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16595. };
  16596. ParticleSystem.prototype.render = function () {
  16597. var effect = this._getEffect();
  16598. // Check
  16599. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16600. return 0;
  16601. var engine = this._scene.getEngine();
  16602. // Render
  16603. engine.enableEffect(effect);
  16604. engine.setState(false);
  16605. var viewMatrix = this._scene.getViewMatrix();
  16606. effect.setTexture("diffuseSampler", this.particleTexture);
  16607. effect.setMatrix("view", viewMatrix);
  16608. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16609. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16610. if (this._scene.clipPlane) {
  16611. var clipPlane = this._scene.clipPlane;
  16612. var invView = viewMatrix.clone();
  16613. invView.invert();
  16614. effect.setMatrix("invView", invView);
  16615. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16616. }
  16617. // VBOs
  16618. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16619. // Draw order
  16620. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16621. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16622. }
  16623. else {
  16624. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16625. }
  16626. if (this.forceDepthWrite) {
  16627. engine.setDepthWrite(true);
  16628. }
  16629. engine.draw(true, 0, this.particles.length * 6);
  16630. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16631. return this.particles.length;
  16632. };
  16633. ParticleSystem.prototype.dispose = function () {
  16634. if (this._vertexBuffer) {
  16635. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16636. this._vertexBuffer = null;
  16637. }
  16638. if (this._indexBuffer) {
  16639. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16640. this._indexBuffer = null;
  16641. }
  16642. if (this.particleTexture) {
  16643. this.particleTexture.dispose();
  16644. this.particleTexture = null;
  16645. }
  16646. // Remove from scene
  16647. var index = this._scene.particleSystems.indexOf(this);
  16648. this._scene.particleSystems.splice(index, 1);
  16649. // Callback
  16650. if (this.onDispose) {
  16651. this.onDispose();
  16652. }
  16653. };
  16654. // Clone
  16655. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16656. var result = new ParticleSystem(name, this._capacity, this._scene);
  16657. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16658. if (newEmitter === undefined) {
  16659. newEmitter = this.emitter;
  16660. }
  16661. result.emitter = newEmitter;
  16662. if (this.particleTexture) {
  16663. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16664. }
  16665. result.start();
  16666. return result;
  16667. };
  16668. // Statics
  16669. ParticleSystem.BLENDMODE_ONEONE = 0;
  16670. ParticleSystem.BLENDMODE_STANDARD = 1;
  16671. return ParticleSystem;
  16672. })();
  16673. BABYLON.ParticleSystem = ParticleSystem;
  16674. })(BABYLON || (BABYLON = {}));
  16675. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16676. (function (BABYLON) {
  16677. var Animation = (function () {
  16678. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16679. this.name = name;
  16680. this.targetProperty = targetProperty;
  16681. this.framePerSecond = framePerSecond;
  16682. this.dataType = dataType;
  16683. this.loopMode = loopMode;
  16684. this._offsetsCache = {};
  16685. this._highLimitsCache = {};
  16686. this._stopped = false;
  16687. this.targetPropertyPath = targetProperty.split(".");
  16688. this.dataType = dataType;
  16689. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16690. }
  16691. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16692. var dataType = undefined;
  16693. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16694. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16695. }
  16696. else if (from instanceof BABYLON.Quaternion) {
  16697. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16698. }
  16699. else if (from instanceof BABYLON.Vector3) {
  16700. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16701. }
  16702. else if (from instanceof BABYLON.Vector2) {
  16703. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16704. }
  16705. else if (from instanceof BABYLON.Color3) {
  16706. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16707. }
  16708. if (dataType == undefined) {
  16709. return null;
  16710. }
  16711. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16712. var keys = [];
  16713. keys.push({ frame: 0, value: from });
  16714. keys.push({ frame: totalFrame, value: to });
  16715. animation.setKeys(keys);
  16716. mesh.animations.push(animation);
  16717. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16718. };
  16719. // Methods
  16720. Animation.prototype.isStopped = function () {
  16721. return this._stopped;
  16722. };
  16723. Animation.prototype.getKeys = function () {
  16724. return this._keys;
  16725. };
  16726. Animation.prototype.getEasingFunction = function () {
  16727. return this._easingFunction;
  16728. };
  16729. Animation.prototype.setEasingFunction = function (easingFunction) {
  16730. this._easingFunction = easingFunction;
  16731. };
  16732. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16733. return startValue + (endValue - startValue) * gradient;
  16734. };
  16735. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16736. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16737. };
  16738. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16739. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16740. };
  16741. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16742. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16743. };
  16744. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16745. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16746. };
  16747. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16748. var startScale = new BABYLON.Vector3(0, 0, 0);
  16749. var startRotation = new BABYLON.Quaternion();
  16750. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16751. startValue.decompose(startScale, startRotation, startTranslation);
  16752. var endScale = new BABYLON.Vector3(0, 0, 0);
  16753. var endRotation = new BABYLON.Quaternion();
  16754. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16755. endValue.decompose(endScale, endRotation, endTranslation);
  16756. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16757. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16758. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16759. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16760. return result;
  16761. };
  16762. Animation.prototype.clone = function () {
  16763. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16764. clone.setKeys(this._keys);
  16765. return clone;
  16766. };
  16767. Animation.prototype.setKeys = function (values) {
  16768. this._keys = values.slice(0);
  16769. this._offsetsCache = {};
  16770. this._highLimitsCache = {};
  16771. };
  16772. Animation.prototype._getKeyValue = function (value) {
  16773. if (typeof value === "function") {
  16774. return value();
  16775. }
  16776. return value;
  16777. };
  16778. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16779. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16780. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16781. }
  16782. this.currentFrame = currentFrame;
  16783. // Try to get a hash to find the right key
  16784. 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));
  16785. if (this._keys[startKey].frame >= currentFrame) {
  16786. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16787. startKey--;
  16788. }
  16789. }
  16790. for (var key = startKey; key < this._keys.length; key++) {
  16791. if (this._keys[key + 1].frame >= currentFrame) {
  16792. var startValue = this._getKeyValue(this._keys[key].value);
  16793. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16794. // gradient : percent of currentFrame between the frame inf and the frame sup
  16795. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16796. // check for easingFunction and correction of gradient
  16797. if (this._easingFunction != null) {
  16798. gradient = this._easingFunction.ease(gradient);
  16799. }
  16800. switch (this.dataType) {
  16801. case Animation.ANIMATIONTYPE_FLOAT:
  16802. switch (loopMode) {
  16803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16805. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16807. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16808. }
  16809. break;
  16810. case Animation.ANIMATIONTYPE_QUATERNION:
  16811. var quaternion = null;
  16812. switch (loopMode) {
  16813. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16814. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16815. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16816. break;
  16817. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16818. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16819. break;
  16820. }
  16821. return quaternion;
  16822. case Animation.ANIMATIONTYPE_VECTOR3:
  16823. switch (loopMode) {
  16824. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16825. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16826. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16827. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16828. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16829. }
  16830. case Animation.ANIMATIONTYPE_VECTOR2:
  16831. switch (loopMode) {
  16832. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16833. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16834. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16835. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16836. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16837. }
  16838. case Animation.ANIMATIONTYPE_COLOR3:
  16839. switch (loopMode) {
  16840. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16841. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16842. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16843. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16844. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16845. }
  16846. case Animation.ANIMATIONTYPE_MATRIX:
  16847. switch (loopMode) {
  16848. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16849. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16850. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16851. return startValue;
  16852. }
  16853. default:
  16854. break;
  16855. }
  16856. break;
  16857. }
  16858. }
  16859. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16860. };
  16861. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16862. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16863. this._stopped = true;
  16864. return false;
  16865. }
  16866. var returnValue = true;
  16867. // Adding a start key at frame 0 if missing
  16868. if (this._keys[0].frame !== 0) {
  16869. var newKey = { frame: 0, value: this._keys[0].value };
  16870. this._keys.splice(0, 0, newKey);
  16871. }
  16872. // Check limits
  16873. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16874. from = this._keys[0].frame;
  16875. }
  16876. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16877. to = this._keys[this._keys.length - 1].frame;
  16878. }
  16879. // Compute ratio
  16880. var range = to - from;
  16881. var offsetValue;
  16882. // ratio represents the frame delta between from and to
  16883. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16884. var highLimitValue = 0;
  16885. if (ratio > range && !loop) {
  16886. returnValue = false;
  16887. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16888. }
  16889. else {
  16890. // Get max value if required
  16891. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16892. var keyOffset = to.toString() + from.toString();
  16893. if (!this._offsetsCache[keyOffset]) {
  16894. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16895. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16896. switch (this.dataType) {
  16897. case Animation.ANIMATIONTYPE_FLOAT:
  16898. this._offsetsCache[keyOffset] = toValue - fromValue;
  16899. break;
  16900. case Animation.ANIMATIONTYPE_QUATERNION:
  16901. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16902. break;
  16903. case Animation.ANIMATIONTYPE_VECTOR3:
  16904. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16905. case Animation.ANIMATIONTYPE_VECTOR2:
  16906. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16907. case Animation.ANIMATIONTYPE_COLOR3:
  16908. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16909. default:
  16910. break;
  16911. }
  16912. this._highLimitsCache[keyOffset] = toValue;
  16913. }
  16914. highLimitValue = this._highLimitsCache[keyOffset];
  16915. offsetValue = this._offsetsCache[keyOffset];
  16916. }
  16917. }
  16918. if (offsetValue === undefined) {
  16919. switch (this.dataType) {
  16920. case Animation.ANIMATIONTYPE_FLOAT:
  16921. offsetValue = 0;
  16922. break;
  16923. case Animation.ANIMATIONTYPE_QUATERNION:
  16924. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16925. break;
  16926. case Animation.ANIMATIONTYPE_VECTOR3:
  16927. offsetValue = BABYLON.Vector3.Zero();
  16928. break;
  16929. case Animation.ANIMATIONTYPE_VECTOR2:
  16930. offsetValue = BABYLON.Vector2.Zero();
  16931. break;
  16932. case Animation.ANIMATIONTYPE_COLOR3:
  16933. offsetValue = BABYLON.Color3.Black();
  16934. }
  16935. }
  16936. // Compute value
  16937. var repeatCount = (ratio / range) >> 0;
  16938. var currentFrame = returnValue ? from + ratio % range : to;
  16939. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16940. // Set value
  16941. if (this.targetPropertyPath.length > 1) {
  16942. var property = this._target[this.targetPropertyPath[0]];
  16943. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16944. property = property[this.targetPropertyPath[index]];
  16945. }
  16946. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16947. }
  16948. else {
  16949. this._target[this.targetPropertyPath[0]] = currentValue;
  16950. }
  16951. if (this._target.markAsDirty) {
  16952. this._target.markAsDirty(this.targetProperty);
  16953. }
  16954. if (!returnValue) {
  16955. this._stopped = true;
  16956. }
  16957. return returnValue;
  16958. };
  16959. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16960. get: function () {
  16961. return Animation._ANIMATIONTYPE_FLOAT;
  16962. },
  16963. enumerable: true,
  16964. configurable: true
  16965. });
  16966. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16967. get: function () {
  16968. return Animation._ANIMATIONTYPE_VECTOR3;
  16969. },
  16970. enumerable: true,
  16971. configurable: true
  16972. });
  16973. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16974. get: function () {
  16975. return Animation._ANIMATIONTYPE_VECTOR2;
  16976. },
  16977. enumerable: true,
  16978. configurable: true
  16979. });
  16980. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16981. get: function () {
  16982. return Animation._ANIMATIONTYPE_QUATERNION;
  16983. },
  16984. enumerable: true,
  16985. configurable: true
  16986. });
  16987. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16988. get: function () {
  16989. return Animation._ANIMATIONTYPE_MATRIX;
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16995. get: function () {
  16996. return Animation._ANIMATIONTYPE_COLOR3;
  16997. },
  16998. enumerable: true,
  16999. configurable: true
  17000. });
  17001. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  17002. get: function () {
  17003. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  17004. },
  17005. enumerable: true,
  17006. configurable: true
  17007. });
  17008. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  17009. get: function () {
  17010. return Animation._ANIMATIONLOOPMODE_CYCLE;
  17011. },
  17012. enumerable: true,
  17013. configurable: true
  17014. });
  17015. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  17016. get: function () {
  17017. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  17018. },
  17019. enumerable: true,
  17020. configurable: true
  17021. });
  17022. // Statics
  17023. Animation._ANIMATIONTYPE_FLOAT = 0;
  17024. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  17025. Animation._ANIMATIONTYPE_QUATERNION = 2;
  17026. Animation._ANIMATIONTYPE_MATRIX = 3;
  17027. Animation._ANIMATIONTYPE_COLOR3 = 4;
  17028. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  17029. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  17030. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  17031. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  17032. return Animation;
  17033. })();
  17034. BABYLON.Animation = Animation;
  17035. })(BABYLON || (BABYLON = {}));
  17036. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  17037. (function (BABYLON) {
  17038. var Animatable = (function () {
  17039. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  17040. if (fromFrame === void 0) { fromFrame = 0; }
  17041. if (toFrame === void 0) { toFrame = 100; }
  17042. if (loopAnimation === void 0) { loopAnimation = false; }
  17043. if (speedRatio === void 0) { speedRatio = 1.0; }
  17044. this.target = target;
  17045. this.fromFrame = fromFrame;
  17046. this.toFrame = toFrame;
  17047. this.loopAnimation = loopAnimation;
  17048. this.speedRatio = speedRatio;
  17049. this.onAnimationEnd = onAnimationEnd;
  17050. this._animations = new Array();
  17051. this._paused = false;
  17052. this.animationStarted = false;
  17053. if (animations) {
  17054. this.appendAnimations(target, animations);
  17055. }
  17056. this._scene = scene;
  17057. scene._activeAnimatables.push(this);
  17058. }
  17059. // Methods
  17060. Animatable.prototype.appendAnimations = function (target, animations) {
  17061. for (var index = 0; index < animations.length; index++) {
  17062. var animation = animations[index];
  17063. animation._target = target;
  17064. this._animations.push(animation);
  17065. }
  17066. };
  17067. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  17068. var animations = this._animations;
  17069. for (var index = 0; index < animations.length; index++) {
  17070. if (animations[index].targetProperty === property) {
  17071. return animations[index];
  17072. }
  17073. }
  17074. return null;
  17075. };
  17076. Animatable.prototype.pause = function () {
  17077. if (this._paused) {
  17078. return;
  17079. }
  17080. this._paused = true;
  17081. };
  17082. Animatable.prototype.restart = function () {
  17083. this._paused = false;
  17084. };
  17085. Animatable.prototype.stop = function () {
  17086. var index = this._scene._activeAnimatables.indexOf(this);
  17087. if (index > -1) {
  17088. this._scene._activeAnimatables.splice(index, 1);
  17089. }
  17090. if (this.onAnimationEnd) {
  17091. this.onAnimationEnd();
  17092. }
  17093. };
  17094. Animatable.prototype._animate = function (delay) {
  17095. if (this._paused) {
  17096. if (!this._pausedDelay) {
  17097. this._pausedDelay = delay;
  17098. }
  17099. return true;
  17100. }
  17101. if (!this._localDelayOffset) {
  17102. this._localDelayOffset = delay;
  17103. }
  17104. else if (this._pausedDelay) {
  17105. this._localDelayOffset += delay - this._pausedDelay;
  17106. this._pausedDelay = null;
  17107. }
  17108. // Animating
  17109. var running = false;
  17110. var animations = this._animations;
  17111. for (var index = 0; index < animations.length; index++) {
  17112. var animation = animations[index];
  17113. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  17114. running = running || isRunning;
  17115. }
  17116. if (!running) {
  17117. // Remove from active animatables
  17118. index = this._scene._activeAnimatables.indexOf(this);
  17119. this._scene._activeAnimatables.splice(index, 1);
  17120. }
  17121. if (!running && this.onAnimationEnd) {
  17122. this.onAnimationEnd();
  17123. }
  17124. return running;
  17125. };
  17126. return Animatable;
  17127. })();
  17128. BABYLON.Animatable = Animatable;
  17129. })(BABYLON || (BABYLON = {}));
  17130. //# sourceMappingURL=babylon.animatable.js.map
  17131. var BABYLON;
  17132. (function (BABYLON) {
  17133. var EasingFunction = (function () {
  17134. function EasingFunction() {
  17135. // Properties
  17136. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  17137. }
  17138. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  17139. get: function () {
  17140. return EasingFunction._EASINGMODE_EASEIN;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  17146. get: function () {
  17147. return EasingFunction._EASINGMODE_EASEOUT;
  17148. },
  17149. enumerable: true,
  17150. configurable: true
  17151. });
  17152. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  17153. get: function () {
  17154. return EasingFunction._EASINGMODE_EASEINOUT;
  17155. },
  17156. enumerable: true,
  17157. configurable: true
  17158. });
  17159. EasingFunction.prototype.setEasingMode = function (easingMode) {
  17160. var n = Math.min(Math.max(easingMode, 0), 2);
  17161. this._easingMode = n;
  17162. };
  17163. EasingFunction.prototype.getEasingMode = function () {
  17164. return this._easingMode;
  17165. };
  17166. EasingFunction.prototype.easeInCore = function (gradient) {
  17167. throw new Error('You must implement this method');
  17168. };
  17169. EasingFunction.prototype.ease = function (gradient) {
  17170. switch (this._easingMode) {
  17171. case EasingFunction.EASINGMODE_EASEIN:
  17172. return this.easeInCore(gradient);
  17173. case EasingFunction.EASINGMODE_EASEOUT:
  17174. return (1 - this.easeInCore(1 - gradient));
  17175. }
  17176. if (gradient >= 0.5) {
  17177. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  17178. }
  17179. return (this.easeInCore(gradient * 2) * 0.5);
  17180. };
  17181. //Statics
  17182. EasingFunction._EASINGMODE_EASEIN = 0;
  17183. EasingFunction._EASINGMODE_EASEOUT = 1;
  17184. EasingFunction._EASINGMODE_EASEINOUT = 2;
  17185. return EasingFunction;
  17186. })();
  17187. BABYLON.EasingFunction = EasingFunction;
  17188. var CircleEase = (function (_super) {
  17189. __extends(CircleEase, _super);
  17190. function CircleEase() {
  17191. _super.apply(this, arguments);
  17192. }
  17193. CircleEase.prototype.easeInCore = function (gradient) {
  17194. gradient = Math.max(0, Math.min(1, gradient));
  17195. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  17196. };
  17197. return CircleEase;
  17198. })(EasingFunction);
  17199. BABYLON.CircleEase = CircleEase;
  17200. var BackEase = (function (_super) {
  17201. __extends(BackEase, _super);
  17202. function BackEase(amplitude) {
  17203. if (amplitude === void 0) { amplitude = 1; }
  17204. _super.call(this);
  17205. this.amplitude = amplitude;
  17206. }
  17207. BackEase.prototype.easeInCore = function (gradient) {
  17208. var num = Math.max(0, this.amplitude);
  17209. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  17210. };
  17211. return BackEase;
  17212. })(EasingFunction);
  17213. BABYLON.BackEase = BackEase;
  17214. var BounceEase = (function (_super) {
  17215. __extends(BounceEase, _super);
  17216. function BounceEase(bounces, bounciness) {
  17217. if (bounces === void 0) { bounces = 3; }
  17218. if (bounciness === void 0) { bounciness = 2; }
  17219. _super.call(this);
  17220. this.bounces = bounces;
  17221. this.bounciness = bounciness;
  17222. }
  17223. BounceEase.prototype.easeInCore = function (gradient) {
  17224. var y = Math.max(0.0, this.bounces);
  17225. var bounciness = this.bounciness;
  17226. if (bounciness <= 1.0) {
  17227. bounciness = 1.001;
  17228. }
  17229. var num9 = Math.pow(bounciness, y);
  17230. var num5 = 1.0 - bounciness;
  17231. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  17232. var num15 = gradient * num4;
  17233. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  17234. var num3 = Math.floor(num65);
  17235. var num13 = num3 + 1.0;
  17236. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  17237. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  17238. var num7 = (num8 + num12) * 0.5;
  17239. var num6 = gradient - num7;
  17240. var num2 = num7 - num8;
  17241. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17242. };
  17243. return BounceEase;
  17244. })(EasingFunction);
  17245. BABYLON.BounceEase = BounceEase;
  17246. var CubicEase = (function (_super) {
  17247. __extends(CubicEase, _super);
  17248. function CubicEase() {
  17249. _super.apply(this, arguments);
  17250. }
  17251. CubicEase.prototype.easeInCore = function (gradient) {
  17252. return (gradient * gradient * gradient);
  17253. };
  17254. return CubicEase;
  17255. })(EasingFunction);
  17256. BABYLON.CubicEase = CubicEase;
  17257. var ElasticEase = (function (_super) {
  17258. __extends(ElasticEase, _super);
  17259. function ElasticEase(oscillations, springiness) {
  17260. if (oscillations === void 0) { oscillations = 3; }
  17261. if (springiness === void 0) { springiness = 3; }
  17262. _super.call(this);
  17263. this.oscillations = oscillations;
  17264. this.springiness = springiness;
  17265. }
  17266. ElasticEase.prototype.easeInCore = function (gradient) {
  17267. var num2;
  17268. var num3 = Math.max(0.0, this.oscillations);
  17269. var num = Math.max(0.0, this.springiness);
  17270. if (num == 0) {
  17271. num2 = gradient;
  17272. }
  17273. else {
  17274. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17275. }
  17276. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17277. };
  17278. return ElasticEase;
  17279. })(EasingFunction);
  17280. BABYLON.ElasticEase = ElasticEase;
  17281. var ExponentialEase = (function (_super) {
  17282. __extends(ExponentialEase, _super);
  17283. function ExponentialEase(exponent) {
  17284. if (exponent === void 0) { exponent = 2; }
  17285. _super.call(this);
  17286. this.exponent = exponent;
  17287. }
  17288. ExponentialEase.prototype.easeInCore = function (gradient) {
  17289. if (this.exponent <= 0) {
  17290. return gradient;
  17291. }
  17292. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17293. };
  17294. return ExponentialEase;
  17295. })(EasingFunction);
  17296. BABYLON.ExponentialEase = ExponentialEase;
  17297. var PowerEase = (function (_super) {
  17298. __extends(PowerEase, _super);
  17299. function PowerEase(power) {
  17300. if (power === void 0) { power = 2; }
  17301. _super.call(this);
  17302. this.power = power;
  17303. }
  17304. PowerEase.prototype.easeInCore = function (gradient) {
  17305. var y = Math.max(0.0, this.power);
  17306. return Math.pow(gradient, y);
  17307. };
  17308. return PowerEase;
  17309. })(EasingFunction);
  17310. BABYLON.PowerEase = PowerEase;
  17311. var QuadraticEase = (function (_super) {
  17312. __extends(QuadraticEase, _super);
  17313. function QuadraticEase() {
  17314. _super.apply(this, arguments);
  17315. }
  17316. QuadraticEase.prototype.easeInCore = function (gradient) {
  17317. return (gradient * gradient);
  17318. };
  17319. return QuadraticEase;
  17320. })(EasingFunction);
  17321. BABYLON.QuadraticEase = QuadraticEase;
  17322. var QuarticEase = (function (_super) {
  17323. __extends(QuarticEase, _super);
  17324. function QuarticEase() {
  17325. _super.apply(this, arguments);
  17326. }
  17327. QuarticEase.prototype.easeInCore = function (gradient) {
  17328. return (gradient * gradient * gradient * gradient);
  17329. };
  17330. return QuarticEase;
  17331. })(EasingFunction);
  17332. BABYLON.QuarticEase = QuarticEase;
  17333. var QuinticEase = (function (_super) {
  17334. __extends(QuinticEase, _super);
  17335. function QuinticEase() {
  17336. _super.apply(this, arguments);
  17337. }
  17338. QuinticEase.prototype.easeInCore = function (gradient) {
  17339. return (gradient * gradient * gradient * gradient * gradient);
  17340. };
  17341. return QuinticEase;
  17342. })(EasingFunction);
  17343. BABYLON.QuinticEase = QuinticEase;
  17344. var SineEase = (function (_super) {
  17345. __extends(SineEase, _super);
  17346. function SineEase() {
  17347. _super.apply(this, arguments);
  17348. }
  17349. SineEase.prototype.easeInCore = function (gradient) {
  17350. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17351. };
  17352. return SineEase;
  17353. })(EasingFunction);
  17354. BABYLON.SineEase = SineEase;
  17355. var BezierCurveEase = (function (_super) {
  17356. __extends(BezierCurveEase, _super);
  17357. function BezierCurveEase(x1, y1, x2, y2) {
  17358. if (x1 === void 0) { x1 = 0; }
  17359. if (y1 === void 0) { y1 = 0; }
  17360. if (x2 === void 0) { x2 = 1; }
  17361. if (y2 === void 0) { y2 = 1; }
  17362. _super.call(this);
  17363. this.x1 = x1;
  17364. this.y1 = y1;
  17365. this.x2 = x2;
  17366. this.y2 = y2;
  17367. }
  17368. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17369. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17370. };
  17371. return BezierCurveEase;
  17372. })(EasingFunction);
  17373. BABYLON.BezierCurveEase = BezierCurveEase;
  17374. })(BABYLON || (BABYLON = {}));
  17375. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17376. (function (BABYLON) {
  17377. var Octree = (function () {
  17378. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17379. if (maxDepth === void 0) { maxDepth = 2; }
  17380. this.maxDepth = maxDepth;
  17381. this.dynamicContent = new Array();
  17382. this._maxBlockCapacity = maxBlockCapacity || 64;
  17383. this._selectionContent = new BABYLON.SmartArray(1024);
  17384. this._creationFunc = creationFunc;
  17385. }
  17386. // Methods
  17387. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17388. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17389. };
  17390. Octree.prototype.addMesh = function (entry) {
  17391. for (var index = 0; index < this.blocks.length; index++) {
  17392. var block = this.blocks[index];
  17393. block.addEntry(entry);
  17394. }
  17395. };
  17396. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17397. this._selectionContent.reset();
  17398. for (var index = 0; index < this.blocks.length; index++) {
  17399. var block = this.blocks[index];
  17400. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17401. }
  17402. if (allowDuplicate) {
  17403. this._selectionContent.concat(this.dynamicContent);
  17404. }
  17405. else {
  17406. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17407. }
  17408. return this._selectionContent;
  17409. };
  17410. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17411. this._selectionContent.reset();
  17412. for (var index = 0; index < this.blocks.length; index++) {
  17413. var block = this.blocks[index];
  17414. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17415. }
  17416. if (allowDuplicate) {
  17417. this._selectionContent.concat(this.dynamicContent);
  17418. }
  17419. else {
  17420. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17421. }
  17422. return this._selectionContent;
  17423. };
  17424. Octree.prototype.intersectsRay = function (ray) {
  17425. this._selectionContent.reset();
  17426. for (var index = 0; index < this.blocks.length; index++) {
  17427. var block = this.blocks[index];
  17428. block.intersectsRay(ray, this._selectionContent);
  17429. }
  17430. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17431. return this._selectionContent;
  17432. };
  17433. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17434. target.blocks = new Array();
  17435. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17436. for (var x = 0; x < 2; x++) {
  17437. for (var y = 0; y < 2; y++) {
  17438. for (var z = 0; z < 2; z++) {
  17439. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17440. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17441. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17442. block.addEntries(entries);
  17443. target.blocks.push(block);
  17444. }
  17445. }
  17446. }
  17447. };
  17448. Octree.CreationFuncForMeshes = function (entry, block) {
  17449. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17450. block.entries.push(entry);
  17451. }
  17452. };
  17453. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17454. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17455. block.entries.push(entry);
  17456. }
  17457. };
  17458. return Octree;
  17459. })();
  17460. BABYLON.Octree = Octree;
  17461. })(BABYLON || (BABYLON = {}));
  17462. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17463. (function (BABYLON) {
  17464. var OctreeBlock = (function () {
  17465. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17466. this.entries = new Array();
  17467. this._boundingVectors = new Array();
  17468. this._capacity = capacity;
  17469. this._depth = depth;
  17470. this._maxDepth = maxDepth;
  17471. this._creationFunc = creationFunc;
  17472. this._minPoint = minPoint;
  17473. this._maxPoint = maxPoint;
  17474. this._boundingVectors.push(minPoint.clone());
  17475. this._boundingVectors.push(maxPoint.clone());
  17476. this._boundingVectors.push(minPoint.clone());
  17477. this._boundingVectors[2].x = maxPoint.x;
  17478. this._boundingVectors.push(minPoint.clone());
  17479. this._boundingVectors[3].y = maxPoint.y;
  17480. this._boundingVectors.push(minPoint.clone());
  17481. this._boundingVectors[4].z = maxPoint.z;
  17482. this._boundingVectors.push(maxPoint.clone());
  17483. this._boundingVectors[5].z = minPoint.z;
  17484. this._boundingVectors.push(maxPoint.clone());
  17485. this._boundingVectors[6].x = minPoint.x;
  17486. this._boundingVectors.push(maxPoint.clone());
  17487. this._boundingVectors[7].y = minPoint.y;
  17488. }
  17489. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17490. // Property
  17491. get: function () {
  17492. return this._capacity;
  17493. },
  17494. enumerable: true,
  17495. configurable: true
  17496. });
  17497. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17498. get: function () {
  17499. return this._minPoint;
  17500. },
  17501. enumerable: true,
  17502. configurable: true
  17503. });
  17504. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17505. get: function () {
  17506. return this._maxPoint;
  17507. },
  17508. enumerable: true,
  17509. configurable: true
  17510. });
  17511. // Methods
  17512. OctreeBlock.prototype.addEntry = function (entry) {
  17513. if (this.blocks) {
  17514. for (var index = 0; index < this.blocks.length; index++) {
  17515. var block = this.blocks[index];
  17516. block.addEntry(entry);
  17517. }
  17518. return;
  17519. }
  17520. this._creationFunc(entry, this);
  17521. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17522. this.createInnerBlocks();
  17523. }
  17524. };
  17525. OctreeBlock.prototype.addEntries = function (entries) {
  17526. for (var index = 0; index < entries.length; index++) {
  17527. var mesh = entries[index];
  17528. this.addEntry(mesh);
  17529. }
  17530. };
  17531. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17532. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17533. if (this.blocks) {
  17534. for (var index = 0; index < this.blocks.length; index++) {
  17535. var block = this.blocks[index];
  17536. block.select(frustumPlanes, selection, allowDuplicate);
  17537. }
  17538. return;
  17539. }
  17540. if (allowDuplicate) {
  17541. selection.concat(this.entries);
  17542. }
  17543. else {
  17544. selection.concatWithNoDuplicate(this.entries);
  17545. }
  17546. }
  17547. };
  17548. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17549. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17550. if (this.blocks) {
  17551. for (var index = 0; index < this.blocks.length; index++) {
  17552. var block = this.blocks[index];
  17553. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17554. }
  17555. return;
  17556. }
  17557. if (allowDuplicate) {
  17558. selection.concat(this.entries);
  17559. }
  17560. else {
  17561. selection.concatWithNoDuplicate(this.entries);
  17562. }
  17563. }
  17564. };
  17565. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17566. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17567. if (this.blocks) {
  17568. for (var index = 0; index < this.blocks.length; index++) {
  17569. var block = this.blocks[index];
  17570. block.intersectsRay(ray, selection);
  17571. }
  17572. return;
  17573. }
  17574. selection.concatWithNoDuplicate(this.entries);
  17575. }
  17576. };
  17577. OctreeBlock.prototype.createInnerBlocks = function () {
  17578. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17579. };
  17580. return OctreeBlock;
  17581. })();
  17582. BABYLON.OctreeBlock = OctreeBlock;
  17583. })(BABYLON || (BABYLON = {}));
  17584. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17585. (function (BABYLON) {
  17586. var Bone = (function () {
  17587. function Bone(name, skeleton, parentBone, matrix) {
  17588. this.name = name;
  17589. this.children = new Array();
  17590. this.animations = new Array();
  17591. this._worldTransform = new BABYLON.Matrix();
  17592. this._absoluteTransform = new BABYLON.Matrix();
  17593. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17594. this._skeleton = skeleton;
  17595. this._matrix = matrix;
  17596. this._baseMatrix = matrix;
  17597. skeleton.bones.push(this);
  17598. if (parentBone) {
  17599. this._parent = parentBone;
  17600. parentBone.children.push(this);
  17601. }
  17602. else {
  17603. this._parent = null;
  17604. }
  17605. this._updateDifferenceMatrix();
  17606. }
  17607. // Members
  17608. Bone.prototype.getParent = function () {
  17609. return this._parent;
  17610. };
  17611. Bone.prototype.getLocalMatrix = function () {
  17612. return this._matrix;
  17613. };
  17614. Bone.prototype.getBaseMatrix = function () {
  17615. return this._baseMatrix;
  17616. };
  17617. Bone.prototype.getWorldMatrix = function () {
  17618. return this._worldTransform;
  17619. };
  17620. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17621. return this._invertedAbsoluteTransform;
  17622. };
  17623. Bone.prototype.getAbsoluteMatrix = function () {
  17624. var matrix = this._matrix.clone();
  17625. var parent = this._parent;
  17626. while (parent) {
  17627. matrix = matrix.multiply(parent.getLocalMatrix());
  17628. parent = parent.getParent();
  17629. }
  17630. return matrix;
  17631. };
  17632. // Methods
  17633. Bone.prototype.updateMatrix = function (matrix) {
  17634. this._matrix = matrix;
  17635. this._skeleton._markAsDirty();
  17636. this._updateDifferenceMatrix();
  17637. };
  17638. Bone.prototype._updateDifferenceMatrix = function () {
  17639. if (this._parent) {
  17640. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17641. }
  17642. else {
  17643. this._absoluteTransform.copyFrom(this._matrix);
  17644. }
  17645. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17646. for (var index = 0; index < this.children.length; index++) {
  17647. this.children[index]._updateDifferenceMatrix();
  17648. }
  17649. };
  17650. Bone.prototype.markAsDirty = function () {
  17651. this._skeleton._markAsDirty();
  17652. };
  17653. return Bone;
  17654. })();
  17655. BABYLON.Bone = Bone;
  17656. })(BABYLON || (BABYLON = {}));
  17657. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17658. (function (BABYLON) {
  17659. var Skeleton = (function () {
  17660. function Skeleton(name, id, scene) {
  17661. this.name = name;
  17662. this.id = id;
  17663. this.bones = new Array();
  17664. this._isDirty = true;
  17665. this._identity = BABYLON.Matrix.Identity();
  17666. this.bones = [];
  17667. this._scene = scene;
  17668. scene.skeletons.push(this);
  17669. this.prepare();
  17670. //make sure it will recalculate the matrix next time prepare is called.
  17671. this._isDirty = true;
  17672. }
  17673. // Members
  17674. Skeleton.prototype.getTransformMatrices = function () {
  17675. return this._transformMatrices;
  17676. };
  17677. // Methods
  17678. Skeleton.prototype._markAsDirty = function () {
  17679. this._isDirty = true;
  17680. };
  17681. Skeleton.prototype.prepare = function () {
  17682. if (!this._isDirty) {
  17683. return;
  17684. }
  17685. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17686. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17687. }
  17688. for (var index = 0; index < this.bones.length; index++) {
  17689. var bone = this.bones[index];
  17690. var parentBone = bone.getParent();
  17691. if (parentBone) {
  17692. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17693. }
  17694. else {
  17695. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17696. }
  17697. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17698. }
  17699. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17700. this._isDirty = false;
  17701. this._scene._activeBones += this.bones.length;
  17702. };
  17703. Skeleton.prototype.getAnimatables = function () {
  17704. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17705. this._animatables = [];
  17706. for (var index = 0; index < this.bones.length; index++) {
  17707. this._animatables.push(this.bones[index]);
  17708. }
  17709. }
  17710. return this._animatables;
  17711. };
  17712. Skeleton.prototype.clone = function (name, id) {
  17713. var result = new Skeleton(name, id || name, this._scene);
  17714. for (var index = 0; index < this.bones.length; index++) {
  17715. var source = this.bones[index];
  17716. var parentBone = null;
  17717. if (source.getParent()) {
  17718. var parentIndex = this.bones.indexOf(source.getParent());
  17719. parentBone = result.bones[parentIndex];
  17720. }
  17721. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17722. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17723. }
  17724. return result;
  17725. };
  17726. return Skeleton;
  17727. })();
  17728. BABYLON.Skeleton = Skeleton;
  17729. })(BABYLON || (BABYLON = {}));
  17730. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17731. (function (BABYLON) {
  17732. var PostProcess = (function () {
  17733. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17735. this.name = name;
  17736. this.width = -1;
  17737. this.height = -1;
  17738. this._reusable = false;
  17739. this._textures = new BABYLON.SmartArray(2);
  17740. this._currentRenderTextureInd = 0;
  17741. if (camera != null) {
  17742. this._camera = camera;
  17743. this._scene = camera.getScene();
  17744. camera.attachPostProcess(this);
  17745. this._engine = this._scene.getEngine();
  17746. }
  17747. else {
  17748. this._engine = engine;
  17749. }
  17750. this._renderRatio = ratio;
  17751. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17752. this._reusable = reusable || false;
  17753. samplers = samplers || [];
  17754. samplers.push("textureSampler");
  17755. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17756. }
  17757. PostProcess.prototype.isReusable = function () {
  17758. return this._reusable;
  17759. };
  17760. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17761. camera = camera || this._camera;
  17762. var scene = camera.getScene();
  17763. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17764. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17765. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17766. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17767. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17768. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17769. if (this._textures.length > 0) {
  17770. for (var i = 0; i < this._textures.length; i++) {
  17771. this._engine._releaseTexture(this._textures.data[i]);
  17772. }
  17773. this._textures.reset();
  17774. }
  17775. this.width = desiredWidth;
  17776. this.height = desiredHeight;
  17777. 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 }));
  17778. if (this._reusable) {
  17779. 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 }));
  17780. }
  17781. if (this.onSizeChanged) {
  17782. this.onSizeChanged();
  17783. }
  17784. }
  17785. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17786. if (this.onActivate) {
  17787. this.onActivate(camera);
  17788. }
  17789. // Clear
  17790. if (this.clearColor) {
  17791. this._engine.clear(this.clearColor, true, true);
  17792. }
  17793. else {
  17794. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17795. }
  17796. if (this._reusable) {
  17797. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17798. }
  17799. };
  17800. PostProcess.prototype.apply = function () {
  17801. // Check
  17802. if (!this._effect.isReady())
  17803. return null;
  17804. // States
  17805. this._engine.enableEffect(this._effect);
  17806. this._engine.setState(false);
  17807. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17808. this._engine.setDepthBuffer(false);
  17809. this._engine.setDepthWrite(false);
  17810. // Texture
  17811. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17812. // Parameters
  17813. if (this.onApply) {
  17814. this.onApply(this._effect);
  17815. }
  17816. return this._effect;
  17817. };
  17818. PostProcess.prototype.dispose = function (camera) {
  17819. camera = camera || this._camera;
  17820. if (this._textures.length > 0) {
  17821. for (var i = 0; i < this._textures.length; i++) {
  17822. this._engine._releaseTexture(this._textures.data[i]);
  17823. }
  17824. this._textures.reset();
  17825. }
  17826. if (!camera) {
  17827. return;
  17828. }
  17829. camera.detachPostProcess(this);
  17830. var index = camera._postProcesses.indexOf(this);
  17831. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17832. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17833. }
  17834. };
  17835. return PostProcess;
  17836. })();
  17837. BABYLON.PostProcess = PostProcess;
  17838. })(BABYLON || (BABYLON = {}));
  17839. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17840. (function (BABYLON) {
  17841. var PostProcessManager = (function () {
  17842. function PostProcessManager(scene) {
  17843. this._vertexDeclaration = [2];
  17844. this._vertexStrideSize = 2 * 4;
  17845. this._scene = scene;
  17846. }
  17847. PostProcessManager.prototype._prepareBuffers = function () {
  17848. if (this._vertexBuffer) {
  17849. return;
  17850. }
  17851. // VBO
  17852. var vertices = [];
  17853. vertices.push(1, 1);
  17854. vertices.push(-1, 1);
  17855. vertices.push(-1, -1);
  17856. vertices.push(1, -1);
  17857. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17858. // Indices
  17859. var indices = [];
  17860. indices.push(0);
  17861. indices.push(1);
  17862. indices.push(2);
  17863. indices.push(0);
  17864. indices.push(2);
  17865. indices.push(3);
  17866. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17867. };
  17868. // Methods
  17869. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17870. var postProcesses = this._scene.activeCamera._postProcesses;
  17871. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17872. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17873. return false;
  17874. }
  17875. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17876. return true;
  17877. };
  17878. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17879. var engine = this._scene.getEngine();
  17880. for (var index = 0; index < postProcesses.length; index++) {
  17881. if (index < postProcesses.length - 1) {
  17882. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17883. }
  17884. else {
  17885. if (targetTexture) {
  17886. engine.bindFramebuffer(targetTexture);
  17887. }
  17888. else {
  17889. engine.restoreDefaultFramebuffer();
  17890. }
  17891. }
  17892. var pp = postProcesses[index];
  17893. var effect = pp.apply();
  17894. if (effect) {
  17895. if (pp.onBeforeRender) {
  17896. pp.onBeforeRender(effect);
  17897. }
  17898. // VBOs
  17899. this._prepareBuffers();
  17900. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17901. // Draw order
  17902. engine.draw(true, 0, 6);
  17903. }
  17904. }
  17905. // Restore depth buffer
  17906. engine.setDepthBuffer(true);
  17907. engine.setDepthWrite(true);
  17908. };
  17909. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17910. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17911. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17912. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17913. return;
  17914. }
  17915. var engine = this._scene.getEngine();
  17916. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17917. if (index < postProcessesTakenIndices.length - 1) {
  17918. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17919. }
  17920. else {
  17921. if (targetTexture) {
  17922. engine.bindFramebuffer(targetTexture);
  17923. }
  17924. else {
  17925. engine.restoreDefaultFramebuffer();
  17926. }
  17927. }
  17928. if (doNotPresent) {
  17929. break;
  17930. }
  17931. var pp = postProcesses[postProcessesTakenIndices[index]];
  17932. var effect = pp.apply();
  17933. if (effect) {
  17934. if (pp.onBeforeRender) {
  17935. pp.onBeforeRender(effect);
  17936. }
  17937. // VBOs
  17938. this._prepareBuffers();
  17939. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17940. // Draw order
  17941. engine.draw(true, 0, 6);
  17942. }
  17943. }
  17944. // Restore depth buffer
  17945. engine.setDepthBuffer(true);
  17946. engine.setDepthWrite(true);
  17947. };
  17948. PostProcessManager.prototype.dispose = function () {
  17949. if (this._vertexBuffer) {
  17950. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17951. this._vertexBuffer = null;
  17952. }
  17953. if (this._indexBuffer) {
  17954. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17955. this._indexBuffer = null;
  17956. }
  17957. };
  17958. return PostProcessManager;
  17959. })();
  17960. BABYLON.PostProcessManager = PostProcessManager;
  17961. })(BABYLON || (BABYLON = {}));
  17962. //# sourceMappingURL=babylon.postProcessManager.js.map
  17963. var BABYLON;
  17964. (function (BABYLON) {
  17965. var PassPostProcess = (function (_super) {
  17966. __extends(PassPostProcess, _super);
  17967. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17968. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17969. }
  17970. return PassPostProcess;
  17971. })(BABYLON.PostProcess);
  17972. BABYLON.PassPostProcess = PassPostProcess;
  17973. })(BABYLON || (BABYLON = {}));
  17974. //# sourceMappingURL=babylon.passPostProcess.js.map
  17975. var BABYLON;
  17976. (function (BABYLON) {
  17977. var BlurPostProcess = (function (_super) {
  17978. __extends(BlurPostProcess, _super);
  17979. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17980. var _this = this;
  17981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17982. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17983. this.direction = direction;
  17984. this.blurWidth = blurWidth;
  17985. this.onApply = function (effect) {
  17986. effect.setFloat2("screenSize", _this.width, _this.height);
  17987. effect.setVector2("direction", _this.direction);
  17988. effect.setFloat("blurWidth", _this.blurWidth);
  17989. };
  17990. }
  17991. return BlurPostProcess;
  17992. })(BABYLON.PostProcess);
  17993. BABYLON.BlurPostProcess = BlurPostProcess;
  17994. })(BABYLON || (BABYLON = {}));
  17995. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17996. var BABYLON;
  17997. (function (BABYLON) {
  17998. var FilterPostProcess = (function (_super) {
  17999. __extends(FilterPostProcess, _super);
  18000. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  18001. var _this = this;
  18002. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  18003. this.kernelMatrix = kernelMatrix;
  18004. this.onApply = function (effect) {
  18005. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  18006. };
  18007. }
  18008. return FilterPostProcess;
  18009. })(BABYLON.PostProcess);
  18010. BABYLON.FilterPostProcess = FilterPostProcess;
  18011. })(BABYLON || (BABYLON = {}));
  18012. //# sourceMappingURL=babylon.filterPostProcess.js.map
  18013. var BABYLON;
  18014. (function (BABYLON) {
  18015. var RefractionPostProcess = (function (_super) {
  18016. __extends(RefractionPostProcess, _super);
  18017. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  18018. var _this = this;
  18019. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  18020. this.color = color;
  18021. this.depth = depth;
  18022. this.colorLevel = colorLevel;
  18023. this.onActivate = function (cam) {
  18024. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  18025. };
  18026. this.onApply = function (effect) {
  18027. effect.setColor3("baseColor", _this.color);
  18028. effect.setFloat("depth", _this.depth);
  18029. effect.setFloat("colorLevel", _this.colorLevel);
  18030. effect.setTexture("refractionSampler", _this._refRexture);
  18031. };
  18032. }
  18033. // Methods
  18034. RefractionPostProcess.prototype.dispose = function (camera) {
  18035. if (this._refRexture) {
  18036. this._refRexture.dispose();
  18037. }
  18038. _super.prototype.dispose.call(this, camera);
  18039. };
  18040. return RefractionPostProcess;
  18041. })(BABYLON.PostProcess);
  18042. BABYLON.RefractionPostProcess = RefractionPostProcess;
  18043. })(BABYLON || (BABYLON = {}));
  18044. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  18045. var BABYLON;
  18046. (function (BABYLON) {
  18047. var BlackAndWhitePostProcess = (function (_super) {
  18048. __extends(BlackAndWhitePostProcess, _super);
  18049. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18050. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  18051. }
  18052. return BlackAndWhitePostProcess;
  18053. })(BABYLON.PostProcess);
  18054. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  18055. })(BABYLON || (BABYLON = {}));
  18056. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  18057. var BABYLON;
  18058. (function (BABYLON) {
  18059. var ConvolutionPostProcess = (function (_super) {
  18060. __extends(ConvolutionPostProcess, _super);
  18061. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  18062. var _this = this;
  18063. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  18064. this.kernel = kernel;
  18065. this.onApply = function (effect) {
  18066. effect.setFloat2("screenSize", _this.width, _this.height);
  18067. effect.setArray("kernel", _this.kernel);
  18068. };
  18069. }
  18070. // Statics
  18071. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  18072. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  18073. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  18074. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  18075. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  18076. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  18077. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  18078. return ConvolutionPostProcess;
  18079. })(BABYLON.PostProcess);
  18080. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  18081. })(BABYLON || (BABYLON = {}));
  18082. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  18083. var BABYLON;
  18084. (function (BABYLON) {
  18085. var FxaaPostProcess = (function (_super) {
  18086. __extends(FxaaPostProcess, _super);
  18087. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18088. var _this = this;
  18089. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  18090. this.onSizeChanged = function () {
  18091. _this.texelWidth = 1.0 / _this.width;
  18092. _this.texelHeight = 1.0 / _this.height;
  18093. };
  18094. this.onApply = function (effect) {
  18095. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  18096. };
  18097. }
  18098. return FxaaPostProcess;
  18099. })(BABYLON.PostProcess);
  18100. BABYLON.FxaaPostProcess = FxaaPostProcess;
  18101. })(BABYLON || (BABYLON = {}));
  18102. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  18103. (function (BABYLON) {
  18104. var LensFlare = (function () {
  18105. function LensFlare(size, position, color, imgUrl, system) {
  18106. this.size = size;
  18107. this.position = position;
  18108. this.dispose = function () {
  18109. if (this.texture) {
  18110. this.texture.dispose();
  18111. }
  18112. // Remove from scene
  18113. var index = this._system.lensFlares.indexOf(this);
  18114. this._system.lensFlares.splice(index, 1);
  18115. };
  18116. this.color = color || new BABYLON.Color3(1, 1, 1);
  18117. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  18118. this._system = system;
  18119. system.lensFlares.push(this);
  18120. }
  18121. return LensFlare;
  18122. })();
  18123. BABYLON.LensFlare = LensFlare;
  18124. })(BABYLON || (BABYLON = {}));
  18125. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  18126. (function (BABYLON) {
  18127. var LensFlareSystem = (function () {
  18128. function LensFlareSystem(name, emitter, scene) {
  18129. this.name = name;
  18130. this.lensFlares = new Array();
  18131. this.borderLimit = 300;
  18132. this._vertexDeclaration = [2];
  18133. this._vertexStrideSize = 2 * 4;
  18134. this._isEnabled = true;
  18135. this._scene = scene;
  18136. this._emitter = emitter;
  18137. scene.lensFlareSystems.push(this);
  18138. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  18139. // VBO
  18140. var vertices = [];
  18141. vertices.push(1, 1);
  18142. vertices.push(-1, 1);
  18143. vertices.push(-1, -1);
  18144. vertices.push(1, -1);
  18145. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18146. // Indices
  18147. var indices = [];
  18148. indices.push(0);
  18149. indices.push(1);
  18150. indices.push(2);
  18151. indices.push(0);
  18152. indices.push(2);
  18153. indices.push(3);
  18154. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18155. // Effects
  18156. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  18157. }
  18158. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  18159. get: function () {
  18160. return this._isEnabled;
  18161. },
  18162. set: function (value) {
  18163. this._isEnabled = value;
  18164. },
  18165. enumerable: true,
  18166. configurable: true
  18167. });
  18168. LensFlareSystem.prototype.getScene = function () {
  18169. return this._scene;
  18170. };
  18171. LensFlareSystem.prototype.getEmitter = function () {
  18172. return this._emitter;
  18173. };
  18174. LensFlareSystem.prototype.getEmitterPosition = function () {
  18175. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  18176. };
  18177. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  18178. var position = this.getEmitterPosition();
  18179. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  18180. this._positionX = position.x;
  18181. this._positionY = position.y;
  18182. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  18183. if (position.z > 0) {
  18184. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  18185. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  18186. return true;
  18187. }
  18188. }
  18189. return false;
  18190. };
  18191. LensFlareSystem.prototype._isVisible = function () {
  18192. if (!this._isEnabled) {
  18193. return false;
  18194. }
  18195. var emitterPosition = this.getEmitterPosition();
  18196. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  18197. var distance = direction.length();
  18198. direction.normalize();
  18199. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  18200. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  18201. return !pickInfo.hit || pickInfo.distance > distance;
  18202. };
  18203. LensFlareSystem.prototype.render = function () {
  18204. if (!this._effect.isReady())
  18205. return false;
  18206. var engine = this._scene.getEngine();
  18207. var viewport = this._scene.activeCamera.viewport;
  18208. var globalViewport = viewport.toGlobal(engine);
  18209. // Position
  18210. if (!this.computeEffectivePosition(globalViewport)) {
  18211. return false;
  18212. }
  18213. // Visibility
  18214. if (!this._isVisible()) {
  18215. return false;
  18216. }
  18217. // Intensity
  18218. var awayX;
  18219. var awayY;
  18220. if (this._positionX < this.borderLimit + globalViewport.x) {
  18221. awayX = this.borderLimit + globalViewport.x - this._positionX;
  18222. }
  18223. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  18224. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  18225. }
  18226. else {
  18227. awayX = 0;
  18228. }
  18229. if (this._positionY < this.borderLimit + globalViewport.y) {
  18230. awayY = this.borderLimit + globalViewport.y - this._positionY;
  18231. }
  18232. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  18233. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  18234. }
  18235. else {
  18236. awayY = 0;
  18237. }
  18238. var away = (awayX > awayY) ? awayX : awayY;
  18239. if (away > this.borderLimit) {
  18240. away = this.borderLimit;
  18241. }
  18242. var intensity = 1.0 - (away / this.borderLimit);
  18243. if (intensity < 0) {
  18244. return false;
  18245. }
  18246. if (intensity > 1.0) {
  18247. intensity = 1.0;
  18248. }
  18249. // Position
  18250. var centerX = globalViewport.x + globalViewport.width / 2;
  18251. var centerY = globalViewport.y + globalViewport.height / 2;
  18252. var distX = centerX - this._positionX;
  18253. var distY = centerY - this._positionY;
  18254. // Effects
  18255. engine.enableEffect(this._effect);
  18256. engine.setState(false);
  18257. engine.setDepthBuffer(false);
  18258. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18259. // VBOs
  18260. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18261. for (var index = 0; index < this.lensFlares.length; index++) {
  18262. var flare = this.lensFlares[index];
  18263. var x = centerX - (distX * flare.position);
  18264. var y = centerY - (distY * flare.position);
  18265. var cw = flare.size;
  18266. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18267. var cx = 2 * (x / globalViewport.width) - 1.0;
  18268. var cy = 1.0 - 2 * (y / globalViewport.height);
  18269. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18270. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18271. // Texture
  18272. this._effect.setTexture("textureSampler", flare.texture);
  18273. // Color
  18274. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18275. // Draw order
  18276. engine.draw(true, 0, 6);
  18277. }
  18278. engine.setDepthBuffer(true);
  18279. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18280. return true;
  18281. };
  18282. LensFlareSystem.prototype.dispose = function () {
  18283. if (this._vertexBuffer) {
  18284. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18285. this._vertexBuffer = null;
  18286. }
  18287. if (this._indexBuffer) {
  18288. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18289. this._indexBuffer = null;
  18290. }
  18291. while (this.lensFlares.length) {
  18292. this.lensFlares[0].dispose();
  18293. }
  18294. // Remove from scene
  18295. var index = this._scene.lensFlareSystems.indexOf(this);
  18296. this._scene.lensFlareSystems.splice(index, 1);
  18297. };
  18298. return LensFlareSystem;
  18299. })();
  18300. BABYLON.LensFlareSystem = LensFlareSystem;
  18301. })(BABYLON || (BABYLON = {}));
  18302. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18303. (function (BABYLON) {
  18304. var IntersectionInfo = (function () {
  18305. function IntersectionInfo(bu, bv, distance) {
  18306. this.bu = bu;
  18307. this.bv = bv;
  18308. this.distance = distance;
  18309. this.faceId = 0;
  18310. this.subMeshId = 0;
  18311. }
  18312. return IntersectionInfo;
  18313. })();
  18314. BABYLON.IntersectionInfo = IntersectionInfo;
  18315. var PickingInfo = (function () {
  18316. function PickingInfo() {
  18317. this.hit = false;
  18318. this.distance = 0;
  18319. this.pickedPoint = null;
  18320. this.pickedMesh = null;
  18321. this.bu = 0;
  18322. this.bv = 0;
  18323. this.faceId = -1;
  18324. this.subMeshId = 0;
  18325. }
  18326. // Methods
  18327. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18328. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18329. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18330. return null;
  18331. }
  18332. var indices = this.pickedMesh.getIndices();
  18333. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18334. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18335. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18336. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18337. normal0 = normal0.scale(this.bu);
  18338. normal1 = normal1.scale(this.bv);
  18339. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18340. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18341. if (useWorldCoordinates) {
  18342. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18343. }
  18344. return result;
  18345. };
  18346. PickingInfo.prototype.getTextureCoordinates = function () {
  18347. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18348. return null;
  18349. }
  18350. var indices = this.pickedMesh.getIndices();
  18351. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18352. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18353. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18354. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18355. uv0 = uv0.scale(this.bu);
  18356. uv1 = uv1.scale(this.bv);
  18357. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18358. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18359. };
  18360. return PickingInfo;
  18361. })();
  18362. BABYLON.PickingInfo = PickingInfo;
  18363. })(BABYLON || (BABYLON = {}));
  18364. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18365. (function (BABYLON) {
  18366. var FilesInput = (function () {
  18367. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18368. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18369. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18370. this._engine = p_engine;
  18371. this._canvas = p_canvas;
  18372. this._currentScene = p_scene;
  18373. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18374. this._progressCallback = p_progressCallback;
  18375. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18376. this._textureLoadingCallback = p_textureLoadingCallback;
  18377. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18378. }
  18379. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18380. var _this = this;
  18381. if (p_elementToMonitor) {
  18382. this._elementToMonitor = p_elementToMonitor;
  18383. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18384. _this.drag(e);
  18385. }, false);
  18386. this._elementToMonitor.addEventListener("dragover", function (e) {
  18387. _this.drag(e);
  18388. }, false);
  18389. this._elementToMonitor.addEventListener("drop", function (e) {
  18390. _this.drop(e);
  18391. }, false);
  18392. }
  18393. };
  18394. FilesInput.prototype.renderFunction = function () {
  18395. if (this._additionnalRenderLoopLogicCallback) {
  18396. this._additionnalRenderLoopLogicCallback();
  18397. }
  18398. if (this._currentScene) {
  18399. if (this._textureLoadingCallback) {
  18400. var remaining = this._currentScene.getWaitingItemsCount();
  18401. if (remaining > 0) {
  18402. this._textureLoadingCallback(remaining);
  18403. }
  18404. }
  18405. this._currentScene.render();
  18406. }
  18407. };
  18408. FilesInput.prototype.drag = function (e) {
  18409. e.stopPropagation();
  18410. e.preventDefault();
  18411. };
  18412. FilesInput.prototype.drop = function (eventDrop) {
  18413. eventDrop.stopPropagation();
  18414. eventDrop.preventDefault();
  18415. this.loadFiles(eventDrop);
  18416. };
  18417. FilesInput.prototype.loadFiles = function (event) {
  18418. if (this._startingProcessingFilesCallback)
  18419. this._startingProcessingFilesCallback();
  18420. // Handling data transfer via drag'n'drop
  18421. if (event && event.dataTransfer && event.dataTransfer.files) {
  18422. this._filesToLoad = event.dataTransfer.files;
  18423. }
  18424. // Handling files from input files
  18425. if (event && event.target && event.target.files) {
  18426. this._filesToLoad = event.target.files;
  18427. }
  18428. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18429. for (var i = 0; i < this._filesToLoad.length; i++) {
  18430. switch (this._filesToLoad[i].type) {
  18431. case "image/jpeg":
  18432. case "image/png":
  18433. case "image/bmp":
  18434. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18435. break;
  18436. case "image/targa":
  18437. case "image/vnd.ms-dds":
  18438. case "audio/wav":
  18439. case "audio/x-wav":
  18440. case "audio/mp3":
  18441. case "audio/mpeg":
  18442. case "audio/mpeg3":
  18443. case "audio/x-mpeg-3":
  18444. case "audio/ogg":
  18445. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18446. break;
  18447. default:
  18448. 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) {
  18449. this._sceneFileToLoad = this._filesToLoad[i];
  18450. }
  18451. break;
  18452. }
  18453. }
  18454. this.reload();
  18455. }
  18456. };
  18457. FilesInput.prototype.reload = function () {
  18458. var _this = this;
  18459. var that = this;
  18460. // If a ".babylon" file has been provided
  18461. if (this._sceneFileToLoad) {
  18462. if (this._currentScene) {
  18463. this._engine.stopRenderLoop();
  18464. this._currentScene.dispose();
  18465. }
  18466. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18467. that._currentScene = newScene;
  18468. // Wait for textures and shaders to be ready
  18469. that._currentScene.executeWhenReady(function () {
  18470. // Attach camera to canvas inputs
  18471. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18472. that._currentScene.createDefaultCameraOrLight();
  18473. }
  18474. that._currentScene.activeCamera.attachControl(that._canvas);
  18475. if (that._sceneLoadedCallback) {
  18476. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18477. }
  18478. that._engine.runRenderLoop(function () {
  18479. that.renderFunction();
  18480. });
  18481. });
  18482. }, function (progress) {
  18483. if (_this._progressCallback) {
  18484. _this._progressCallback(progress);
  18485. }
  18486. });
  18487. }
  18488. else {
  18489. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18490. }
  18491. };
  18492. FilesInput.FilesTextures = new Array();
  18493. FilesInput.FilesToLoad = new Array();
  18494. return FilesInput;
  18495. })();
  18496. BABYLON.FilesInput = FilesInput;
  18497. })(BABYLON || (BABYLON = {}));
  18498. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18499. (function (BABYLON) {
  18500. var OimoJSPlugin = (function () {
  18501. function OimoJSPlugin() {
  18502. this._registeredMeshes = [];
  18503. /**
  18504. * Update the body position according to the mesh position
  18505. * @param mesh
  18506. */
  18507. this.updateBodyPosition = function (mesh) {
  18508. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18509. var registeredMesh = this._registeredMeshes[index];
  18510. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18511. var body = registeredMesh.body.body;
  18512. mesh.computeWorldMatrix(true);
  18513. var center = mesh.getBoundingInfo().boundingBox.center;
  18514. body.setPosition(center.x, center.y, center.z);
  18515. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18516. return;
  18517. }
  18518. // Case where the parent has been updated
  18519. if (registeredMesh.mesh.parent === mesh) {
  18520. mesh.computeWorldMatrix(true);
  18521. registeredMesh.mesh.computeWorldMatrix(true);
  18522. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18523. var absoluteRotation = mesh.rotation;
  18524. body = registeredMesh.body.body;
  18525. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18526. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18527. return;
  18528. }
  18529. }
  18530. };
  18531. }
  18532. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18533. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18534. };
  18535. OimoJSPlugin.prototype.initialize = function (iterations) {
  18536. this._world = new OIMO.World();
  18537. this._world.clear();
  18538. };
  18539. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18540. this._world.gravity = gravity;
  18541. };
  18542. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18543. var body = null;
  18544. this.unregisterMesh(mesh);
  18545. mesh.computeWorldMatrix(true);
  18546. var initialRotation = null;
  18547. if (mesh.rotationQuaternion) {
  18548. initialRotation = mesh.rotationQuaternion.clone();
  18549. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18550. mesh.computeWorldMatrix(true);
  18551. }
  18552. var bbox = mesh.getBoundingInfo().boundingBox;
  18553. // The delta between the mesh position and the mesh bounding box center
  18554. var deltaPosition = mesh.position.subtract(bbox.center);
  18555. // Transform delta position with the rotation
  18556. if (initialRotation) {
  18557. var m = new BABYLON.Matrix();
  18558. initialRotation.toRotationMatrix(m);
  18559. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18560. }
  18561. switch (impostor) {
  18562. case BABYLON.PhysicsEngine.SphereImpostor:
  18563. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18564. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18565. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18566. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18567. body = new OIMO.Body({
  18568. type: 'sphere',
  18569. size: [size],
  18570. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18571. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18572. move: options.mass != 0,
  18573. config: [options.mass, options.friction, options.restitution],
  18574. world: this._world
  18575. });
  18576. break;
  18577. case BABYLON.PhysicsEngine.PlaneImpostor:
  18578. case BABYLON.PhysicsEngine.CylinderImpostor:
  18579. case BABYLON.PhysicsEngine.BoxImpostor:
  18580. var min = bbox.minimumWorld;
  18581. var max = bbox.maximumWorld;
  18582. var box = max.subtract(min);
  18583. var sizeX = this._checkWithEpsilon(box.x);
  18584. var sizeY = this._checkWithEpsilon(box.y);
  18585. var sizeZ = this._checkWithEpsilon(box.z);
  18586. body = new OIMO.Body({
  18587. type: 'box',
  18588. size: [sizeX, sizeY, sizeZ],
  18589. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18590. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18591. move: options.mass != 0,
  18592. config: [options.mass, options.friction, options.restitution],
  18593. world: this._world
  18594. });
  18595. break;
  18596. }
  18597. //If quaternion was set as the rotation of the object
  18598. if (initialRotation) {
  18599. //We have to access the rigid body's properties to set the quaternion.
  18600. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18601. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18602. //update the internal rotation matrix
  18603. body.body.syncShapes();
  18604. }
  18605. this._registeredMeshes.push({
  18606. mesh: mesh,
  18607. body: body,
  18608. delta: deltaPosition
  18609. });
  18610. return body;
  18611. };
  18612. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18613. var types = [], sizes = [], positions = [], rotations = [];
  18614. var initialMesh = parts[0].mesh;
  18615. for (var index = 0; index < parts.length; index++) {
  18616. var part = parts[index];
  18617. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18618. types.push(bodyParameters.type);
  18619. sizes.push.apply(sizes, bodyParameters.size);
  18620. positions.push.apply(positions, bodyParameters.pos);
  18621. rotations.push.apply(rotations, bodyParameters.rot);
  18622. }
  18623. var body = new OIMO.Body({
  18624. type: types,
  18625. size: sizes,
  18626. pos: positions,
  18627. rot: rotations,
  18628. move: options.mass != 0,
  18629. config: [options.mass, options.friction, options.restitution],
  18630. world: this._world
  18631. });
  18632. this._registeredMeshes.push({
  18633. mesh: initialMesh,
  18634. body: body
  18635. });
  18636. return body;
  18637. };
  18638. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18639. var bodyParameters = null;
  18640. var mesh = part.mesh;
  18641. // We need the bounding box/sphere info to compute the physics body
  18642. mesh.computeWorldMatrix();
  18643. switch (part.impostor) {
  18644. case BABYLON.PhysicsEngine.SphereImpostor:
  18645. var bbox = mesh.getBoundingInfo().boundingBox;
  18646. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18647. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18648. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18649. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18650. bodyParameters = {
  18651. type: 'sphere',
  18652. /* bug with oimo : sphere needs 3 sizes in this case */
  18653. size: [size, -1, -1],
  18654. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18655. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18656. };
  18657. break;
  18658. case BABYLON.PhysicsEngine.PlaneImpostor:
  18659. case BABYLON.PhysicsEngine.BoxImpostor:
  18660. bbox = mesh.getBoundingInfo().boundingBox;
  18661. var min = bbox.minimumWorld;
  18662. var max = bbox.maximumWorld;
  18663. var box = max.subtract(min);
  18664. var sizeX = this._checkWithEpsilon(box.x);
  18665. var sizeY = this._checkWithEpsilon(box.y);
  18666. var sizeZ = this._checkWithEpsilon(box.z);
  18667. var relativePosition = mesh.position;
  18668. bodyParameters = {
  18669. type: 'box',
  18670. size: [sizeX, sizeY, sizeZ],
  18671. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18672. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18673. };
  18674. break;
  18675. }
  18676. return bodyParameters;
  18677. };
  18678. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18679. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18680. var registeredMesh = this._registeredMeshes[index];
  18681. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18682. if (registeredMesh.body) {
  18683. this._world.removeRigidBody(registeredMesh.body.body);
  18684. this._unbindBody(registeredMesh.body);
  18685. }
  18686. this._registeredMeshes.splice(index, 1);
  18687. return;
  18688. }
  18689. }
  18690. };
  18691. OimoJSPlugin.prototype._unbindBody = function (body) {
  18692. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18693. var registeredMesh = this._registeredMeshes[index];
  18694. if (registeredMesh.body === body) {
  18695. registeredMesh.body = null;
  18696. }
  18697. }
  18698. };
  18699. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18700. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18701. var registeredMesh = this._registeredMeshes[index];
  18702. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18703. // Get object mass to have a behaviour similar to cannon.js
  18704. var mass = registeredMesh.body.body.massInfo.mass;
  18705. // The force is scaled with the mass of object
  18706. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18707. return;
  18708. }
  18709. }
  18710. };
  18711. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18712. var body1 = null, body2 = null;
  18713. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18714. var registeredMesh = this._registeredMeshes[index];
  18715. if (registeredMesh.mesh === mesh1) {
  18716. body1 = registeredMesh.body.body;
  18717. }
  18718. else if (registeredMesh.mesh === mesh2) {
  18719. body2 = registeredMesh.body.body;
  18720. }
  18721. }
  18722. if (!body1 || !body2) {
  18723. return false;
  18724. }
  18725. if (!options) {
  18726. options = {};
  18727. }
  18728. new OIMO.Link({
  18729. type: options.type,
  18730. body1: body1,
  18731. body2: body2,
  18732. min: options.min,
  18733. max: options.max,
  18734. axe1: options.axe1,
  18735. axe2: options.axe2,
  18736. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18737. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18738. collision: options.collision,
  18739. spring: options.spring,
  18740. world: this._world
  18741. });
  18742. return true;
  18743. };
  18744. OimoJSPlugin.prototype.dispose = function () {
  18745. this._world.clear();
  18746. while (this._registeredMeshes.length) {
  18747. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18748. }
  18749. };
  18750. OimoJSPlugin.prototype.isSupported = function () {
  18751. return OIMO !== undefined;
  18752. };
  18753. OimoJSPlugin.prototype._getLastShape = function (body) {
  18754. var lastShape = body.shapes;
  18755. while (lastShape.next) {
  18756. lastShape = lastShape.next;
  18757. }
  18758. return lastShape;
  18759. };
  18760. OimoJSPlugin.prototype.runOneStep = function (time) {
  18761. this._world.step();
  18762. // Update the position of all registered meshes
  18763. var i = this._registeredMeshes.length;
  18764. var m;
  18765. while (i--) {
  18766. var body = this._registeredMeshes[i].body.body;
  18767. var mesh = this._registeredMeshes[i].mesh;
  18768. var delta = this._registeredMeshes[i].delta;
  18769. if (!body.sleeping) {
  18770. if (body.shapes.next) {
  18771. var parentShape = this._getLastShape(body);
  18772. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18773. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18774. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18775. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18776. if (!mesh.rotationQuaternion) {
  18777. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18778. }
  18779. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18780. mesh.computeWorldMatrix();
  18781. }
  18782. else {
  18783. m = body.getMatrix();
  18784. mtx = BABYLON.Matrix.FromArray(m);
  18785. // Body position
  18786. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18787. if (!delta) {
  18788. mesh.position.x = bodyX;
  18789. mesh.position.y = bodyY;
  18790. mesh.position.z = bodyZ;
  18791. }
  18792. else {
  18793. mesh.position.x = bodyX + delta.x;
  18794. mesh.position.y = bodyY + delta.y;
  18795. mesh.position.z = bodyZ + delta.z;
  18796. }
  18797. if (!mesh.rotationQuaternion) {
  18798. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18799. }
  18800. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18801. mesh.computeWorldMatrix();
  18802. }
  18803. }
  18804. }
  18805. };
  18806. return OimoJSPlugin;
  18807. })();
  18808. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18809. })(BABYLON || (BABYLON = {}));
  18810. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18811. (function (BABYLON) {
  18812. var PhysicsEngine = (function () {
  18813. function PhysicsEngine(plugin) {
  18814. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18815. }
  18816. PhysicsEngine.prototype._initialize = function (gravity) {
  18817. this._currentPlugin.initialize();
  18818. this._setGravity(gravity);
  18819. };
  18820. PhysicsEngine.prototype._runOneStep = function (delta) {
  18821. if (delta > 0.1) {
  18822. delta = 0.1;
  18823. }
  18824. else if (delta <= 0) {
  18825. delta = 1.0 / 60.0;
  18826. }
  18827. this._currentPlugin.runOneStep(delta);
  18828. };
  18829. PhysicsEngine.prototype._setGravity = function (gravity) {
  18830. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18831. this._currentPlugin.setGravity(this.gravity);
  18832. };
  18833. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18834. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18835. };
  18836. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18837. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18838. };
  18839. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18840. this._currentPlugin.unregisterMesh(mesh);
  18841. };
  18842. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18843. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18844. };
  18845. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18846. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18847. };
  18848. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18849. this._currentPlugin.updateBodyPosition(mesh);
  18850. };
  18851. PhysicsEngine.prototype.dispose = function () {
  18852. this._currentPlugin.dispose();
  18853. };
  18854. PhysicsEngine.prototype.isSupported = function () {
  18855. return this._currentPlugin.isSupported();
  18856. };
  18857. // Statics
  18858. PhysicsEngine.NoImpostor = 0;
  18859. PhysicsEngine.SphereImpostor = 1;
  18860. PhysicsEngine.BoxImpostor = 2;
  18861. PhysicsEngine.PlaneImpostor = 3;
  18862. PhysicsEngine.MeshImpostor = 4;
  18863. PhysicsEngine.CapsuleImpostor = 5;
  18864. PhysicsEngine.ConeImpostor = 6;
  18865. PhysicsEngine.CylinderImpostor = 7;
  18866. PhysicsEngine.ConvexHullImpostor = 8;
  18867. PhysicsEngine.Epsilon = 0.001;
  18868. return PhysicsEngine;
  18869. })();
  18870. BABYLON.PhysicsEngine = PhysicsEngine;
  18871. })(BABYLON || (BABYLON = {}));
  18872. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18873. (function (BABYLON) {
  18874. var serializeLight = function (light) {
  18875. var serializationObject = {};
  18876. serializationObject.name = light.name;
  18877. serializationObject.id = light.id;
  18878. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18879. if (light instanceof BABYLON.PointLight) {
  18880. serializationObject.type = 0;
  18881. serializationObject.position = light.position.asArray();
  18882. }
  18883. else if (light instanceof BABYLON.DirectionalLight) {
  18884. serializationObject.type = 1;
  18885. var directionalLight = light;
  18886. serializationObject.position = directionalLight.position.asArray();
  18887. serializationObject.direction = directionalLight.direction.asArray();
  18888. }
  18889. else if (light instanceof BABYLON.SpotLight) {
  18890. serializationObject.type = 2;
  18891. var spotLight = light;
  18892. serializationObject.position = spotLight.position.asArray();
  18893. serializationObject.direction = spotLight.position.asArray();
  18894. serializationObject.angle = spotLight.angle;
  18895. serializationObject.exponent = spotLight.exponent;
  18896. }
  18897. else if (light instanceof BABYLON.HemisphericLight) {
  18898. serializationObject.type = 3;
  18899. var hemisphericLight = light;
  18900. serializationObject.direction = hemisphericLight.direction.asArray();
  18901. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18902. }
  18903. if (light.intensity) {
  18904. serializationObject.intensity = light.intensity;
  18905. }
  18906. serializationObject.range = light.range;
  18907. serializationObject.diffuse = light.diffuse.asArray();
  18908. serializationObject.specular = light.specular.asArray();
  18909. return serializationObject;
  18910. };
  18911. var serializeFresnelParameter = function (fresnelParameter) {
  18912. var serializationObject = {};
  18913. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18914. serializationObject.leftColor = fresnelParameter.leftColor;
  18915. serializationObject.rightColor = fresnelParameter.rightColor;
  18916. serializationObject.bias = fresnelParameter.bias;
  18917. serializationObject.power = fresnelParameter.power;
  18918. return serializationObject;
  18919. };
  18920. var appendAnimations = function (source, destination) {
  18921. if (source.animations) {
  18922. destination.animations = [];
  18923. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18924. var animation = source.animations[animationIndex];
  18925. destination.animations.push(serializeAnimation(animation));
  18926. }
  18927. }
  18928. };
  18929. var serializeCamera = function (camera) {
  18930. var serializationObject = {};
  18931. serializationObject.name = camera.name;
  18932. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18933. serializationObject.id = camera.id;
  18934. serializationObject.position = camera.position.asArray();
  18935. // Parent
  18936. if (camera.parent) {
  18937. serializationObject.parentId = camera.parent.id;
  18938. }
  18939. serializationObject.fov = camera.fov;
  18940. serializationObject.minZ = camera.minZ;
  18941. serializationObject.maxZ = camera.maxZ;
  18942. serializationObject.inertia = camera.inertia;
  18943. //setting the type
  18944. if (camera instanceof BABYLON.FreeCamera) {
  18945. serializationObject.type = "FreeCamera";
  18946. }
  18947. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18948. serializationObject.type = "ArcRotateCamera";
  18949. }
  18950. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18951. serializationObject.type = "AnaglyphArcRotateCamera";
  18952. }
  18953. else if (camera instanceof BABYLON.GamepadCamera) {
  18954. serializationObject.type = "GamepadCamera";
  18955. }
  18956. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18957. serializationObject.type = "AnaglyphFreeCamera";
  18958. }
  18959. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18960. serializationObject.type = "DeviceOrientationCamera";
  18961. }
  18962. else if (camera instanceof BABYLON.FollowCamera) {
  18963. serializationObject.type = "FollowCamera";
  18964. }
  18965. else if (camera instanceof BABYLON.OculusCamera) {
  18966. serializationObject.type = "OculusCamera";
  18967. }
  18968. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18969. serializationObject.type = "OculusGamepadCamera";
  18970. }
  18971. else if (camera instanceof BABYLON.TouchCamera) {
  18972. serializationObject.type = "TouchCamera";
  18973. }
  18974. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18975. serializationObject.type = "VirtualJoysticksCamera";
  18976. }
  18977. else if (camera instanceof BABYLON.WebVRCamera) {
  18978. serializationObject.type = "WebVRCamera";
  18979. }
  18980. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18981. serializationObject.type = "VRDeviceOrientationCamera";
  18982. }
  18983. //special properties of specific cameras
  18984. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18985. var arcCamera = camera;
  18986. serializationObject.alpha = arcCamera.alpha;
  18987. serializationObject.beta = arcCamera.beta;
  18988. serializationObject.radius = arcCamera.radius;
  18989. if (arcCamera.target && arcCamera.target.id) {
  18990. serializationObject.lockedTargetId = arcCamera.target.id;
  18991. }
  18992. }
  18993. else if (camera instanceof BABYLON.FollowCamera) {
  18994. var followCam = camera;
  18995. serializationObject.radius = followCam.radius;
  18996. serializationObject.heightOffset = followCam.heightOffset;
  18997. serializationObject.rotationOffset = followCam.rotationOffset;
  18998. }
  18999. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  19000. //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.
  19001. if (camera['_eyeSpace'] !== undefined) {
  19002. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  19003. }
  19004. }
  19005. //general properties that not all cameras have. The [] is due to typescript's type safety
  19006. if (camera['speed'] !== undefined) {
  19007. serializationObject.speed = camera['speed'];
  19008. }
  19009. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  19010. serializationObject.target = camera['target'].asArray();
  19011. }
  19012. // Target
  19013. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  19014. serializationObject.rotation = camera['rotation'].asArray();
  19015. }
  19016. // Locked target
  19017. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  19018. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  19019. }
  19020. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  19021. serializationObject.applyGravity = camera['applyGravity'] || false;
  19022. if (camera['ellipsoid']) {
  19023. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  19024. }
  19025. // Animations
  19026. appendAnimations(camera, serializationObject);
  19027. // Layer mask
  19028. serializationObject.layerMask = camera.layerMask;
  19029. return serializationObject;
  19030. };
  19031. var serializeAnimation = function (animation) {
  19032. var serializationObject = {};
  19033. serializationObject.name = animation.name;
  19034. serializationObject.property = animation.targetProperty;
  19035. serializationObject.framePerSecond = animation.framePerSecond;
  19036. serializationObject.dataType = animation.dataType;
  19037. serializationObject.loopBehavior = animation.loopMode;
  19038. var dataType = animation.dataType;
  19039. serializationObject.keys = [];
  19040. var keys = animation.getKeys();
  19041. for (var index = 0; index < keys.length; index++) {
  19042. var animationKey = keys[index];
  19043. var key = {};
  19044. key.frame = animationKey.frame;
  19045. switch (dataType) {
  19046. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19047. key.values = [animationKey.value];
  19048. break;
  19049. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19050. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19051. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19052. key.values = animationKey.value.asArray();
  19053. break;
  19054. }
  19055. serializationObject.keys.push(key);
  19056. }
  19057. return serializationObject;
  19058. };
  19059. var serializeMultiMaterial = function (material) {
  19060. var serializationObject = {};
  19061. serializationObject.name = material.name;
  19062. serializationObject.id = material.id;
  19063. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19064. serializationObject.materials = [];
  19065. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  19066. var subMat = material.subMaterials[matIndex];
  19067. if (subMat) {
  19068. serializationObject.materials.push(subMat.id);
  19069. }
  19070. else {
  19071. serializationObject.materials.push(null);
  19072. }
  19073. }
  19074. return serializationObject;
  19075. };
  19076. var serializeMaterial = function (material) {
  19077. var serializationObject = {};
  19078. serializationObject.name = material.name;
  19079. serializationObject.ambient = material.ambientColor.asArray();
  19080. serializationObject.diffuse = material.diffuseColor.asArray();
  19081. serializationObject.specular = material.specularColor.asArray();
  19082. serializationObject.specularPower = material.specularPower;
  19083. serializationObject.emissive = material.emissiveColor.asArray();
  19084. serializationObject.alpha = material.alpha;
  19085. serializationObject.id = material.id;
  19086. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19087. serializationObject.backFaceCulling = material.backFaceCulling;
  19088. if (material.diffuseTexture) {
  19089. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  19090. }
  19091. if (material.diffuseFresnelParameters) {
  19092. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  19093. }
  19094. if (material.ambientTexture) {
  19095. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  19096. }
  19097. if (material.opacityTexture) {
  19098. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  19099. }
  19100. if (material.opacityFresnelParameters) {
  19101. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  19102. }
  19103. if (material.reflectionTexture) {
  19104. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  19105. }
  19106. if (material.reflectionFresnelParameters) {
  19107. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  19108. }
  19109. if (material.emissiveTexture) {
  19110. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  19111. }
  19112. if (material.emissiveFresnelParameters) {
  19113. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  19114. }
  19115. if (material.specularTexture) {
  19116. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  19117. }
  19118. if (material.bumpTexture) {
  19119. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  19120. }
  19121. return serializationObject;
  19122. };
  19123. var serializeTexture = function (texture) {
  19124. var serializationObject = {};
  19125. if (!texture.name) {
  19126. return null;
  19127. }
  19128. if (texture instanceof BABYLON.CubeTexture) {
  19129. serializationObject.name = texture.name;
  19130. serializationObject.hasAlpha = texture.hasAlpha;
  19131. serializationObject.level = texture.level;
  19132. serializationObject.coordinatesMode = texture.coordinatesMode;
  19133. return serializationObject;
  19134. }
  19135. if (texture instanceof BABYLON.MirrorTexture) {
  19136. var mirrorTexture = texture;
  19137. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  19138. serializationObject.renderList = [];
  19139. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  19140. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  19141. }
  19142. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  19143. }
  19144. else if (texture instanceof BABYLON.RenderTargetTexture) {
  19145. var renderTargetTexture = texture;
  19146. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  19147. serializationObject.renderList = [];
  19148. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  19149. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  19150. }
  19151. }
  19152. var regularTexture = texture;
  19153. serializationObject.name = texture.name;
  19154. serializationObject.hasAlpha = texture.hasAlpha;
  19155. serializationObject.level = texture.level;
  19156. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  19157. serializationObject.coordinatesMode = texture.coordinatesMode;
  19158. serializationObject.uOffset = regularTexture.uOffset;
  19159. serializationObject.vOffset = regularTexture.vOffset;
  19160. serializationObject.uScale = regularTexture.uScale;
  19161. serializationObject.vScale = regularTexture.vScale;
  19162. serializationObject.uAng = regularTexture.uAng;
  19163. serializationObject.vAng = regularTexture.vAng;
  19164. serializationObject.wAng = regularTexture.wAng;
  19165. serializationObject.wrapU = texture.wrapU;
  19166. serializationObject.wrapV = texture.wrapV;
  19167. // Animations
  19168. appendAnimations(texture, serializationObject);
  19169. return serializationObject;
  19170. };
  19171. var serializeSkeleton = function (skeleton) {
  19172. var serializationObject = {};
  19173. serializationObject.name = skeleton.name;
  19174. serializationObject.id = skeleton.id;
  19175. serializationObject.bones = [];
  19176. for (var index = 0; index < skeleton.bones.length; index++) {
  19177. var bone = skeleton.bones[index];
  19178. var serializedBone = {
  19179. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  19180. name: bone.name,
  19181. matrix: bone.getLocalMatrix().toArray()
  19182. };
  19183. serializationObject.bones.push(serializedBone);
  19184. if (bone.animations && bone.animations.length > 0) {
  19185. serializedBone.animation = serializeAnimation(bone.animations[0]);
  19186. }
  19187. }
  19188. return serializationObject;
  19189. };
  19190. var serializeParticleSystem = function (particleSystem) {
  19191. var serializationObject = {};
  19192. serializationObject.emitterId = particleSystem.emitter.id;
  19193. serializationObject.capacity = particleSystem.getCapacity();
  19194. if (particleSystem.particleTexture) {
  19195. serializationObject.textureName = particleSystem.particleTexture.name;
  19196. }
  19197. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  19198. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  19199. serializationObject.minSize = particleSystem.minSize;
  19200. serializationObject.maxSize = particleSystem.maxSize;
  19201. serializationObject.minLifeTime = particleSystem.minLifeTime;
  19202. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  19203. serializationObject.emitRate = particleSystem.emitRate;
  19204. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  19205. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  19206. serializationObject.gravity = particleSystem.gravity.asArray();
  19207. serializationObject.direction1 = particleSystem.direction1.asArray();
  19208. serializationObject.direction2 = particleSystem.direction2.asArray();
  19209. serializationObject.color1 = particleSystem.color1.asArray();
  19210. serializationObject.color2 = particleSystem.color2.asArray();
  19211. serializationObject.colorDead = particleSystem.colorDead.asArray();
  19212. serializationObject.updateSpeed = particleSystem.updateSpeed;
  19213. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  19214. serializationObject.textureMask = particleSystem.textureMask.asArray();
  19215. serializationObject.blendMode = particleSystem.blendMode;
  19216. return serializationObject;
  19217. };
  19218. var serializeLensFlareSystem = function (lensFlareSystem) {
  19219. var serializationObject = {};
  19220. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  19221. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  19222. serializationObject.flares = [];
  19223. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  19224. var flare = lensFlareSystem.lensFlares[index];
  19225. serializationObject.flares.push({
  19226. size: flare.size,
  19227. position: flare.position,
  19228. color: flare.color.asArray(),
  19229. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  19230. });
  19231. }
  19232. return serializationObject;
  19233. };
  19234. var serializeShadowGenerator = function (light) {
  19235. var serializationObject = {};
  19236. var shadowGenerator = light.getShadowGenerator();
  19237. serializationObject.lightId = light.id;
  19238. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  19239. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  19240. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  19241. serializationObject.renderList = [];
  19242. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19243. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19244. serializationObject.renderList.push(mesh.id);
  19245. }
  19246. return serializationObject;
  19247. };
  19248. var serializedGeometries = [];
  19249. var serializeGeometry = function (geometry, serializationGeometries) {
  19250. if (serializedGeometries[geometry.id]) {
  19251. return;
  19252. }
  19253. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19254. serializationGeometries.boxes.push(serializeBox(geometry));
  19255. }
  19256. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19257. serializationGeometries.spheres.push(serializeSphere(geometry));
  19258. }
  19259. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19260. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19261. }
  19262. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19263. serializationGeometries.toruses.push(serializeTorus(geometry));
  19264. }
  19265. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19266. serializationGeometries.grounds.push(serializeGround(geometry));
  19267. }
  19268. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19269. serializationGeometries.planes.push(serializePlane(geometry));
  19270. }
  19271. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19272. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19273. }
  19274. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19275. throw new Error("Unknow primitive type");
  19276. }
  19277. else {
  19278. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19279. }
  19280. serializedGeometries[geometry.id] = true;
  19281. };
  19282. var serializeGeometryBase = function (geometry) {
  19283. var serializationObject = {};
  19284. serializationObject.id = geometry.id;
  19285. if (BABYLON.Tags.HasTags(geometry)) {
  19286. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19287. }
  19288. return serializationObject;
  19289. };
  19290. var serializeVertexData = function (vertexData) {
  19291. var serializationObject = serializeGeometryBase(vertexData);
  19292. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19293. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19294. }
  19295. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19296. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19297. }
  19298. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19299. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19300. }
  19301. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19302. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19303. }
  19304. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19305. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19306. }
  19307. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19308. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19309. serializationObject.matricesIndices._isExpanded = true;
  19310. }
  19311. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19312. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19313. }
  19314. serializationObject.indices = vertexData.getIndices();
  19315. return serializationObject;
  19316. };
  19317. var serializePrimitive = function (primitive) {
  19318. var serializationObject = serializeGeometryBase(primitive);
  19319. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19320. return serializationObject;
  19321. };
  19322. var serializeBox = function (box) {
  19323. var serializationObject = serializePrimitive(box);
  19324. serializationObject.size = box.size;
  19325. return serializationObject;
  19326. };
  19327. var serializeSphere = function (sphere) {
  19328. var serializationObject = serializePrimitive(sphere);
  19329. serializationObject.segments = sphere.segments;
  19330. serializationObject.diameter = sphere.diameter;
  19331. return serializationObject;
  19332. };
  19333. var serializeCylinder = function (cylinder) {
  19334. var serializationObject = serializePrimitive(cylinder);
  19335. serializationObject.height = cylinder.height;
  19336. serializationObject.diameterTop = cylinder.diameterTop;
  19337. serializationObject.diameterBottom = cylinder.diameterBottom;
  19338. serializationObject.tessellation = cylinder.tessellation;
  19339. return serializationObject;
  19340. };
  19341. var serializeTorus = function (torus) {
  19342. var serializationObject = serializePrimitive(torus);
  19343. serializationObject.diameter = torus.diameter;
  19344. serializationObject.thickness = torus.thickness;
  19345. serializationObject.tessellation = torus.tessellation;
  19346. return serializationObject;
  19347. };
  19348. var serializeGround = function (ground) {
  19349. var serializationObject = serializePrimitive(ground);
  19350. serializationObject.width = ground.width;
  19351. serializationObject.height = ground.height;
  19352. serializationObject.subdivisions = ground.subdivisions;
  19353. return serializationObject;
  19354. };
  19355. var serializePlane = function (plane) {
  19356. var serializationObject = serializePrimitive(plane);
  19357. serializationObject.size = plane.size;
  19358. return serializationObject;
  19359. };
  19360. var serializeTorusKnot = function (torusKnot) {
  19361. var serializationObject = serializePrimitive(torusKnot);
  19362. serializationObject.radius = torusKnot.radius;
  19363. serializationObject.tube = torusKnot.tube;
  19364. serializationObject.radialSegments = torusKnot.radialSegments;
  19365. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19366. serializationObject.p = torusKnot.p;
  19367. serializationObject.q = torusKnot.q;
  19368. return serializationObject;
  19369. };
  19370. var serializeMesh = function (mesh, serializationScene) {
  19371. var serializationObject = {};
  19372. serializationObject.name = mesh.name;
  19373. serializationObject.id = mesh.id;
  19374. if (BABYLON.Tags.HasTags(mesh)) {
  19375. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19376. }
  19377. serializationObject.position = mesh.position.asArray();
  19378. if (mesh.rotationQuaternion) {
  19379. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19380. }
  19381. else if (mesh.rotation) {
  19382. serializationObject.rotation = mesh.rotation.asArray();
  19383. }
  19384. serializationObject.scaling = mesh.scaling.asArray();
  19385. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19386. serializationObject.isEnabled = mesh.isEnabled();
  19387. serializationObject.isVisible = mesh.isVisible;
  19388. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19389. serializationObject.pickable = mesh.isPickable;
  19390. serializationObject.receiveShadows = mesh.receiveShadows;
  19391. serializationObject.billboardMode = mesh.billboardMode;
  19392. serializationObject.visibility = mesh.visibility;
  19393. serializationObject.checkCollisions = mesh.checkCollisions;
  19394. // Parent
  19395. if (mesh.parent) {
  19396. serializationObject.parentId = mesh.parent.id;
  19397. }
  19398. // Geometry
  19399. var geometry = mesh._geometry;
  19400. if (geometry) {
  19401. var geometryId = geometry.id;
  19402. serializationObject.geometryId = geometryId;
  19403. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19404. // 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
  19405. serializeGeometry(geometry, serializationScene.geometries);
  19406. }
  19407. // SubMeshes
  19408. serializationObject.subMeshes = [];
  19409. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19410. var subMesh = mesh.subMeshes[subIndex];
  19411. serializationObject.subMeshes.push({
  19412. materialIndex: subMesh.materialIndex,
  19413. verticesStart: subMesh.verticesStart,
  19414. verticesCount: subMesh.verticesCount,
  19415. indexStart: subMesh.indexStart,
  19416. indexCount: subMesh.indexCount
  19417. });
  19418. }
  19419. }
  19420. // Material
  19421. if (mesh.material) {
  19422. serializationObject.materialId = mesh.material.id;
  19423. }
  19424. else {
  19425. mesh.material = null;
  19426. }
  19427. // Skeleton
  19428. if (mesh.skeleton) {
  19429. serializationObject.skeletonId = mesh.skeleton.id;
  19430. }
  19431. // Physics
  19432. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19433. serializationObject.physicsMass = mesh.getPhysicsMass();
  19434. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19435. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19436. switch (mesh.getPhysicsImpostor()) {
  19437. case BABYLON.PhysicsEngine.BoxImpostor:
  19438. serializationObject.physicsImpostor = 1;
  19439. break;
  19440. case BABYLON.PhysicsEngine.SphereImpostor:
  19441. serializationObject.physicsImpostor = 2;
  19442. break;
  19443. }
  19444. }
  19445. // Instances
  19446. serializationObject.instances = [];
  19447. for (var index = 0; index < mesh.instances.length; index++) {
  19448. var instance = mesh.instances[index];
  19449. var serializationInstance = {
  19450. name: instance.name,
  19451. position: instance.position,
  19452. rotation: instance.rotation,
  19453. rotationQuaternion: instance.rotationQuaternion,
  19454. scaling: instance.scaling
  19455. };
  19456. serializationObject.instances.push(serializationInstance);
  19457. // Animations
  19458. appendAnimations(instance, serializationInstance);
  19459. }
  19460. // Animations
  19461. appendAnimations(mesh, serializationObject);
  19462. // Layer mask
  19463. serializationObject.layerMask = mesh.layerMask;
  19464. return serializationObject;
  19465. };
  19466. var SceneSerializer = (function () {
  19467. function SceneSerializer() {
  19468. }
  19469. SceneSerializer.Serialize = function (scene) {
  19470. var serializationObject = {};
  19471. // Scene
  19472. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19473. serializationObject.autoClear = scene.autoClear;
  19474. serializationObject.clearColor = scene.clearColor.asArray();
  19475. serializationObject.ambientColor = scene.ambientColor.asArray();
  19476. serializationObject.gravity = scene.gravity.asArray();
  19477. // Fog
  19478. if (scene.fogMode && scene.fogMode !== 0) {
  19479. serializationObject.fogMode = scene.fogMode;
  19480. serializationObject.fogColor = scene.fogColor.asArray();
  19481. serializationObject.fogStart = scene.fogStart;
  19482. serializationObject.fogEnd = scene.fogEnd;
  19483. serializationObject.fogDensity = scene.fogDensity;
  19484. }
  19485. // Lights
  19486. serializationObject.lights = [];
  19487. for (var index = 0; index < scene.lights.length; index++) {
  19488. var light = scene.lights[index];
  19489. serializationObject.lights.push(serializeLight(light));
  19490. }
  19491. // Cameras
  19492. serializationObject.cameras = [];
  19493. for (index = 0; index < scene.cameras.length; index++) {
  19494. var camera = scene.cameras[index];
  19495. serializationObject.cameras.push(serializeCamera(camera));
  19496. }
  19497. if (scene.activeCamera) {
  19498. serializationObject.activeCameraID = scene.activeCamera.id;
  19499. }
  19500. // Materials
  19501. serializationObject.materials = [];
  19502. serializationObject.multiMaterials = [];
  19503. for (index = 0; index < scene.materials.length; index++) {
  19504. var material = scene.materials[index];
  19505. if (material instanceof BABYLON.StandardMaterial) {
  19506. serializationObject.materials.push(serializeMaterial(material));
  19507. }
  19508. else if (material instanceof BABYLON.MultiMaterial) {
  19509. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19510. }
  19511. }
  19512. // Skeletons
  19513. serializationObject.skeletons = [];
  19514. for (index = 0; index < scene.skeletons.length; index++) {
  19515. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19516. }
  19517. // Geometries
  19518. serializationObject.geometries = {};
  19519. serializationObject.geometries.boxes = [];
  19520. serializationObject.geometries.spheres = [];
  19521. serializationObject.geometries.cylinders = [];
  19522. serializationObject.geometries.toruses = [];
  19523. serializationObject.geometries.grounds = [];
  19524. serializationObject.geometries.planes = [];
  19525. serializationObject.geometries.torusKnots = [];
  19526. serializationObject.geometries.vertexData = [];
  19527. serializedGeometries = [];
  19528. var geometries = scene.getGeometries();
  19529. for (index = 0; index < geometries.length; index++) {
  19530. var geometry = geometries[index];
  19531. if (geometry.isReady()) {
  19532. serializeGeometry(geometry, serializationObject.geometries);
  19533. }
  19534. }
  19535. // Meshes
  19536. serializationObject.meshes = [];
  19537. for (index = 0; index < scene.meshes.length; index++) {
  19538. var abstractMesh = scene.meshes[index];
  19539. if (abstractMesh instanceof BABYLON.Mesh) {
  19540. var mesh = abstractMesh;
  19541. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19542. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19543. }
  19544. }
  19545. }
  19546. // Particles Systems
  19547. serializationObject.particleSystems = [];
  19548. for (index = 0; index < scene.particleSystems.length; index++) {
  19549. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19550. }
  19551. // Lens flares
  19552. serializationObject.lensFlareSystems = [];
  19553. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19554. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19555. }
  19556. // Shadows
  19557. serializationObject.shadowGenerators = [];
  19558. for (index = 0; index < scene.lights.length; index++) {
  19559. light = scene.lights[index];
  19560. if (light.getShadowGenerator()) {
  19561. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19562. }
  19563. }
  19564. return serializationObject;
  19565. };
  19566. return SceneSerializer;
  19567. })();
  19568. BABYLON.SceneSerializer = SceneSerializer;
  19569. })(BABYLON || (BABYLON = {}));
  19570. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19571. (function (BABYLON) {
  19572. var SceneLoader = (function () {
  19573. function SceneLoader() {
  19574. }
  19575. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19576. get: function () {
  19577. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19578. },
  19579. set: function (value) {
  19580. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19586. get: function () {
  19587. return SceneLoader._ShowLoadingScreen;
  19588. },
  19589. set: function (value) {
  19590. SceneLoader._ShowLoadingScreen = value;
  19591. },
  19592. enumerable: true,
  19593. configurable: true
  19594. });
  19595. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19596. var dotPosition = sceneFilename.lastIndexOf(".");
  19597. var queryStringPosition = sceneFilename.indexOf("?");
  19598. if (queryStringPosition === -1) {
  19599. queryStringPosition = sceneFilename.length;
  19600. }
  19601. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19602. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19603. var plugin = this._registeredPlugins[index];
  19604. if (plugin.extensions.indexOf(extension) !== -1) {
  19605. return plugin;
  19606. }
  19607. }
  19608. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19609. };
  19610. // Public functions
  19611. SceneLoader.RegisterPlugin = function (plugin) {
  19612. plugin.extensions = plugin.extensions.toLowerCase();
  19613. SceneLoader._registeredPlugins.push(plugin);
  19614. };
  19615. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19616. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19617. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19618. return;
  19619. }
  19620. var manifestChecked = function (success) {
  19621. scene.database = database;
  19622. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19623. var importMeshFromData = function (data) {
  19624. var meshes = [];
  19625. var particleSystems = [];
  19626. var skeletons = [];
  19627. try {
  19628. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19629. if (onerror) {
  19630. onerror(scene, 'unable to load the scene');
  19631. }
  19632. return;
  19633. }
  19634. }
  19635. catch (e) {
  19636. if (onerror) {
  19637. onerror(scene, e);
  19638. }
  19639. return;
  19640. }
  19641. if (onsuccess) {
  19642. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19643. onsuccess(meshes, particleSystems, skeletons);
  19644. }
  19645. };
  19646. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19647. // Direct load
  19648. importMeshFromData(sceneFilename.substr(5));
  19649. return;
  19650. }
  19651. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19652. importMeshFromData(data);
  19653. }, progressCallBack, database);
  19654. };
  19655. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19656. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19657. };
  19658. /**
  19659. * Load a scene
  19660. * @param rootUrl a string that defines the root url for scene and resources
  19661. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19662. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19663. */
  19664. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19665. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19666. };
  19667. /**
  19668. * Append a scene
  19669. * @param rootUrl a string that defines the root url for scene and resources
  19670. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19671. * @param scene is the instance of BABYLON.Scene to append to
  19672. */
  19673. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19674. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19675. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19676. return;
  19677. }
  19678. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19679. var database;
  19680. if (SceneLoader.ShowLoadingScreen) {
  19681. scene.getEngine().displayLoadingUI();
  19682. }
  19683. var loadSceneFromData = function (data) {
  19684. scene.database = database;
  19685. if (!plugin.load(scene, data, rootUrl)) {
  19686. if (onerror) {
  19687. onerror(scene);
  19688. }
  19689. scene.getEngine().hideLoadingUI();
  19690. return;
  19691. }
  19692. if (onsuccess) {
  19693. onsuccess(scene);
  19694. }
  19695. if (SceneLoader.ShowLoadingScreen) {
  19696. scene.executeWhenReady(function () {
  19697. scene.getEngine().hideLoadingUI();
  19698. });
  19699. }
  19700. };
  19701. var manifestChecked = function (success) {
  19702. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19703. };
  19704. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19705. // Direct load
  19706. loadSceneFromData(sceneFilename.substr(5));
  19707. return;
  19708. }
  19709. if (rootUrl.indexOf("file:") === -1) {
  19710. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19711. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19712. }
  19713. else {
  19714. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19715. }
  19716. };
  19717. // Flags
  19718. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19719. SceneLoader._ShowLoadingScreen = true;
  19720. // Members
  19721. SceneLoader._registeredPlugins = new Array();
  19722. return SceneLoader;
  19723. })();
  19724. BABYLON.SceneLoader = SceneLoader;
  19725. ;
  19726. })(BABYLON || (BABYLON = {}));
  19727. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19728. (function (BABYLON) {
  19729. var Internals;
  19730. (function (Internals) {
  19731. var checkColors4 = function (colors, count) {
  19732. // Check if color3 was used
  19733. if (colors.length === count * 3) {
  19734. var colors4 = [];
  19735. for (var index = 0; index < colors.length; index += 3) {
  19736. var newIndex = (index / 3) * 4;
  19737. colors4[newIndex] = colors[index];
  19738. colors4[newIndex + 1] = colors[index + 1];
  19739. colors4[newIndex + 2] = colors[index + 2];
  19740. colors4[newIndex + 3] = 1.0;
  19741. }
  19742. return colors4;
  19743. }
  19744. return colors;
  19745. };
  19746. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19747. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19748. texture.name = parsedTexture.name;
  19749. texture.hasAlpha = parsedTexture.hasAlpha;
  19750. texture.level = parsedTexture.level;
  19751. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19752. return texture;
  19753. };
  19754. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19755. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19756. return null;
  19757. }
  19758. if (parsedTexture.isCube) {
  19759. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19760. }
  19761. var texture;
  19762. if (parsedTexture.mirrorPlane) {
  19763. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19764. texture._waitingRenderList = parsedTexture.renderList;
  19765. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19766. }
  19767. else if (parsedTexture.isRenderTarget) {
  19768. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19769. texture._waitingRenderList = parsedTexture.renderList;
  19770. }
  19771. else {
  19772. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19773. }
  19774. texture.name = parsedTexture.name;
  19775. texture.hasAlpha = parsedTexture.hasAlpha;
  19776. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19777. texture.level = parsedTexture.level;
  19778. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19779. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19780. texture.uOffset = parsedTexture.uOffset;
  19781. texture.vOffset = parsedTexture.vOffset;
  19782. texture.uScale = parsedTexture.uScale;
  19783. texture.vScale = parsedTexture.vScale;
  19784. texture.uAng = parsedTexture.uAng;
  19785. texture.vAng = parsedTexture.vAng;
  19786. texture.wAng = parsedTexture.wAng;
  19787. texture.wrapU = parsedTexture.wrapU;
  19788. texture.wrapV = parsedTexture.wrapV;
  19789. // Animations
  19790. if (parsedTexture.animations) {
  19791. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19792. var parsedAnimation = parsedTexture.animations[animationIndex];
  19793. texture.animations.push(parseAnimation(parsedAnimation));
  19794. }
  19795. }
  19796. return texture;
  19797. };
  19798. var parseSkeleton = function (parsedSkeleton, scene) {
  19799. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19800. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19801. var parsedBone = parsedSkeleton.bones[index];
  19802. var parentBone = null;
  19803. if (parsedBone.parentBoneIndex > -1) {
  19804. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19805. }
  19806. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19807. if (parsedBone.animation) {
  19808. bone.animations.push(parseAnimation(parsedBone.animation));
  19809. }
  19810. }
  19811. return skeleton;
  19812. };
  19813. var parseFresnelParameters = function (parsedFresnelParameters) {
  19814. var fresnelParameters = new BABYLON.FresnelParameters();
  19815. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19816. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19817. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19818. fresnelParameters.bias = parsedFresnelParameters.bias;
  19819. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19820. return fresnelParameters;
  19821. };
  19822. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19823. var material;
  19824. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19825. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19826. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19827. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19828. material.specularPower = parsedMaterial.specularPower;
  19829. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19830. material.alpha = parsedMaterial.alpha;
  19831. material.id = parsedMaterial.id;
  19832. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19833. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19834. material.wireframe = parsedMaterial.wireframe;
  19835. if (parsedMaterial.diffuseTexture) {
  19836. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19837. }
  19838. if (parsedMaterial.diffuseFresnelParameters) {
  19839. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19840. }
  19841. if (parsedMaterial.ambientTexture) {
  19842. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19843. }
  19844. if (parsedMaterial.opacityTexture) {
  19845. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19846. }
  19847. if (parsedMaterial.opacityFresnelParameters) {
  19848. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19849. }
  19850. if (parsedMaterial.reflectionTexture) {
  19851. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19852. }
  19853. if (parsedMaterial.reflectionFresnelParameters) {
  19854. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19855. }
  19856. if (parsedMaterial.emissiveTexture) {
  19857. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19858. }
  19859. if (parsedMaterial.emissiveFresnelParameters) {
  19860. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19861. }
  19862. if (parsedMaterial.specularTexture) {
  19863. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19864. }
  19865. if (parsedMaterial.bumpTexture) {
  19866. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19867. }
  19868. return material;
  19869. };
  19870. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19871. for (var index = 0; index < parsedData.materials.length; index++) {
  19872. var parsedMaterial = parsedData.materials[index];
  19873. if (parsedMaterial.id === id) {
  19874. return parseMaterial(parsedMaterial, scene, rootUrl);
  19875. }
  19876. }
  19877. return null;
  19878. };
  19879. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19880. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19881. multiMaterial.id = parsedMultiMaterial.id;
  19882. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19883. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19884. var subMatId = parsedMultiMaterial.materials[matIndex];
  19885. if (subMatId) {
  19886. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19887. }
  19888. else {
  19889. multiMaterial.subMaterials.push(null);
  19890. }
  19891. }
  19892. return multiMaterial;
  19893. };
  19894. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19895. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19896. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19897. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19898. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19899. var parsedFlare = parsedLensFlareSystem.flares[index];
  19900. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19901. }
  19902. return lensFlareSystem;
  19903. };
  19904. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19905. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19906. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19907. if (parsedParticleSystem.textureName) {
  19908. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19909. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19910. }
  19911. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19912. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19913. particleSystem.minSize = parsedParticleSystem.minSize;
  19914. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19915. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19916. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19917. particleSystem.emitter = emitter;
  19918. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19919. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19920. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19921. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19922. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19923. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19924. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19925. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19926. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19927. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19928. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19929. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19930. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19931. particleSystem.start();
  19932. return particleSystem;
  19933. };
  19934. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19935. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19936. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19937. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19938. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19939. shadowGenerator.getShadowMap().renderList.push(mesh);
  19940. }
  19941. if (parsedShadowGenerator.usePoissonSampling) {
  19942. shadowGenerator.usePoissonSampling = true;
  19943. }
  19944. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19945. shadowGenerator.useVarianceShadowMap = true;
  19946. }
  19947. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19948. shadowGenerator.useBlurVarianceShadowMap = true;
  19949. if (parsedShadowGenerator.blurScale) {
  19950. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19951. }
  19952. if (parsedShadowGenerator.blurBoxOffset) {
  19953. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19954. }
  19955. }
  19956. if (parsedShadowGenerator.bias !== undefined) {
  19957. shadowGenerator.bias = parsedShadowGenerator.bias;
  19958. }
  19959. return shadowGenerator;
  19960. };
  19961. var parseAnimation = function (parsedAnimation) {
  19962. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19963. var dataType = parsedAnimation.dataType;
  19964. var keys = [];
  19965. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19966. var key = parsedAnimation.keys[index];
  19967. var data;
  19968. switch (dataType) {
  19969. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19970. data = key.values[0];
  19971. break;
  19972. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19973. data = BABYLON.Quaternion.FromArray(key.values);
  19974. break;
  19975. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19976. data = BABYLON.Matrix.FromArray(key.values);
  19977. break;
  19978. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19979. default:
  19980. data = BABYLON.Vector3.FromArray(key.values);
  19981. break;
  19982. }
  19983. keys.push({
  19984. frame: key.frame,
  19985. value: data
  19986. });
  19987. }
  19988. animation.setKeys(keys);
  19989. return animation;
  19990. };
  19991. var parseLight = function (parsedLight, scene) {
  19992. var light;
  19993. switch (parsedLight.type) {
  19994. case 0:
  19995. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19996. break;
  19997. case 1:
  19998. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19999. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  20000. break;
  20001. case 2:
  20002. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  20003. break;
  20004. case 3:
  20005. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20006. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  20007. break;
  20008. }
  20009. light.id = parsedLight.id;
  20010. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  20011. if (parsedLight.intensity !== undefined) {
  20012. light.intensity = parsedLight.intensity;
  20013. }
  20014. if (parsedLight.range) {
  20015. light.range = parsedLight.range;
  20016. }
  20017. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  20018. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  20019. if (parsedLight.excludedMeshesIds) {
  20020. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  20021. }
  20022. // Parent
  20023. if (parsedLight.parentId) {
  20024. light._waitingParentId = parsedLight.parentId;
  20025. }
  20026. if (parsedLight.includedOnlyMeshesIds) {
  20027. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  20028. }
  20029. // Animations
  20030. if (parsedLight.animations) {
  20031. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20032. var parsedAnimation = parsedLight.animations[animationIndex];
  20033. light.animations.push(parseAnimation(parsedAnimation));
  20034. }
  20035. }
  20036. if (parsedLight.autoAnimate) {
  20037. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  20038. }
  20039. };
  20040. var parseCamera = function (parsedCamera, scene) {
  20041. var camera;
  20042. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  20043. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  20044. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  20045. var alpha = parsedCamera.alpha;
  20046. var beta = parsedCamera.beta;
  20047. var radius = parsedCamera.radius;
  20048. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  20049. var eye_space = parsedCamera.eye_space;
  20050. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  20051. }
  20052. else {
  20053. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  20054. }
  20055. }
  20056. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20057. eye_space = parsedCamera.eye_space;
  20058. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  20059. }
  20060. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20061. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20062. }
  20063. else if (parsedCamera.type === "FollowCamera") {
  20064. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20065. camera.heightOffset = parsedCamera.heightOffset;
  20066. camera.radius = parsedCamera.radius;
  20067. camera.rotationOffset = parsedCamera.rotationOffset;
  20068. if (lockedTargetMesh)
  20069. camera.target = lockedTargetMesh;
  20070. }
  20071. else if (parsedCamera.type === "GamepadCamera") {
  20072. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20073. }
  20074. else if (parsedCamera.type === "OculusCamera") {
  20075. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  20076. }
  20077. else if (parsedCamera.type === "OculusGamepadCamera") {
  20078. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  20079. }
  20080. else if (parsedCamera.type === "TouchCamera") {
  20081. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20082. }
  20083. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20084. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20085. }
  20086. else if (parsedCamera.type === "WebVRCamera") {
  20087. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  20088. }
  20089. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  20090. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  20091. }
  20092. else {
  20093. // Free Camera is the default value
  20094. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20095. }
  20096. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20097. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20098. camera.lockedTarget = lockedTargetMesh;
  20099. }
  20100. camera.id = parsedCamera.id;
  20101. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20102. // Parent
  20103. if (parsedCamera.parentId) {
  20104. camera._waitingParentId = parsedCamera.parentId;
  20105. }
  20106. // Target
  20107. if (parsedCamera.target) {
  20108. if (camera.setTarget) {
  20109. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20110. }
  20111. else {
  20112. //For ArcRotate
  20113. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20114. }
  20115. }
  20116. else {
  20117. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20118. }
  20119. camera.fov = parsedCamera.fov;
  20120. camera.minZ = parsedCamera.minZ;
  20121. camera.maxZ = parsedCamera.maxZ;
  20122. camera.speed = parsedCamera.speed;
  20123. camera.inertia = parsedCamera.inertia;
  20124. camera.checkCollisions = parsedCamera.checkCollisions;
  20125. camera.applyGravity = parsedCamera.applyGravity;
  20126. if (parsedCamera.ellipsoid) {
  20127. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20128. }
  20129. // Animations
  20130. if (parsedCamera.animations) {
  20131. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20132. var parsedAnimation = parsedCamera.animations[animationIndex];
  20133. camera.animations.push(parseAnimation(parsedAnimation));
  20134. }
  20135. }
  20136. if (parsedCamera.autoAnimate) {
  20137. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20138. }
  20139. // Layer Mask
  20140. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20141. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20142. }
  20143. else {
  20144. camera.layerMask = 0xFFFFFFFF;
  20145. }
  20146. return camera;
  20147. };
  20148. var parseGeometry = function (parsedGeometry, scene) {
  20149. var id = parsedGeometry.id;
  20150. return scene.getGeometryByID(id);
  20151. };
  20152. var parseBox = function (parsedBox, scene) {
  20153. if (parseGeometry(parsedBox, scene)) {
  20154. return null; // null since geometry could be something else than a box...
  20155. }
  20156. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20157. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20158. scene.pushGeometry(box, true);
  20159. return box;
  20160. };
  20161. var parseSphere = function (parsedSphere, scene) {
  20162. if (parseGeometry(parsedSphere, scene)) {
  20163. return null; // null since geometry could be something else than a sphere...
  20164. }
  20165. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20166. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20167. scene.pushGeometry(sphere, true);
  20168. return sphere;
  20169. };
  20170. var parseCylinder = function (parsedCylinder, scene) {
  20171. if (parseGeometry(parsedCylinder, scene)) {
  20172. return null; // null since geometry could be something else than a cylinder...
  20173. }
  20174. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20175. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20176. scene.pushGeometry(cylinder, true);
  20177. return cylinder;
  20178. };
  20179. var parseTorus = function (parsedTorus, scene) {
  20180. if (parseGeometry(parsedTorus, scene)) {
  20181. return null; // null since geometry could be something else than a torus...
  20182. }
  20183. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20184. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20185. scene.pushGeometry(torus, true);
  20186. return torus;
  20187. };
  20188. var parseGround = function (parsedGround, scene) {
  20189. if (parseGeometry(parsedGround, scene)) {
  20190. return null; // null since geometry could be something else than a ground...
  20191. }
  20192. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20193. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20194. scene.pushGeometry(ground, true);
  20195. return ground;
  20196. };
  20197. var parsePlane = function (parsedPlane, scene) {
  20198. if (parseGeometry(parsedPlane, scene)) {
  20199. return null; // null since geometry could be something else than a plane...
  20200. }
  20201. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20202. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20203. scene.pushGeometry(plane, true);
  20204. return plane;
  20205. };
  20206. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20207. if (parseGeometry(parsedTorusKnot, scene)) {
  20208. return null; // null since geometry could be something else than a torusKnot...
  20209. }
  20210. 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);
  20211. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20212. scene.pushGeometry(torusKnot, true);
  20213. return torusKnot;
  20214. };
  20215. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20216. if (parseGeometry(parsedVertexData, scene)) {
  20217. return null; // null since geometry could be a primitive
  20218. }
  20219. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20220. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20221. if (parsedVertexData.delayLoadingFile) {
  20222. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20223. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20224. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20225. geometry._delayInfo = [];
  20226. if (parsedVertexData.hasUVs) {
  20227. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20228. }
  20229. if (parsedVertexData.hasUVs2) {
  20230. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20231. }
  20232. if (parsedVertexData.hasColors) {
  20233. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20234. }
  20235. if (parsedVertexData.hasMatricesIndices) {
  20236. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20237. }
  20238. if (parsedVertexData.hasMatricesWeights) {
  20239. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20240. }
  20241. geometry._delayLoadingFunction = importVertexData;
  20242. }
  20243. else {
  20244. importVertexData(parsedVertexData, geometry);
  20245. }
  20246. scene.pushGeometry(geometry, true);
  20247. return geometry;
  20248. };
  20249. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20250. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20251. mesh.id = parsedMesh.id;
  20252. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20253. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20254. if (parsedMesh.rotationQuaternion) {
  20255. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20256. }
  20257. else if (parsedMesh.rotation) {
  20258. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20259. }
  20260. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20261. if (parsedMesh.localMatrix) {
  20262. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20263. }
  20264. else if (parsedMesh.pivotMatrix) {
  20265. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20266. }
  20267. mesh.setEnabled(parsedMesh.isEnabled);
  20268. mesh.isVisible = parsedMesh.isVisible;
  20269. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20270. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20271. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20272. if (parsedMesh.applyFog !== undefined) {
  20273. mesh.applyFog = parsedMesh.applyFog;
  20274. }
  20275. if (parsedMesh.pickable !== undefined) {
  20276. mesh.isPickable = parsedMesh.pickable;
  20277. }
  20278. if (parsedMesh.alphaIndex !== undefined) {
  20279. mesh.alphaIndex = parsedMesh.alphaIndex;
  20280. }
  20281. mesh.receiveShadows = parsedMesh.receiveShadows;
  20282. mesh.billboardMode = parsedMesh.billboardMode;
  20283. if (parsedMesh.visibility !== undefined) {
  20284. mesh.visibility = parsedMesh.visibility;
  20285. }
  20286. mesh.checkCollisions = parsedMesh.checkCollisions;
  20287. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20288. // Parent
  20289. if (parsedMesh.parentId) {
  20290. mesh._waitingParentId = parsedMesh.parentId;
  20291. }
  20292. // Actions
  20293. if (parsedMesh.actions !== undefined) {
  20294. mesh._waitingActions = parsedMesh.actions;
  20295. }
  20296. // Geometry
  20297. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20298. if (parsedMesh.delayLoadingFile) {
  20299. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20300. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20301. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20302. if (parsedMesh._binaryInfo) {
  20303. mesh._binaryInfo = parsedMesh._binaryInfo;
  20304. }
  20305. mesh._delayInfo = [];
  20306. if (parsedMesh.hasUVs) {
  20307. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20308. }
  20309. if (parsedMesh.hasUVs2) {
  20310. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20311. }
  20312. if (parsedMesh.hasColors) {
  20313. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20314. }
  20315. if (parsedMesh.hasMatricesIndices) {
  20316. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20317. }
  20318. if (parsedMesh.hasMatricesWeights) {
  20319. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20320. }
  20321. mesh._delayLoadingFunction = importGeometry;
  20322. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20323. mesh._checkDelayState();
  20324. }
  20325. }
  20326. else {
  20327. importGeometry(parsedMesh, mesh);
  20328. }
  20329. // Material
  20330. if (parsedMesh.materialId) {
  20331. mesh.setMaterialByID(parsedMesh.materialId);
  20332. }
  20333. else {
  20334. mesh.material = null;
  20335. }
  20336. // Skeleton
  20337. if (parsedMesh.skeletonId > -1) {
  20338. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20339. }
  20340. // Physics
  20341. if (parsedMesh.physicsImpostor) {
  20342. if (!scene.isPhysicsEnabled()) {
  20343. scene.enablePhysics();
  20344. }
  20345. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20346. }
  20347. // Animations
  20348. if (parsedMesh.animations) {
  20349. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20350. var parsedAnimation = parsedMesh.animations[animationIndex];
  20351. mesh.animations.push(parseAnimation(parsedAnimation));
  20352. }
  20353. }
  20354. if (parsedMesh.autoAnimate) {
  20355. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20356. }
  20357. // Layer Mask
  20358. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20359. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20360. }
  20361. else {
  20362. mesh.layerMask = 0xFFFFFFFF;
  20363. }
  20364. // Instances
  20365. if (parsedMesh.instances) {
  20366. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20367. var parsedInstance = parsedMesh.instances[index];
  20368. var instance = mesh.createInstance(parsedInstance.name);
  20369. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20370. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20371. if (parsedInstance.rotationQuaternion) {
  20372. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20373. }
  20374. else if (parsedInstance.rotation) {
  20375. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20376. }
  20377. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20378. instance.checkCollisions = mesh.checkCollisions;
  20379. if (parsedMesh.animations) {
  20380. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20381. parsedAnimation = parsedMesh.animations[animationIndex];
  20382. instance.animations.push(parseAnimation(parsedAnimation));
  20383. }
  20384. }
  20385. }
  20386. }
  20387. return mesh;
  20388. };
  20389. var parseActions = function (parsedActions, object, scene) {
  20390. var actionManager = new BABYLON.ActionManager(scene);
  20391. if (object === null)
  20392. scene.actionManager = actionManager;
  20393. else
  20394. object.actionManager = actionManager;
  20395. // instanciate a new object
  20396. var instanciate = function (name, params) {
  20397. var newInstance = Object.create(BABYLON[name].prototype);
  20398. newInstance.constructor.apply(newInstance, params);
  20399. return newInstance;
  20400. };
  20401. var parseParameter = function (name, value, target, propertyPath) {
  20402. if (propertyPath === null) {
  20403. // String, boolean or float
  20404. var floatValue = parseFloat(value);
  20405. if (value === "true" || value === "false")
  20406. return value === "true";
  20407. else
  20408. return isNaN(floatValue) ? value : floatValue;
  20409. }
  20410. var effectiveTarget = propertyPath.split(".");
  20411. var values = value.split(",");
  20412. for (var i = 0; i < effectiveTarget.length; i++) {
  20413. target = target[effectiveTarget[i]];
  20414. }
  20415. // Return appropriate value with its type
  20416. if (typeof (target) === "boolean")
  20417. return values[0] === "true";
  20418. if (typeof (target) === "string")
  20419. return values[0];
  20420. // Parameters with multiple values such as Vector3 etc.
  20421. var split = new Array();
  20422. for (var i = 0; i < values.length; i++)
  20423. split.push(parseFloat(values[i]));
  20424. if (target instanceof BABYLON.Vector3)
  20425. return BABYLON.Vector3.FromArray(split);
  20426. if (target instanceof BABYLON.Vector4)
  20427. return BABYLON.Vector4.FromArray(split);
  20428. if (target instanceof BABYLON.Color3)
  20429. return BABYLON.Color3.FromArray(split);
  20430. if (target instanceof BABYLON.Color4)
  20431. return BABYLON.Color4.FromArray(split);
  20432. return parseFloat(values[0]);
  20433. };
  20434. // traverse graph per trigger
  20435. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20436. if (combineArray === void 0) { combineArray = null; }
  20437. if (parsedAction.detached)
  20438. return;
  20439. var parameters = new Array();
  20440. var target = null;
  20441. var propertyPath = null;
  20442. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20443. // Parameters
  20444. if (parsedAction.type === 2)
  20445. parameters.push(actionManager);
  20446. else
  20447. parameters.push(trigger);
  20448. if (combine) {
  20449. var actions = new Array();
  20450. for (var j = 0; j < parsedAction.combine.length; j++) {
  20451. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20452. }
  20453. parameters.push(actions);
  20454. }
  20455. else {
  20456. for (var i = 0; i < parsedAction.properties.length; i++) {
  20457. var value = parsedAction.properties[i].value;
  20458. var name = parsedAction.properties[i].name;
  20459. var targetType = parsedAction.properties[i].targetType;
  20460. if (name === "target")
  20461. if (targetType !== null && targetType === "SceneProperties")
  20462. value = target = scene;
  20463. else
  20464. value = target = scene.getNodeByName(value);
  20465. else if (name === "parent")
  20466. value = scene.getNodeByName(value);
  20467. else if (name === "sound")
  20468. value = scene.getSoundByName(value);
  20469. else if (name !== "propertyPath") {
  20470. if (parsedAction.type === 2 && name === "operator")
  20471. value = BABYLON.ValueCondition[value];
  20472. else
  20473. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20474. }
  20475. else {
  20476. propertyPath = value;
  20477. }
  20478. parameters.push(value);
  20479. }
  20480. }
  20481. if (combineArray === null) {
  20482. parameters.push(condition);
  20483. }
  20484. else {
  20485. parameters.push(null);
  20486. }
  20487. // If interpolate value action
  20488. if (parsedAction.name === "InterpolateValueAction") {
  20489. var param = parameters[parameters.length - 2];
  20490. parameters[parameters.length - 1] = param;
  20491. parameters[parameters.length - 2] = condition;
  20492. }
  20493. // Action or condition(s) and not CombineAction
  20494. var newAction = instanciate(parsedAction.name, parameters);
  20495. if (combineArray === null) {
  20496. if (newAction instanceof BABYLON.Condition) {
  20497. condition = newAction;
  20498. newAction = action;
  20499. }
  20500. else {
  20501. condition = null;
  20502. if (action)
  20503. action.then(newAction);
  20504. else
  20505. actionManager.registerAction(newAction);
  20506. }
  20507. }
  20508. else {
  20509. combineArray.push(newAction);
  20510. }
  20511. for (var i = 0; i < parsedAction.children.length; i++)
  20512. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20513. };
  20514. for (var i = 0; i < parsedActions.children.length; i++) {
  20515. var triggerParams;
  20516. var trigger = parsedActions.children[i];
  20517. if (trigger.properties.length > 0) {
  20518. var param = trigger.properties[0].value;
  20519. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20520. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20521. }
  20522. else
  20523. triggerParams = BABYLON.ActionManager[trigger.name];
  20524. for (var j = 0; j < trigger.children.length; j++) {
  20525. if (!trigger.detached)
  20526. traverse(trigger.children[j], triggerParams, null, null);
  20527. }
  20528. }
  20529. };
  20530. var parseSound = function (parsedSound, scene, rootUrl) {
  20531. var soundName = parsedSound.name;
  20532. var soundUrl = rootUrl + soundName;
  20533. var options = {
  20534. autoplay: parsedSound.autoplay,
  20535. loop: parsedSound.loop,
  20536. volume: parsedSound.volume,
  20537. spatialSound: parsedSound.spatialSound,
  20538. maxDistance: parsedSound.maxDistance,
  20539. rolloffFactor: parsedSound.rolloffFactor,
  20540. refDistance: parsedSound.refDistance,
  20541. distanceModel: parsedSound.distanceModel,
  20542. playbackRate: parsedSound.playbackRate
  20543. };
  20544. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20545. scene._removePendingData(newSound);
  20546. }, options);
  20547. scene._addPendingData(newSound);
  20548. if (parsedSound.position) {
  20549. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20550. newSound.setPosition(soundPosition);
  20551. }
  20552. if (parsedSound.isDirectional) {
  20553. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20554. if (parsedSound.localDirectionToMesh) {
  20555. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20556. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20557. }
  20558. }
  20559. if (parsedSound.connectedMeshId) {
  20560. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20561. if (connectedMesh) {
  20562. newSound.attachToMesh(connectedMesh);
  20563. }
  20564. }
  20565. };
  20566. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20567. names = (names instanceof Array) ? names : [names];
  20568. for (var i in names) {
  20569. if (mesh.name === names[i]) {
  20570. hierarchyIds.push(mesh.id);
  20571. return true;
  20572. }
  20573. }
  20574. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20575. hierarchyIds.push(mesh.id);
  20576. return true;
  20577. }
  20578. return false;
  20579. };
  20580. var importVertexData = function (parsedVertexData, geometry) {
  20581. var vertexData = new BABYLON.VertexData();
  20582. // positions
  20583. var positions = parsedVertexData.positions;
  20584. if (positions) {
  20585. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20586. }
  20587. // normals
  20588. var normals = parsedVertexData.normals;
  20589. if (normals) {
  20590. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20591. }
  20592. // uvs
  20593. var uvs = parsedVertexData.uvs;
  20594. if (uvs) {
  20595. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20596. }
  20597. // uv2s
  20598. var uv2s = parsedVertexData.uv2s;
  20599. if (uv2s) {
  20600. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20601. }
  20602. // colors
  20603. var colors = parsedVertexData.colors;
  20604. if (colors) {
  20605. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20606. }
  20607. // matricesIndices
  20608. var matricesIndices = parsedVertexData.matricesIndices;
  20609. if (matricesIndices) {
  20610. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20611. }
  20612. // matricesWeights
  20613. var matricesWeights = parsedVertexData.matricesWeights;
  20614. if (matricesWeights) {
  20615. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20616. }
  20617. // indices
  20618. var indices = parsedVertexData.indices;
  20619. if (indices) {
  20620. vertexData.indices = indices;
  20621. }
  20622. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20623. };
  20624. var importGeometry = function (parsedGeometry, mesh) {
  20625. var scene = mesh.getScene();
  20626. // Geometry
  20627. var geometryId = parsedGeometry.geometryId;
  20628. if (geometryId) {
  20629. var geometry = scene.getGeometryByID(geometryId);
  20630. if (geometry) {
  20631. geometry.applyToMesh(mesh);
  20632. }
  20633. }
  20634. else if (parsedGeometry instanceof ArrayBuffer) {
  20635. var binaryInfo = mesh._binaryInfo;
  20636. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20637. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20638. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20639. }
  20640. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20641. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20642. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20643. }
  20644. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20645. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20646. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20647. }
  20648. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20649. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20650. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20651. }
  20652. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20653. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20654. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20655. }
  20656. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20657. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20658. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20659. }
  20660. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20661. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20662. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20663. }
  20664. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20665. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20666. mesh.setIndices(indicesData);
  20667. }
  20668. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20669. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20670. mesh.subMeshes = [];
  20671. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20672. var materialIndex = subMeshesData[(i * 5) + 0];
  20673. var verticesStart = subMeshesData[(i * 5) + 1];
  20674. var verticesCount = subMeshesData[(i * 5) + 2];
  20675. var indexStart = subMeshesData[(i * 5) + 3];
  20676. var indexCount = subMeshesData[(i * 5) + 4];
  20677. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20678. }
  20679. }
  20680. }
  20681. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20682. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20683. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20684. if (parsedGeometry.uvs) {
  20685. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20686. }
  20687. if (parsedGeometry.uvs2) {
  20688. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20689. }
  20690. if (parsedGeometry.colors) {
  20691. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20692. }
  20693. if (parsedGeometry.matricesIndices) {
  20694. if (!parsedGeometry.matricesIndices._isExpanded) {
  20695. var floatIndices = [];
  20696. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20697. var matricesIndex = parsedGeometry.matricesIndices[i];
  20698. floatIndices.push(matricesIndex & 0x000000FF);
  20699. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20700. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20701. floatIndices.push(matricesIndex >> 24);
  20702. }
  20703. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20704. }
  20705. else {
  20706. delete parsedGeometry.matricesIndices._isExpanded;
  20707. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20708. }
  20709. }
  20710. if (parsedGeometry.matricesWeights) {
  20711. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20712. }
  20713. mesh.setIndices(parsedGeometry.indices);
  20714. // SubMeshes
  20715. if (parsedGeometry.subMeshes) {
  20716. mesh.subMeshes = [];
  20717. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20718. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20719. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20720. }
  20721. }
  20722. }
  20723. // Flat shading
  20724. if (mesh._shouldGenerateFlatShading) {
  20725. mesh.convertToFlatShadedMesh();
  20726. delete mesh._shouldGenerateFlatShading;
  20727. }
  20728. // Update
  20729. mesh.computeWorldMatrix(true);
  20730. // Octree
  20731. if (scene._selectionOctree) {
  20732. scene._selectionOctree.addMesh(mesh);
  20733. }
  20734. };
  20735. BABYLON.SceneLoader.RegisterPlugin({
  20736. extensions: ".babylon",
  20737. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20738. var parsedData = JSON.parse(data);
  20739. var loadedSkeletonsIds = [];
  20740. var loadedMaterialsIds = [];
  20741. var hierarchyIds = [];
  20742. for (var index = 0; index < parsedData.meshes.length; index++) {
  20743. var parsedMesh = parsedData.meshes[index];
  20744. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20745. if (meshesNames instanceof Array) {
  20746. // Remove found mesh name from list.
  20747. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20748. }
  20749. // Material ?
  20750. if (parsedMesh.materialId) {
  20751. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20752. if (!materialFound) {
  20753. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20754. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20755. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20756. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20757. var subMatId = parsedMultiMaterial.materials[matIndex];
  20758. loadedMaterialsIds.push(subMatId);
  20759. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20760. }
  20761. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20762. parseMultiMaterial(parsedMultiMaterial, scene);
  20763. materialFound = true;
  20764. break;
  20765. }
  20766. }
  20767. }
  20768. if (!materialFound) {
  20769. loadedMaterialsIds.push(parsedMesh.materialId);
  20770. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20771. }
  20772. }
  20773. // Skeleton ?
  20774. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20775. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20776. if (!skeletonAlreadyLoaded) {
  20777. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20778. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20779. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20780. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20781. loadedSkeletonsIds.push(parsedSkeleton.id);
  20782. }
  20783. }
  20784. }
  20785. }
  20786. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20787. meshes.push(mesh);
  20788. }
  20789. }
  20790. for (index = 0; index < scene.meshes.length; index++) {
  20791. var currentMesh = scene.meshes[index];
  20792. if (currentMesh._waitingParentId) {
  20793. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20794. currentMesh._waitingParentId = undefined;
  20795. }
  20796. }
  20797. // Particles
  20798. if (parsedData.particleSystems) {
  20799. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20800. var parsedParticleSystem = parsedData.particleSystems[index];
  20801. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20802. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20803. }
  20804. }
  20805. }
  20806. return true;
  20807. },
  20808. load: function (scene, data, rootUrl) {
  20809. var parsedData = JSON.parse(data);
  20810. // Scene
  20811. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20812. scene.autoClear = parsedData.autoClear;
  20813. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20814. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20815. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20816. // Fog
  20817. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20818. scene.fogMode = parsedData.fogMode;
  20819. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20820. scene.fogStart = parsedData.fogStart;
  20821. scene.fogEnd = parsedData.fogEnd;
  20822. scene.fogDensity = parsedData.fogDensity;
  20823. }
  20824. for (var index = 0; index < parsedData.lights.length; index++) {
  20825. var parsedLight = parsedData.lights[index];
  20826. parseLight(parsedLight, scene);
  20827. }
  20828. // Materials
  20829. if (parsedData.materials) {
  20830. for (index = 0; index < parsedData.materials.length; index++) {
  20831. var parsedMaterial = parsedData.materials[index];
  20832. parseMaterial(parsedMaterial, scene, rootUrl);
  20833. }
  20834. }
  20835. if (parsedData.multiMaterials) {
  20836. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20837. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20838. parseMultiMaterial(parsedMultiMaterial, scene);
  20839. }
  20840. }
  20841. // Skeletons
  20842. if (parsedData.skeletons) {
  20843. for (index = 0; index < parsedData.skeletons.length; index++) {
  20844. var parsedSkeleton = parsedData.skeletons[index];
  20845. parseSkeleton(parsedSkeleton, scene);
  20846. }
  20847. }
  20848. // Geometries
  20849. var geometries = parsedData.geometries;
  20850. if (geometries) {
  20851. // Boxes
  20852. var boxes = geometries.boxes;
  20853. if (boxes) {
  20854. for (index = 0; index < boxes.length; index++) {
  20855. var parsedBox = boxes[index];
  20856. parseBox(parsedBox, scene);
  20857. }
  20858. }
  20859. // Spheres
  20860. var spheres = geometries.spheres;
  20861. if (spheres) {
  20862. for (index = 0; index < spheres.length; index++) {
  20863. var parsedSphere = spheres[index];
  20864. parseSphere(parsedSphere, scene);
  20865. }
  20866. }
  20867. // Cylinders
  20868. var cylinders = geometries.cylinders;
  20869. if (cylinders) {
  20870. for (index = 0; index < cylinders.length; index++) {
  20871. var parsedCylinder = cylinders[index];
  20872. parseCylinder(parsedCylinder, scene);
  20873. }
  20874. }
  20875. // Toruses
  20876. var toruses = geometries.toruses;
  20877. if (toruses) {
  20878. for (index = 0; index < toruses.length; index++) {
  20879. var parsedTorus = toruses[index];
  20880. parseTorus(parsedTorus, scene);
  20881. }
  20882. }
  20883. // Grounds
  20884. var grounds = geometries.grounds;
  20885. if (grounds) {
  20886. for (index = 0; index < grounds.length; index++) {
  20887. var parsedGround = grounds[index];
  20888. parseGround(parsedGround, scene);
  20889. }
  20890. }
  20891. // Planes
  20892. var planes = geometries.planes;
  20893. if (planes) {
  20894. for (index = 0; index < planes.length; index++) {
  20895. var parsedPlane = planes[index];
  20896. parsePlane(parsedPlane, scene);
  20897. }
  20898. }
  20899. // TorusKnots
  20900. var torusKnots = geometries.torusKnots;
  20901. if (torusKnots) {
  20902. for (index = 0; index < torusKnots.length; index++) {
  20903. var parsedTorusKnot = torusKnots[index];
  20904. parseTorusKnot(parsedTorusKnot, scene);
  20905. }
  20906. }
  20907. // VertexData
  20908. var vertexData = geometries.vertexData;
  20909. if (vertexData) {
  20910. for (index = 0; index < vertexData.length; index++) {
  20911. var parsedVertexData = vertexData[index];
  20912. parseVertexData(parsedVertexData, scene, rootUrl);
  20913. }
  20914. }
  20915. }
  20916. for (index = 0; index < parsedData.meshes.length; index++) {
  20917. var parsedMesh = parsedData.meshes[index];
  20918. parseMesh(parsedMesh, scene, rootUrl);
  20919. }
  20920. for (index = 0; index < parsedData.cameras.length; index++) {
  20921. var parsedCamera = parsedData.cameras[index];
  20922. parseCamera(parsedCamera, scene);
  20923. }
  20924. if (parsedData.activeCameraID) {
  20925. scene.setActiveCameraByID(parsedData.activeCameraID);
  20926. }
  20927. for (index = 0; index < scene.cameras.length; index++) {
  20928. var camera = scene.cameras[index];
  20929. if (camera._waitingParentId) {
  20930. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20931. camera._waitingParentId = undefined;
  20932. }
  20933. }
  20934. for (index = 0; index < scene.lights.length; index++) {
  20935. var light = scene.lights[index];
  20936. if (light._waitingParentId) {
  20937. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20938. light._waitingParentId = undefined;
  20939. }
  20940. }
  20941. // Sounds
  20942. if (parsedData.sounds) {
  20943. for (index = 0; index < parsedData.sounds.length; index++) {
  20944. var parsedSound = parsedData.sounds[index];
  20945. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20946. parseSound(parsedSound, scene, rootUrl);
  20947. }
  20948. else {
  20949. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20950. }
  20951. }
  20952. }
  20953. for (index = 0; index < scene.meshes.length; index++) {
  20954. var mesh = scene.meshes[index];
  20955. if (mesh._waitingParentId) {
  20956. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20957. mesh._waitingParentId = undefined;
  20958. }
  20959. if (mesh._waitingActions) {
  20960. parseActions(mesh._waitingActions, mesh, scene);
  20961. mesh._waitingActions = undefined;
  20962. }
  20963. }
  20964. // Particles Systems
  20965. if (parsedData.particleSystems) {
  20966. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20967. var parsedParticleSystem = parsedData.particleSystems[index];
  20968. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20969. }
  20970. }
  20971. // Lens flares
  20972. if (parsedData.lensFlareSystems) {
  20973. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20974. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20975. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20976. }
  20977. }
  20978. // Shadows
  20979. if (parsedData.shadowGenerators) {
  20980. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20981. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20982. parseShadowGenerator(parsedShadowGenerator, scene);
  20983. }
  20984. }
  20985. // Actions (scene)
  20986. if (parsedData.actions) {
  20987. parseActions(parsedData.actions, null, scene);
  20988. }
  20989. // Finish
  20990. return true;
  20991. }
  20992. });
  20993. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20994. })(BABYLON || (BABYLON = {}));
  20995. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20996. (function (BABYLON) {
  20997. // Unique ID when we import meshes from Babylon to CSG
  20998. var currentCSGMeshId = 0;
  20999. // # class Vertex
  21000. // Represents a vertex of a polygon. Use your own vertex class instead of this
  21001. // one to provide additional features like texture coordinates and vertex
  21002. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  21003. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  21004. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  21005. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  21006. // is not used anywhere else.
  21007. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  21008. var Vertex = (function () {
  21009. function Vertex(pos, normal, uv) {
  21010. this.pos = pos;
  21011. this.normal = normal;
  21012. this.uv = uv;
  21013. }
  21014. Vertex.prototype.clone = function () {
  21015. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  21016. };
  21017. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  21018. // orientation of a polygon is flipped.
  21019. Vertex.prototype.flip = function () {
  21020. this.normal = this.normal.scale(-1);
  21021. };
  21022. // Create a new vertex between this vertex and `other` by linearly
  21023. // interpolating all properties using a parameter of `t`. Subclasses should
  21024. // override this to interpolate additional properties.
  21025. Vertex.prototype.interpolate = function (other, t) {
  21026. 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));
  21027. };
  21028. return Vertex;
  21029. })();
  21030. // # class Plane
  21031. // Represents a plane in 3D space.
  21032. var Plane = (function () {
  21033. function Plane(normal, w) {
  21034. this.normal = normal;
  21035. this.w = w;
  21036. }
  21037. Plane.FromPoints = function (a, b, c) {
  21038. var v0 = c.subtract(a);
  21039. var v1 = b.subtract(a);
  21040. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  21041. return null;
  21042. }
  21043. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  21044. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  21045. };
  21046. Plane.prototype.clone = function () {
  21047. return new Plane(this.normal.clone(), this.w);
  21048. };
  21049. Plane.prototype.flip = function () {
  21050. this.normal.scaleInPlace(-1);
  21051. this.w = -this.w;
  21052. };
  21053. // Split `polygon` by this plane if needed, then put the polygon or polygon
  21054. // fragments in the appropriate lists. Coplanar polygons go into either
  21055. // `coplanarFront` or `coplanarBack` depending on their orientation with
  21056. // respect to this plane. Polygons in front or in back of this plane go into
  21057. // either `front` or `back`.
  21058. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  21059. var COPLANAR = 0;
  21060. var FRONT = 1;
  21061. var BACK = 2;
  21062. var SPANNING = 3;
  21063. // Classify each point as well as the entire polygon into one of the above
  21064. // four classes.
  21065. var polygonType = 0;
  21066. var types = [];
  21067. for (var i = 0; i < polygon.vertices.length; i++) {
  21068. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  21069. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  21070. polygonType |= type;
  21071. types.push(type);
  21072. }
  21073. switch (polygonType) {
  21074. case COPLANAR:
  21075. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  21076. break;
  21077. case FRONT:
  21078. front.push(polygon);
  21079. break;
  21080. case BACK:
  21081. back.push(polygon);
  21082. break;
  21083. case SPANNING:
  21084. var f = [], b = [];
  21085. for (i = 0; i < polygon.vertices.length; i++) {
  21086. var j = (i + 1) % polygon.vertices.length;
  21087. var ti = types[i], tj = types[j];
  21088. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  21089. if (ti != BACK)
  21090. f.push(vi);
  21091. if (ti != FRONT)
  21092. b.push(ti != BACK ? vi.clone() : vi);
  21093. if ((ti | tj) == SPANNING) {
  21094. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  21095. var v = vi.interpolate(vj, t);
  21096. f.push(v);
  21097. b.push(v.clone());
  21098. }
  21099. }
  21100. if (f.length >= 3) {
  21101. var poly = new Polygon(f, polygon.shared);
  21102. if (poly.plane)
  21103. front.push(poly);
  21104. }
  21105. if (b.length >= 3) {
  21106. poly = new Polygon(b, polygon.shared);
  21107. if (poly.plane)
  21108. back.push(poly);
  21109. }
  21110. break;
  21111. }
  21112. };
  21113. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  21114. // point is on the plane.
  21115. Plane.EPSILON = 1e-5;
  21116. return Plane;
  21117. })();
  21118. // # class Polygon
  21119. // Represents a convex polygon. The vertices used to initialize a polygon must
  21120. // be coplanar and form a convex loop.
  21121. //
  21122. // Each convex polygon has a `shared` property, which is shared between all
  21123. // polygons that are clones of each other or were split from the same polygon.
  21124. // This can be used to define per-polygon properties (such as surface color).
  21125. var Polygon = (function () {
  21126. function Polygon(vertices, shared) {
  21127. this.vertices = vertices;
  21128. this.shared = shared;
  21129. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  21130. }
  21131. Polygon.prototype.clone = function () {
  21132. var vertices = this.vertices.map(function (v) { return v.clone(); });
  21133. return new Polygon(vertices, this.shared);
  21134. };
  21135. Polygon.prototype.flip = function () {
  21136. this.vertices.reverse().map(function (v) {
  21137. v.flip();
  21138. });
  21139. this.plane.flip();
  21140. };
  21141. return Polygon;
  21142. })();
  21143. // # class Node
  21144. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  21145. // by picking a polygon to split along. That polygon (and all other coplanar
  21146. // polygons) are added directly to that node and the other polygons are added to
  21147. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  21148. // no distinction between internal and leaf nodes.
  21149. var Node = (function () {
  21150. function Node(polygons) {
  21151. this.plane = null;
  21152. this.front = null;
  21153. this.back = null;
  21154. this.polygons = [];
  21155. if (polygons) {
  21156. this.build(polygons);
  21157. }
  21158. }
  21159. Node.prototype.clone = function () {
  21160. var node = new Node();
  21161. node.plane = this.plane && this.plane.clone();
  21162. node.front = this.front && this.front.clone();
  21163. node.back = this.back && this.back.clone();
  21164. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  21165. return node;
  21166. };
  21167. // Convert solid space to empty space and empty space to solid space.
  21168. Node.prototype.invert = function () {
  21169. for (var i = 0; i < this.polygons.length; i++) {
  21170. this.polygons[i].flip();
  21171. }
  21172. if (this.plane) {
  21173. this.plane.flip();
  21174. }
  21175. if (this.front) {
  21176. this.front.invert();
  21177. }
  21178. if (this.back) {
  21179. this.back.invert();
  21180. }
  21181. var temp = this.front;
  21182. this.front = this.back;
  21183. this.back = temp;
  21184. };
  21185. // Recursively remove all polygons in `polygons` that are inside this BSP
  21186. // tree.
  21187. Node.prototype.clipPolygons = function (polygons) {
  21188. if (!this.plane)
  21189. return polygons.slice();
  21190. var front = [], back = [];
  21191. for (var i = 0; i < polygons.length; i++) {
  21192. this.plane.splitPolygon(polygons[i], front, back, front, back);
  21193. }
  21194. if (this.front) {
  21195. front = this.front.clipPolygons(front);
  21196. }
  21197. if (this.back) {
  21198. back = this.back.clipPolygons(back);
  21199. }
  21200. else {
  21201. back = [];
  21202. }
  21203. return front.concat(back);
  21204. };
  21205. // Remove all polygons in this BSP tree that are inside the other BSP tree
  21206. // `bsp`.
  21207. Node.prototype.clipTo = function (bsp) {
  21208. this.polygons = bsp.clipPolygons(this.polygons);
  21209. if (this.front)
  21210. this.front.clipTo(bsp);
  21211. if (this.back)
  21212. this.back.clipTo(bsp);
  21213. };
  21214. // Return a list of all polygons in this BSP tree.
  21215. Node.prototype.allPolygons = function () {
  21216. var polygons = this.polygons.slice();
  21217. if (this.front)
  21218. polygons = polygons.concat(this.front.allPolygons());
  21219. if (this.back)
  21220. polygons = polygons.concat(this.back.allPolygons());
  21221. return polygons;
  21222. };
  21223. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  21224. // new polygons are filtered down to the bottom of the tree and become new
  21225. // nodes there. Each set of polygons is partitioned using the first polygon
  21226. // (no heuristic is used to pick a good split).
  21227. Node.prototype.build = function (polygons) {
  21228. if (!polygons.length)
  21229. return;
  21230. if (!this.plane)
  21231. this.plane = polygons[0].plane.clone();
  21232. var front = [], back = [];
  21233. for (var i = 0; i < polygons.length; i++) {
  21234. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  21235. }
  21236. if (front.length) {
  21237. if (!this.front)
  21238. this.front = new Node();
  21239. this.front.build(front);
  21240. }
  21241. if (back.length) {
  21242. if (!this.back)
  21243. this.back = new Node();
  21244. this.back.build(back);
  21245. }
  21246. };
  21247. return Node;
  21248. })();
  21249. var CSG = (function () {
  21250. function CSG() {
  21251. this.polygons = new Array();
  21252. }
  21253. // Convert BABYLON.Mesh to BABYLON.CSG
  21254. CSG.FromMesh = function (mesh) {
  21255. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21256. if (mesh instanceof BABYLON.Mesh) {
  21257. mesh.computeWorldMatrix(true);
  21258. var matrix = mesh.getWorldMatrix();
  21259. var meshPosition = mesh.position.clone();
  21260. var meshRotation = mesh.rotation.clone();
  21261. var meshScaling = mesh.scaling.clone();
  21262. }
  21263. else {
  21264. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21265. }
  21266. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21267. var subMeshes = mesh.subMeshes;
  21268. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21269. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21270. vertices = [];
  21271. for (var j = 0; j < 3; j++) {
  21272. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21273. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21274. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21275. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21276. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21277. vertex = new Vertex(position, normal, uv);
  21278. vertices.push(vertex);
  21279. }
  21280. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21281. // To handle the case of degenerated triangle
  21282. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21283. if (polygon.plane)
  21284. polygons.push(polygon);
  21285. }
  21286. }
  21287. var csg = CSG.FromPolygons(polygons);
  21288. csg.matrix = matrix;
  21289. csg.position = meshPosition;
  21290. csg.rotation = meshRotation;
  21291. csg.scaling = meshScaling;
  21292. currentCSGMeshId++;
  21293. return csg;
  21294. };
  21295. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21296. CSG.FromPolygons = function (polygons) {
  21297. var csg = new BABYLON.CSG();
  21298. csg.polygons = polygons;
  21299. return csg;
  21300. };
  21301. CSG.prototype.clone = function () {
  21302. var csg = new BABYLON.CSG();
  21303. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21304. csg.copyTransformAttributes(this);
  21305. return csg;
  21306. };
  21307. CSG.prototype.toPolygons = function () {
  21308. return this.polygons;
  21309. };
  21310. CSG.prototype.union = function (csg) {
  21311. var a = new Node(this.clone().polygons);
  21312. var b = new Node(csg.clone().polygons);
  21313. a.clipTo(b);
  21314. b.clipTo(a);
  21315. b.invert();
  21316. b.clipTo(a);
  21317. b.invert();
  21318. a.build(b.allPolygons());
  21319. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21320. };
  21321. CSG.prototype.unionInPlace = function (csg) {
  21322. var a = new Node(this.polygons);
  21323. var b = new Node(csg.polygons);
  21324. a.clipTo(b);
  21325. b.clipTo(a);
  21326. b.invert();
  21327. b.clipTo(a);
  21328. b.invert();
  21329. a.build(b.allPolygons());
  21330. this.polygons = a.allPolygons();
  21331. };
  21332. CSG.prototype.subtract = function (csg) {
  21333. var a = new Node(this.clone().polygons);
  21334. var b = new Node(csg.clone().polygons);
  21335. a.invert();
  21336. a.clipTo(b);
  21337. b.clipTo(a);
  21338. b.invert();
  21339. b.clipTo(a);
  21340. b.invert();
  21341. a.build(b.allPolygons());
  21342. a.invert();
  21343. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21344. };
  21345. CSG.prototype.subtractInPlace = function (csg) {
  21346. var a = new Node(this.polygons);
  21347. var b = new Node(csg.polygons);
  21348. a.invert();
  21349. a.clipTo(b);
  21350. b.clipTo(a);
  21351. b.invert();
  21352. b.clipTo(a);
  21353. b.invert();
  21354. a.build(b.allPolygons());
  21355. a.invert();
  21356. this.polygons = a.allPolygons();
  21357. };
  21358. CSG.prototype.intersect = function (csg) {
  21359. var a = new Node(this.clone().polygons);
  21360. var b = new Node(csg.clone().polygons);
  21361. a.invert();
  21362. b.clipTo(a);
  21363. b.invert();
  21364. a.clipTo(b);
  21365. b.clipTo(a);
  21366. a.build(b.allPolygons());
  21367. a.invert();
  21368. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21369. };
  21370. CSG.prototype.intersectInPlace = function (csg) {
  21371. var a = new Node(this.polygons);
  21372. var b = new Node(csg.polygons);
  21373. a.invert();
  21374. b.clipTo(a);
  21375. b.invert();
  21376. a.clipTo(b);
  21377. b.clipTo(a);
  21378. a.build(b.allPolygons());
  21379. a.invert();
  21380. this.polygons = a.allPolygons();
  21381. };
  21382. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21383. // not modified.
  21384. CSG.prototype.inverse = function () {
  21385. var csg = this.clone();
  21386. csg.inverseInPlace();
  21387. return csg;
  21388. };
  21389. CSG.prototype.inverseInPlace = function () {
  21390. this.polygons.map(function (p) {
  21391. p.flip();
  21392. });
  21393. };
  21394. // This is used to keep meshes transformations so they can be restored
  21395. // when we build back a Babylon Mesh
  21396. // NB : All CSG operations are performed in world coordinates
  21397. CSG.prototype.copyTransformAttributes = function (csg) {
  21398. this.matrix = csg.matrix;
  21399. this.position = csg.position;
  21400. this.rotation = csg.rotation;
  21401. this.scaling = csg.scaling;
  21402. return this;
  21403. };
  21404. // Build Raw mesh from CSG
  21405. // Coordinates here are in world space
  21406. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21407. var matrix = this.matrix.clone();
  21408. matrix.invert();
  21409. 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;
  21410. if (keepSubMeshes) {
  21411. // Sort Polygons, since subMeshes are indices range
  21412. polygons.sort(function (a, b) {
  21413. if (a.shared.meshId === b.shared.meshId) {
  21414. return a.shared.subMeshId - b.shared.subMeshId;
  21415. }
  21416. else {
  21417. return a.shared.meshId - b.shared.meshId;
  21418. }
  21419. });
  21420. }
  21421. for (var i = 0, il = polygons.length; i < il; i++) {
  21422. polygon = polygons[i];
  21423. // Building SubMeshes
  21424. if (!subMesh_dict[polygon.shared.meshId]) {
  21425. subMesh_dict[polygon.shared.meshId] = {};
  21426. }
  21427. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21428. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21429. indexStart: +Infinity,
  21430. indexEnd: -Infinity,
  21431. materialIndex: polygon.shared.materialIndex
  21432. };
  21433. }
  21434. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21435. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21436. polygonIndices[0] = 0;
  21437. polygonIndices[1] = j - 1;
  21438. polygonIndices[2] = j;
  21439. for (var k = 0; k < 3; k++) {
  21440. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21441. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21442. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21443. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21444. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21445. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21446. // Check if 2 points can be merged
  21447. 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)) {
  21448. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21449. uvs.push(uv.x, uv.y);
  21450. normals.push(normal.x, normal.y, normal.z);
  21451. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21452. }
  21453. indices.push(vertex_idx);
  21454. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21455. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21456. currentIndex++;
  21457. }
  21458. }
  21459. }
  21460. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21461. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21462. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21463. mesh.setIndices(indices);
  21464. if (keepSubMeshes) {
  21465. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21466. var materialIndexOffset = 0, materialMaxIndex;
  21467. mesh.subMeshes.length = 0;
  21468. for (var m in subMesh_dict) {
  21469. materialMaxIndex = -1;
  21470. for (var sm in subMesh_dict[m]) {
  21471. subMesh_obj = subMesh_dict[m][sm];
  21472. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21473. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21474. }
  21475. materialIndexOffset += ++materialMaxIndex;
  21476. }
  21477. }
  21478. return mesh;
  21479. };
  21480. // Build Mesh from CSG taking material and transforms into account
  21481. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21482. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21483. mesh.material = material;
  21484. mesh.position.copyFrom(this.position);
  21485. mesh.rotation.copyFrom(this.rotation);
  21486. mesh.scaling.copyFrom(this.scaling);
  21487. mesh.computeWorldMatrix(true);
  21488. return mesh;
  21489. };
  21490. return CSG;
  21491. })();
  21492. BABYLON.CSG = CSG;
  21493. })(BABYLON || (BABYLON = {}));
  21494. //# sourceMappingURL=babylon.csg.js.map
  21495. var BABYLON;
  21496. (function (BABYLON) {
  21497. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21498. __extends(OculusDistortionCorrectionPostProcess, _super);
  21499. //ANY
  21500. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21501. var _this = this;
  21502. _super.call(this, name, "oculusDistortionCorrection", [
  21503. 'LensCenter',
  21504. 'Scale',
  21505. 'ScaleIn',
  21506. 'HmdWarpParam'
  21507. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21508. this._isRightEye = isRightEye;
  21509. this._distortionFactors = cameraSettings.DistortionK;
  21510. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21511. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21512. this.onSizeChanged = function () {
  21513. _this.aspectRatio = _this.width * .5 / _this.height;
  21514. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21515. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21516. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21517. };
  21518. this.onApply = function (effect) {
  21519. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21520. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21521. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21522. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21523. };
  21524. }
  21525. return OculusDistortionCorrectionPostProcess;
  21526. })(BABYLON.PostProcess);
  21527. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21528. })(BABYLON || (BABYLON = {}));
  21529. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21530. // 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
  21531. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21532. var BABYLON;
  21533. (function (BABYLON) {
  21534. (function (JoystickAxis) {
  21535. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21536. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21537. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21538. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21539. var JoystickAxis = BABYLON.JoystickAxis;
  21540. var VirtualJoystick = (function () {
  21541. function VirtualJoystick(leftJoystick) {
  21542. var _this = this;
  21543. if (leftJoystick) {
  21544. this._leftJoystick = true;
  21545. }
  21546. else {
  21547. this._leftJoystick = false;
  21548. }
  21549. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21550. VirtualJoystick._globalJoystickIndex++;
  21551. // By default left & right arrow keys are moving the X
  21552. // and up & down keys are moving the Y
  21553. this._axisTargetedByLeftAndRight = 0 /* X */;
  21554. this._axisTargetedByUpAndDown = 1 /* Y */;
  21555. this.reverseLeftRight = false;
  21556. this.reverseUpDown = false;
  21557. // collections of pointers
  21558. this._touches = new BABYLON.SmartCollection();
  21559. this.deltaPosition = BABYLON.Vector3.Zero();
  21560. this._joystickSensibility = 25;
  21561. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21562. this._rotationSpeed = 25;
  21563. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21564. this._rotateOnAxisRelativeToMesh = false;
  21565. // injecting a canvas element on top of the canvas 3D game
  21566. if (!VirtualJoystick.vjCanvas) {
  21567. window.addEventListener("resize", function () {
  21568. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21569. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21570. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21571. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21572. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21573. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21574. }, false);
  21575. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21576. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21577. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21578. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21579. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21580. VirtualJoystick.vjCanvas.style.width = "100%";
  21581. VirtualJoystick.vjCanvas.style.height = "100%";
  21582. VirtualJoystick.vjCanvas.style.position = "absolute";
  21583. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21584. VirtualJoystick.vjCanvas.style.top = "0px";
  21585. VirtualJoystick.vjCanvas.style.left = "0px";
  21586. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21587. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21588. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21589. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21590. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21591. document.body.appendChild(VirtualJoystick.vjCanvas);
  21592. }
  21593. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21594. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21595. this.pressed = false;
  21596. // default joystick color
  21597. this._joystickColor = "cyan";
  21598. this._joystickPointerID = -1;
  21599. // current joystick position
  21600. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21601. // origin joystick position
  21602. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21603. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21604. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21605. _this._onPointerDown(evt);
  21606. }, false);
  21607. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21608. _this._onPointerMove(evt);
  21609. }, false);
  21610. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21611. _this._onPointerUp(evt);
  21612. }, false);
  21613. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21614. _this._onPointerUp(evt);
  21615. }, false);
  21616. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21617. evt.preventDefault(); // Disables system menu
  21618. }, false);
  21619. requestAnimationFrame(function () {
  21620. _this._drawVirtualJoystick();
  21621. });
  21622. }
  21623. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21624. this._joystickSensibility = newJoystickSensibility;
  21625. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21626. };
  21627. VirtualJoystick.prototype._onPointerDown = function (e) {
  21628. var positionOnScreenCondition;
  21629. e.preventDefault();
  21630. if (this._leftJoystick === true) {
  21631. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21632. }
  21633. else {
  21634. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21635. }
  21636. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21637. // First contact will be dedicated to the virtual joystick
  21638. this._joystickPointerID = e.pointerId;
  21639. this._joystickPointerStartPos.x = e.clientX;
  21640. this._joystickPointerStartPos.y = e.clientY;
  21641. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21642. this._deltaJoystickVector.x = 0;
  21643. this._deltaJoystickVector.y = 0;
  21644. this.pressed = true;
  21645. this._touches.add(e.pointerId.toString(), e);
  21646. }
  21647. else {
  21648. // You can only trigger the action buttons with a joystick declared
  21649. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21650. this._action();
  21651. this._touches.add(e.pointerId.toString(), e);
  21652. }
  21653. }
  21654. };
  21655. VirtualJoystick.prototype._onPointerMove = function (e) {
  21656. // If the current pointer is the one associated to the joystick (first touch contact)
  21657. if (this._joystickPointerID == e.pointerId) {
  21658. this._joystickPointerPos.x = e.clientX;
  21659. this._joystickPointerPos.y = e.clientY;
  21660. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21661. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21662. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21663. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21664. switch (this._axisTargetedByLeftAndRight) {
  21665. case 0 /* X */:
  21666. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21667. break;
  21668. case 1 /* Y */:
  21669. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21670. break;
  21671. case 2 /* Z */:
  21672. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21673. break;
  21674. }
  21675. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21676. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21677. switch (this._axisTargetedByUpAndDown) {
  21678. case 0 /* X */:
  21679. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21680. break;
  21681. case 1 /* Y */:
  21682. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21683. break;
  21684. case 2 /* Z */:
  21685. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21686. break;
  21687. }
  21688. }
  21689. else {
  21690. if (this._touches.item(e.pointerId.toString())) {
  21691. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21692. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21693. }
  21694. }
  21695. };
  21696. VirtualJoystick.prototype._onPointerUp = function (e) {
  21697. this._clearCanvas();
  21698. if (this._joystickPointerID == e.pointerId) {
  21699. this._joystickPointerID = -1;
  21700. this.pressed = false;
  21701. }
  21702. this._deltaJoystickVector.x = 0;
  21703. this._deltaJoystickVector.y = 0;
  21704. this._touches.remove(e.pointerId.toString());
  21705. };
  21706. /**
  21707. * Change the color of the virtual joystick
  21708. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21709. */
  21710. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21711. this._joystickColor = newColor;
  21712. };
  21713. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21714. this._action = action;
  21715. };
  21716. // Define which axis you'd like to control for left & right
  21717. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21718. switch (axis) {
  21719. case 0 /* X */:
  21720. case 1 /* Y */:
  21721. case 2 /* Z */:
  21722. this._axisTargetedByLeftAndRight = axis;
  21723. break;
  21724. default:
  21725. this._axisTargetedByLeftAndRight = 0 /* X */;
  21726. break;
  21727. }
  21728. };
  21729. // Define which axis you'd like to control for up & down
  21730. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21731. switch (axis) {
  21732. case 0 /* X */:
  21733. case 1 /* Y */:
  21734. case 2 /* Z */:
  21735. this._axisTargetedByUpAndDown = axis;
  21736. break;
  21737. default:
  21738. this._axisTargetedByUpAndDown = 1 /* Y */;
  21739. break;
  21740. }
  21741. };
  21742. VirtualJoystick.prototype._clearCanvas = function () {
  21743. if (this._leftJoystick) {
  21744. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21745. }
  21746. else {
  21747. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21748. }
  21749. };
  21750. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21751. var _this = this;
  21752. if (this.pressed) {
  21753. this._clearCanvas();
  21754. this._touches.forEach(function (touch) {
  21755. if (touch.pointerId === _this._joystickPointerID) {
  21756. VirtualJoystick.vjCanvasContext.beginPath();
  21757. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21758. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21759. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21760. VirtualJoystick.vjCanvasContext.stroke();
  21761. VirtualJoystick.vjCanvasContext.beginPath();
  21762. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21763. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21764. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21765. VirtualJoystick.vjCanvasContext.stroke();
  21766. VirtualJoystick.vjCanvasContext.beginPath();
  21767. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21768. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21769. VirtualJoystick.vjCanvasContext.stroke();
  21770. }
  21771. else {
  21772. VirtualJoystick.vjCanvasContext.beginPath();
  21773. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21774. VirtualJoystick.vjCanvasContext.beginPath();
  21775. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21776. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21777. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21778. VirtualJoystick.vjCanvasContext.stroke();
  21779. }
  21780. ;
  21781. });
  21782. }
  21783. requestAnimationFrame(function () {
  21784. _this._drawVirtualJoystick();
  21785. });
  21786. };
  21787. VirtualJoystick.prototype.releaseCanvas = function () {
  21788. if (VirtualJoystick.vjCanvas) {
  21789. document.body.removeChild(VirtualJoystick.vjCanvas);
  21790. VirtualJoystick.vjCanvas = null;
  21791. }
  21792. };
  21793. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21794. VirtualJoystick._globalJoystickIndex = 0;
  21795. return VirtualJoystick;
  21796. })();
  21797. BABYLON.VirtualJoystick = VirtualJoystick;
  21798. })(BABYLON || (BABYLON = {}));
  21799. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21800. var BABYLON;
  21801. (function (BABYLON) {
  21802. var OculusRiftDevKit2013_Metric = {
  21803. HResolution: 1280,
  21804. VResolution: 800,
  21805. HScreenSize: 0.149759993,
  21806. VScreenSize: 0.0935999975,
  21807. VScreenCenter: 0.0467999987,
  21808. EyeToScreenDistance: 0.0410000011,
  21809. LensSeparationDistance: 0.0635000020,
  21810. InterpupillaryDistance: 0.0640000030,
  21811. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21812. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21813. PostProcessScaleFactor: 1.714605507808412,
  21814. LensCenterOffset: 0.151976421
  21815. };
  21816. var _OculusInnerCamera = (function (_super) {
  21817. __extends(_OculusInnerCamera, _super);
  21818. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21819. _super.call(this, name, position, scene);
  21820. this._workMatrix = new BABYLON.Matrix();
  21821. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21822. // Constants
  21823. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21824. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21825. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21826. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21827. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21828. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21829. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21830. // Postprocess
  21831. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21832. }
  21833. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21834. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21835. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21836. return this._projectionMatrix;
  21837. };
  21838. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21839. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21840. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21841. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21842. // Computing target and final matrix
  21843. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21844. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21845. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21846. return this._viewMatrix;
  21847. };
  21848. return _OculusInnerCamera;
  21849. })(BABYLON.FreeCamera);
  21850. var OculusCamera = (function (_super) {
  21851. __extends(OculusCamera, _super);
  21852. function OculusCamera(name, position, scene) {
  21853. _super.call(this, name, position, scene);
  21854. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21855. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21856. this.subCameras.push(this._leftCamera);
  21857. this.subCameras.push(this._rightCamera);
  21858. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21859. }
  21860. OculusCamera.prototype._update = function () {
  21861. this._leftCamera.position.copyFrom(this.position);
  21862. this._rightCamera.position.copyFrom(this.position);
  21863. this._updateCamera(this._leftCamera);
  21864. this._updateCamera(this._rightCamera);
  21865. _super.prototype._update.call(this);
  21866. };
  21867. OculusCamera.prototype._updateCamera = function (camera) {
  21868. camera.minZ = this.minZ;
  21869. camera.maxZ = this.maxZ;
  21870. camera.rotation.x = this.rotation.x;
  21871. camera.rotation.y = this.rotation.y;
  21872. camera.rotation.z = this.rotation.z;
  21873. };
  21874. // Oculus events
  21875. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21876. var yaw = evt.alpha / 180 * Math.PI;
  21877. var pitch = evt.beta / 180 * Math.PI;
  21878. var roll = evt.gamma / 180 * Math.PI;
  21879. if (!this._offsetOrientation) {
  21880. this._offsetOrientation = {
  21881. yaw: yaw,
  21882. pitch: pitch,
  21883. roll: roll
  21884. };
  21885. return;
  21886. }
  21887. else {
  21888. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21889. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21890. this.rotation.z += this._offsetOrientation.roll - roll;
  21891. this._offsetOrientation.yaw = yaw;
  21892. this._offsetOrientation.pitch = pitch;
  21893. this._offsetOrientation.roll = roll;
  21894. }
  21895. };
  21896. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21897. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21898. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21899. };
  21900. OculusCamera.prototype.detachControl = function (element) {
  21901. _super.prototype.detachControl.call(this, element);
  21902. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21903. };
  21904. return OculusCamera;
  21905. })(BABYLON.FreeCamera);
  21906. BABYLON.OculusCamera = OculusCamera;
  21907. })(BABYLON || (BABYLON = {}));
  21908. //# sourceMappingURL=babylon.oculusCamera.js.map
  21909. var BABYLON;
  21910. (function (BABYLON) {
  21911. var OculusRiftDevKit2013_Metric = {
  21912. HResolution: 1280,
  21913. VResolution: 800,
  21914. HScreenSize: 0.149759993,
  21915. VScreenSize: 0.0935999975,
  21916. VScreenCenter: 0.0467999987,
  21917. EyeToScreenDistance: 0.0410000011,
  21918. LensSeparationDistance: 0.0635000020,
  21919. InterpupillaryDistance: 0.0640000030,
  21920. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21921. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21922. PostProcessScaleFactor: 1.714605507808412,
  21923. LensCenterOffset: 0.151976421
  21924. };
  21925. var _OculusInnerGamepadCamera = (function (_super) {
  21926. __extends(_OculusInnerGamepadCamera, _super);
  21927. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21928. _super.call(this, name, position, scene);
  21929. this._workMatrix = new BABYLON.Matrix();
  21930. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21931. // Constants
  21932. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21933. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21934. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21935. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21936. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21937. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21938. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21939. // Postprocess
  21940. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21941. }
  21942. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21943. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21944. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21945. return this._projectionMatrix;
  21946. };
  21947. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21948. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21949. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21950. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21951. // Computing target and final matrix
  21952. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21953. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21954. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21955. return this._viewMatrix;
  21956. };
  21957. return _OculusInnerGamepadCamera;
  21958. })(BABYLON.FreeCamera);
  21959. var OculusGamepadCamera = (function (_super) {
  21960. __extends(OculusGamepadCamera, _super);
  21961. function OculusGamepadCamera(name, position, scene) {
  21962. var _this = this;
  21963. _super.call(this, name, position, scene);
  21964. this.angularSensibility = 200;
  21965. this.moveSensibility = 75;
  21966. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21967. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21968. this.subCameras.push(this._leftCamera);
  21969. this.subCameras.push(this._rightCamera);
  21970. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21971. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21972. _this._onNewGameConnected(gamepad);
  21973. });
  21974. }
  21975. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21976. // Only the first gamepad can control the camera
  21977. if (gamepad.index === 0) {
  21978. this._gamepad = gamepad;
  21979. }
  21980. };
  21981. OculusGamepadCamera.prototype._update = function () {
  21982. this._leftCamera.position.copyFrom(this.position);
  21983. this._rightCamera.position.copyFrom(this.position);
  21984. this._updateCamera(this._leftCamera);
  21985. this._updateCamera(this._rightCamera);
  21986. _super.prototype._update.call(this);
  21987. };
  21988. OculusGamepadCamera.prototype._checkInputs = function () {
  21989. if (!this._gamepad) {
  21990. return;
  21991. }
  21992. var LSValues = this._gamepad.leftStick;
  21993. var normalizedLX = LSValues.x / this.moveSensibility;
  21994. var normalizedLY = LSValues.y / this.moveSensibility;
  21995. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21996. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21997. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21998. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21999. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22000. };
  22001. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  22002. camera.minZ = this.minZ;
  22003. camera.maxZ = this.maxZ;
  22004. camera.rotation.x = this.rotation.x;
  22005. camera.rotation.y = this.rotation.y;
  22006. camera.rotation.z = this.rotation.z;
  22007. };
  22008. // Oculus events
  22009. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  22010. var yaw = evt.alpha / 180 * Math.PI;
  22011. var pitch = evt.beta / 180 * Math.PI;
  22012. var roll = evt.gamma / 180 * Math.PI;
  22013. if (!this._offsetOrientation) {
  22014. this._offsetOrientation = {
  22015. yaw: yaw,
  22016. pitch: pitch,
  22017. roll: roll
  22018. };
  22019. return;
  22020. }
  22021. else {
  22022. this.rotation.y += yaw - this._offsetOrientation.yaw;
  22023. this.rotation.x += pitch - this._offsetOrientation.pitch;
  22024. this.rotation.z += this._offsetOrientation.roll - roll;
  22025. this._offsetOrientation.yaw = yaw;
  22026. this._offsetOrientation.pitch = pitch;
  22027. this._offsetOrientation.roll = roll;
  22028. }
  22029. };
  22030. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  22031. _super.prototype.attachControl.call(this, element, noPreventDefault);
  22032. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  22033. };
  22034. OculusGamepadCamera.prototype.detachControl = function (element) {
  22035. _super.prototype.detachControl.call(this, element);
  22036. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  22037. };
  22038. OculusGamepadCamera.prototype.dispose = function () {
  22039. this._gamepads.dispose();
  22040. _super.prototype.dispose.call(this);
  22041. };
  22042. return OculusGamepadCamera;
  22043. })(BABYLON.FreeCamera);
  22044. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  22045. })(BABYLON || (BABYLON = {}));
  22046. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  22047. var BABYLON;
  22048. (function (BABYLON) {
  22049. // We're mainly based on the logic defined into the FreeCamera code
  22050. var VirtualJoysticksCamera = (function (_super) {
  22051. __extends(VirtualJoysticksCamera, _super);
  22052. function VirtualJoysticksCamera(name, position, scene) {
  22053. _super.call(this, name, position, scene);
  22054. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  22055. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  22056. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  22057. this._leftjoystick.setJoystickSensibility(0.15);
  22058. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  22059. this._rightjoystick.setAxisForUpDown(0 /* X */);
  22060. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  22061. this._rightjoystick.reverseUpDown = true;
  22062. this._rightjoystick.setJoystickSensibility(0.05);
  22063. this._rightjoystick.setJoystickColor("yellow");
  22064. }
  22065. VirtualJoysticksCamera.prototype._checkInputs = function () {
  22066. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22067. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  22068. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22069. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  22070. if (!this._leftjoystick.pressed) {
  22071. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  22072. }
  22073. if (!this._rightjoystick.pressed) {
  22074. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  22075. }
  22076. };
  22077. VirtualJoysticksCamera.prototype.dispose = function () {
  22078. this._leftjoystick.releaseCanvas();
  22079. _super.prototype.dispose.call(this);
  22080. };
  22081. return VirtualJoysticksCamera;
  22082. })(BABYLON.FreeCamera);
  22083. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  22084. })(BABYLON || (BABYLON = {}));
  22085. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  22086. var BABYLON;
  22087. (function (BABYLON) {
  22088. var ShaderMaterial = (function (_super) {
  22089. __extends(ShaderMaterial, _super);
  22090. function ShaderMaterial(name, scene, shaderPath, options) {
  22091. _super.call(this, name, scene);
  22092. this._textures = new Array();
  22093. this._floats = new Array();
  22094. this._floatsArrays = {};
  22095. this._colors3 = new Array();
  22096. this._colors4 = new Array();
  22097. this._vectors2 = new Array();
  22098. this._vectors3 = new Array();
  22099. this._matrices = new Array();
  22100. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  22101. this._shaderPath = shaderPath;
  22102. options.needAlphaBlending = options.needAlphaBlending || false;
  22103. options.needAlphaTesting = options.needAlphaTesting || false;
  22104. options.attributes = options.attributes || ["position", "normal", "uv"];
  22105. options.uniforms = options.uniforms || ["worldViewProjection"];
  22106. options.samplers = options.samplers || [];
  22107. this._options = options;
  22108. }
  22109. ShaderMaterial.prototype.needAlphaBlending = function () {
  22110. return this._options.needAlphaBlending;
  22111. };
  22112. ShaderMaterial.prototype.needAlphaTesting = function () {
  22113. return this._options.needAlphaTesting;
  22114. };
  22115. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  22116. if (this._options.uniforms.indexOf(uniformName) === -1) {
  22117. this._options.uniforms.push(uniformName);
  22118. }
  22119. };
  22120. ShaderMaterial.prototype.setTexture = function (name, texture) {
  22121. if (this._options.samplers.indexOf(name) === -1) {
  22122. this._options.samplers.push(name);
  22123. }
  22124. this._textures[name] = texture;
  22125. return this;
  22126. };
  22127. ShaderMaterial.prototype.setFloat = function (name, value) {
  22128. this._checkUniform(name);
  22129. this._floats[name] = value;
  22130. return this;
  22131. };
  22132. ShaderMaterial.prototype.setFloats = function (name, value) {
  22133. this._checkUniform(name);
  22134. this._floatsArrays[name] = value;
  22135. return this;
  22136. };
  22137. ShaderMaterial.prototype.setColor3 = function (name, value) {
  22138. this._checkUniform(name);
  22139. this._colors3[name] = value;
  22140. return this;
  22141. };
  22142. ShaderMaterial.prototype.setColor4 = function (name, value) {
  22143. this._checkUniform(name);
  22144. this._colors4[name] = value;
  22145. return this;
  22146. };
  22147. ShaderMaterial.prototype.setVector2 = function (name, value) {
  22148. this._checkUniform(name);
  22149. this._vectors2[name] = value;
  22150. return this;
  22151. };
  22152. ShaderMaterial.prototype.setVector3 = function (name, value) {
  22153. this._checkUniform(name);
  22154. this._vectors3[name] = value;
  22155. return this;
  22156. };
  22157. ShaderMaterial.prototype.setMatrix = function (name, value) {
  22158. this._checkUniform(name);
  22159. this._matrices[name] = value;
  22160. return this;
  22161. };
  22162. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  22163. var scene = this.getScene();
  22164. var engine = scene.getEngine();
  22165. if (!this.checkReadyOnEveryCall) {
  22166. if (this._renderId === scene.getRenderId()) {
  22167. return true;
  22168. }
  22169. }
  22170. // Instances
  22171. var defines = [];
  22172. var fallbacks = new BABYLON.EffectFallbacks();
  22173. if (useInstances) {
  22174. defines.push("#define INSTANCES");
  22175. }
  22176. // Bones
  22177. if (mesh && mesh.useBones) {
  22178. defines.push("#define BONES");
  22179. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22180. defines.push("#define BONES4");
  22181. fallbacks.addFallback(0, "BONES4");
  22182. }
  22183. // Alpha test
  22184. if (engine.getAlphaTesting()) {
  22185. defines.push("#define ALPHATEST");
  22186. }
  22187. var previousEffect = this._effect;
  22188. var join = defines.join("\n");
  22189. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  22190. if (!this._effect.isReady()) {
  22191. return false;
  22192. }
  22193. if (previousEffect !== this._effect) {
  22194. scene.resetCachedMaterial();
  22195. }
  22196. this._renderId = scene.getRenderId();
  22197. return true;
  22198. };
  22199. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22200. var scene = this.getScene();
  22201. if (this._options.uniforms.indexOf("world") !== -1) {
  22202. this._effect.setMatrix("world", world);
  22203. }
  22204. if (this._options.uniforms.indexOf("worldView") !== -1) {
  22205. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  22206. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  22207. }
  22208. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22209. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22210. }
  22211. };
  22212. ShaderMaterial.prototype.bind = function (world, mesh) {
  22213. // Std values
  22214. this.bindOnlyWorldMatrix(world);
  22215. if (this.getScene().getCachedMaterial() !== this) {
  22216. if (this._options.uniforms.indexOf("view") !== -1) {
  22217. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22218. }
  22219. if (this._options.uniforms.indexOf("projection") !== -1) {
  22220. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22221. }
  22222. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22223. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22224. }
  22225. // Bones
  22226. if (mesh && mesh.useBones) {
  22227. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22228. }
  22229. for (var name in this._textures) {
  22230. this._effect.setTexture(name, this._textures[name]);
  22231. }
  22232. for (name in this._floats) {
  22233. this._effect.setFloat(name, this._floats[name]);
  22234. }
  22235. for (name in this._floatsArrays) {
  22236. this._effect.setArray(name, this._floatsArrays[name]);
  22237. }
  22238. for (name in this._colors3) {
  22239. this._effect.setColor3(name, this._colors3[name]);
  22240. }
  22241. for (name in this._colors4) {
  22242. var color = this._colors4[name];
  22243. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22244. }
  22245. for (name in this._vectors2) {
  22246. this._effect.setVector2(name, this._vectors2[name]);
  22247. }
  22248. for (name in this._vectors3) {
  22249. this._effect.setVector3(name, this._vectors3[name]);
  22250. }
  22251. for (name in this._matrices) {
  22252. this._effect.setMatrix(name, this._matrices[name]);
  22253. }
  22254. }
  22255. _super.prototype.bind.call(this, world, mesh);
  22256. };
  22257. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22258. for (var name in this._textures) {
  22259. this._textures[name].dispose();
  22260. }
  22261. this._textures = [];
  22262. _super.prototype.dispose.call(this, forceDisposeEffect);
  22263. };
  22264. return ShaderMaterial;
  22265. })(BABYLON.Material);
  22266. BABYLON.ShaderMaterial = ShaderMaterial;
  22267. })(BABYLON || (BABYLON = {}));
  22268. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22269. (function (BABYLON) {
  22270. var VertexData = (function () {
  22271. function VertexData() {
  22272. }
  22273. VertexData.prototype.set = function (data, kind) {
  22274. switch (kind) {
  22275. case BABYLON.VertexBuffer.PositionKind:
  22276. this.positions = data;
  22277. break;
  22278. case BABYLON.VertexBuffer.NormalKind:
  22279. this.normals = data;
  22280. break;
  22281. case BABYLON.VertexBuffer.UVKind:
  22282. this.uvs = data;
  22283. break;
  22284. case BABYLON.VertexBuffer.UV2Kind:
  22285. this.uv2s = data;
  22286. break;
  22287. case BABYLON.VertexBuffer.ColorKind:
  22288. this.colors = data;
  22289. break;
  22290. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22291. this.matricesIndices = data;
  22292. break;
  22293. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22294. this.matricesWeights = data;
  22295. break;
  22296. }
  22297. };
  22298. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22299. this._applyTo(mesh, updatable);
  22300. };
  22301. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22302. this._applyTo(geometry, updatable);
  22303. };
  22304. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22305. this._update(mesh);
  22306. };
  22307. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22308. this._update(geometry);
  22309. };
  22310. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22311. if (this.positions) {
  22312. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22313. }
  22314. if (this.normals) {
  22315. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22316. }
  22317. if (this.uvs) {
  22318. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22319. }
  22320. if (this.uv2s) {
  22321. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22322. }
  22323. if (this.colors) {
  22324. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22325. }
  22326. if (this.matricesIndices) {
  22327. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22328. }
  22329. if (this.matricesWeights) {
  22330. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22331. }
  22332. if (this.indices) {
  22333. meshOrGeometry.setIndices(this.indices);
  22334. }
  22335. };
  22336. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22337. if (this.positions) {
  22338. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22339. }
  22340. if (this.normals) {
  22341. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22342. }
  22343. if (this.uvs) {
  22344. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22345. }
  22346. if (this.uv2s) {
  22347. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22348. }
  22349. if (this.colors) {
  22350. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22351. }
  22352. if (this.matricesIndices) {
  22353. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22354. }
  22355. if (this.matricesWeights) {
  22356. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22357. }
  22358. if (this.indices) {
  22359. meshOrGeometry.setIndices(this.indices);
  22360. }
  22361. };
  22362. VertexData.prototype.transform = function (matrix) {
  22363. var transformed = BABYLON.Vector3.Zero();
  22364. if (this.positions) {
  22365. var position = BABYLON.Vector3.Zero();
  22366. for (var index = 0; index < this.positions.length; index += 3) {
  22367. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22368. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22369. this.positions[index] = transformed.x;
  22370. this.positions[index + 1] = transformed.y;
  22371. this.positions[index + 2] = transformed.z;
  22372. }
  22373. }
  22374. if (this.normals) {
  22375. var normal = BABYLON.Vector3.Zero();
  22376. for (index = 0; index < this.normals.length; index += 3) {
  22377. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22378. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22379. this.normals[index] = transformed.x;
  22380. this.normals[index + 1] = transformed.y;
  22381. this.normals[index + 2] = transformed.z;
  22382. }
  22383. }
  22384. };
  22385. VertexData.prototype.merge = function (other) {
  22386. if (other.indices) {
  22387. if (!this.indices) {
  22388. this.indices = [];
  22389. }
  22390. var offset = this.positions ? this.positions.length / 3 : 0;
  22391. for (var index = 0; index < other.indices.length; index++) {
  22392. this.indices.push(other.indices[index] + offset);
  22393. }
  22394. }
  22395. if (other.positions) {
  22396. if (!this.positions) {
  22397. this.positions = [];
  22398. }
  22399. for (index = 0; index < other.positions.length; index++) {
  22400. this.positions.push(other.positions[index]);
  22401. }
  22402. }
  22403. if (other.normals) {
  22404. if (!this.normals) {
  22405. this.normals = [];
  22406. }
  22407. for (index = 0; index < other.normals.length; index++) {
  22408. this.normals.push(other.normals[index]);
  22409. }
  22410. }
  22411. if (other.uvs) {
  22412. if (!this.uvs) {
  22413. this.uvs = [];
  22414. }
  22415. for (index = 0; index < other.uvs.length; index++) {
  22416. this.uvs.push(other.uvs[index]);
  22417. }
  22418. }
  22419. if (other.uv2s) {
  22420. if (!this.uv2s) {
  22421. this.uv2s = [];
  22422. }
  22423. for (index = 0; index < other.uv2s.length; index++) {
  22424. this.uv2s.push(other.uv2s[index]);
  22425. }
  22426. }
  22427. if (other.matricesIndices) {
  22428. if (!this.matricesIndices) {
  22429. this.matricesIndices = [];
  22430. }
  22431. for (index = 0; index < other.matricesIndices.length; index++) {
  22432. this.matricesIndices.push(other.matricesIndices[index]);
  22433. }
  22434. }
  22435. if (other.matricesWeights) {
  22436. if (!this.matricesWeights) {
  22437. this.matricesWeights = [];
  22438. }
  22439. for (index = 0; index < other.matricesWeights.length; index++) {
  22440. this.matricesWeights.push(other.matricesWeights[index]);
  22441. }
  22442. }
  22443. if (other.colors) {
  22444. if (!this.colors) {
  22445. this.colors = [];
  22446. }
  22447. for (index = 0; index < other.colors.length; index++) {
  22448. this.colors.push(other.colors[index]);
  22449. }
  22450. }
  22451. };
  22452. // Statics
  22453. VertexData.ExtractFromMesh = function (mesh) {
  22454. return VertexData._ExtractFrom(mesh);
  22455. };
  22456. VertexData.ExtractFromGeometry = function (geometry) {
  22457. return VertexData._ExtractFrom(geometry);
  22458. };
  22459. VertexData._ExtractFrom = function (meshOrGeometry) {
  22460. var result = new VertexData();
  22461. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22462. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22463. }
  22464. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22465. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22466. }
  22467. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22468. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22469. }
  22470. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22471. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22472. }
  22473. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22474. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22475. }
  22476. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22477. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22478. }
  22479. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22480. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22481. }
  22482. result.indices = meshOrGeometry.getIndices();
  22483. return result;
  22484. };
  22485. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22486. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22487. closeArray = closeArray || false;
  22488. closePath = closePath || false;
  22489. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22490. offset = offset || defaultOffset;
  22491. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22492. var positions = [];
  22493. var indices = [];
  22494. var normals = [];
  22495. var uvs = [];
  22496. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22497. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22498. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22499. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22500. var minlg; // minimal length among all paths from pathArray
  22501. var lg = []; // array of path lengths : nb of vertex per path
  22502. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22503. var p; // path iterator
  22504. var i; // point iterator
  22505. var j; // point iterator
  22506. // if single path in pathArray
  22507. if (pathArray.length < 2) {
  22508. var ar1 = [];
  22509. var ar2 = [];
  22510. for (i = 0; i < pathArray[0].length - offset; i++) {
  22511. ar1.push(pathArray[0][i]);
  22512. ar2.push(pathArray[0][i + offset]);
  22513. }
  22514. pathArray = [ar1, ar2];
  22515. }
  22516. // positions and horizontal distances (u)
  22517. var idc = 0;
  22518. minlg = pathArray[0].length;
  22519. for (p = 0; p < pathArray.length; p++) {
  22520. uTotalDistance[p] = 0;
  22521. us[p] = [0];
  22522. var path = pathArray[p];
  22523. var l = path.length;
  22524. minlg = (minlg < l) ? minlg : l;
  22525. lg[p] = l;
  22526. idx[p] = idc;
  22527. j = 0;
  22528. while (j < l) {
  22529. positions.push(path[j].x, path[j].y, path[j].z);
  22530. if (j > 0) {
  22531. var vectlg = path[j].subtract(path[j - 1]).length();
  22532. var dist = vectlg + uTotalDistance[p];
  22533. us[p].push(dist);
  22534. uTotalDistance[p] = dist;
  22535. }
  22536. j++;
  22537. }
  22538. if (closePath) {
  22539. vectlg = path[0].subtract(path[j - 1]).length();
  22540. dist = vectlg + uTotalDistance[p];
  22541. uTotalDistance[p] = dist;
  22542. }
  22543. idc += l;
  22544. }
  22545. for (i = 0; i < minlg; i++) {
  22546. vTotalDistance[i] = 0;
  22547. vs[i] = [0];
  22548. var path1;
  22549. var path2;
  22550. for (p = 0; p < pathArray.length - 1; p++) {
  22551. path1 = pathArray[p];
  22552. path2 = pathArray[p + 1];
  22553. vectlg = path2[i].subtract(path1[i]).length();
  22554. dist = vectlg + vTotalDistance[i];
  22555. vs[i].push(dist);
  22556. vTotalDistance[i] = dist;
  22557. }
  22558. if (closeArray) {
  22559. path1 = pathArray[p];
  22560. path2 = pathArray[0];
  22561. vectlg = path2[i].subtract(path1[i]).length();
  22562. dist = vectlg + vTotalDistance[i];
  22563. vTotalDistance[i] = dist;
  22564. }
  22565. }
  22566. // uvs
  22567. var u;
  22568. var v;
  22569. for (p = 0; p < pathArray.length; p++) {
  22570. for (i = 0; i < minlg; i++) {
  22571. u = us[p][i] / uTotalDistance[p];
  22572. v = vs[i][p] / vTotalDistance[i];
  22573. uvs.push(u, v);
  22574. }
  22575. }
  22576. // indices
  22577. p = 0; // path index
  22578. var pi = 0; // positions array index
  22579. var l1 = lg[p] - 1; // path1 length
  22580. var l2 = lg[p + 1] - 1; // path2 length
  22581. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22582. var shft = idx[1] - idx[0]; // shift
  22583. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22584. var t1; // two consecutive triangles, so 4 points : point1
  22585. var t2; // point2
  22586. var t3; // point3
  22587. var t4; // point4
  22588. while (pi <= min && p < path1nb) {
  22589. // 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
  22590. t1 = pi;
  22591. t2 = pi + shft;
  22592. t3 = pi + 1;
  22593. t4 = pi + shft + 1;
  22594. indices.push(pi, pi + shft, pi + 1);
  22595. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22596. pi += 1;
  22597. if (pi === min) {
  22598. if (closePath) {
  22599. indices.push(pi, pi + shft, idx[p]);
  22600. indices.push(idx[p] + shft, idx[p], pi + shft);
  22601. t3 = idx[p];
  22602. t4 = idx[p] + shft;
  22603. }
  22604. p++;
  22605. if (p === lg.length - 1) {
  22606. shft = idx[0] - idx[p];
  22607. l1 = lg[p] - 1;
  22608. l2 = lg[0] - 1;
  22609. }
  22610. else {
  22611. shft = idx[p + 1] - idx[p];
  22612. l1 = lg[p] - 1;
  22613. l2 = lg[p + 1] - 1;
  22614. }
  22615. pi = idx[p];
  22616. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22617. }
  22618. }
  22619. // normals
  22620. VertexData.ComputeNormals(positions, indices, normals);
  22621. // sides
  22622. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22623. // Result
  22624. var vertexData = new VertexData();
  22625. vertexData.indices = indices;
  22626. vertexData.positions = positions;
  22627. vertexData.normals = normals;
  22628. vertexData.uvs = uvs;
  22629. return vertexData;
  22630. };
  22631. VertexData.CreateBox = function (size, sideOrientation) {
  22632. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22633. var normalsSource = [
  22634. new BABYLON.Vector3(0, 0, 1),
  22635. new BABYLON.Vector3(0, 0, -1),
  22636. new BABYLON.Vector3(1, 0, 0),
  22637. new BABYLON.Vector3(-1, 0, 0),
  22638. new BABYLON.Vector3(0, 1, 0),
  22639. new BABYLON.Vector3(0, -1, 0)
  22640. ];
  22641. var indices = [];
  22642. var positions = [];
  22643. var normals = [];
  22644. var uvs = [];
  22645. size = size || 1;
  22646. for (var index = 0; index < normalsSource.length; index++) {
  22647. var normal = normalsSource[index];
  22648. // Get two vectors perpendicular to the face normal and to each other.
  22649. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22650. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22651. // Six indices (two triangles) per face.
  22652. var verticesLength = positions.length / 3;
  22653. indices.push(verticesLength);
  22654. indices.push(verticesLength + 1);
  22655. indices.push(verticesLength + 2);
  22656. indices.push(verticesLength);
  22657. indices.push(verticesLength + 2);
  22658. indices.push(verticesLength + 3);
  22659. // Four vertices per face.
  22660. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22661. positions.push(vertex.x, vertex.y, vertex.z);
  22662. normals.push(normal.x, normal.y, normal.z);
  22663. uvs.push(1.0, 1.0);
  22664. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22665. positions.push(vertex.x, vertex.y, vertex.z);
  22666. normals.push(normal.x, normal.y, normal.z);
  22667. uvs.push(0.0, 1.0);
  22668. vertex = normal.add(side1).add(side2).scale(size / 2);
  22669. positions.push(vertex.x, vertex.y, vertex.z);
  22670. normals.push(normal.x, normal.y, normal.z);
  22671. uvs.push(0.0, 0.0);
  22672. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22673. positions.push(vertex.x, vertex.y, vertex.z);
  22674. normals.push(normal.x, normal.y, normal.z);
  22675. uvs.push(1.0, 0.0);
  22676. }
  22677. // sides
  22678. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22679. // Result
  22680. var vertexData = new VertexData();
  22681. vertexData.indices = indices;
  22682. vertexData.positions = positions;
  22683. vertexData.normals = normals;
  22684. vertexData.uvs = uvs;
  22685. return vertexData;
  22686. };
  22687. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22688. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22689. segments = segments || 32;
  22690. diameter = diameter || 1;
  22691. var radius = diameter / 2;
  22692. var totalZRotationSteps = 2 + segments;
  22693. var totalYRotationSteps = 2 * totalZRotationSteps;
  22694. var indices = [];
  22695. var positions = [];
  22696. var normals = [];
  22697. var uvs = [];
  22698. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22699. var normalizedZ = zRotationStep / totalZRotationSteps;
  22700. var angleZ = (normalizedZ * Math.PI);
  22701. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22702. var normalizedY = yRotationStep / totalYRotationSteps;
  22703. var angleY = normalizedY * Math.PI * 2;
  22704. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22705. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22706. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22707. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22708. var vertex = complete.scale(radius);
  22709. var normal = BABYLON.Vector3.Normalize(vertex);
  22710. positions.push(vertex.x, vertex.y, vertex.z);
  22711. normals.push(normal.x, normal.y, normal.z);
  22712. uvs.push(normalizedZ, normalizedY);
  22713. }
  22714. if (zRotationStep > 0) {
  22715. var verticesCount = positions.length / 3;
  22716. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22717. indices.push((firstIndex));
  22718. indices.push((firstIndex + 1));
  22719. indices.push(firstIndex + totalYRotationSteps + 1);
  22720. indices.push((firstIndex + totalYRotationSteps + 1));
  22721. indices.push((firstIndex + 1));
  22722. indices.push((firstIndex + totalYRotationSteps + 2));
  22723. }
  22724. }
  22725. }
  22726. // Sides
  22727. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22728. // Result
  22729. var vertexData = new VertexData();
  22730. vertexData.indices = indices;
  22731. vertexData.positions = positions;
  22732. vertexData.normals = normals;
  22733. vertexData.uvs = uvs;
  22734. return vertexData;
  22735. };
  22736. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22737. if (subdivisions === void 0) { subdivisions = 1; }
  22738. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22739. var radiusTop = diameterTop / 2;
  22740. var radiusBottom = diameterBottom / 2;
  22741. var indices = [];
  22742. var positions = [];
  22743. var normals = [];
  22744. var uvs = [];
  22745. height = height || 1;
  22746. diameterTop = diameterTop || 0.5;
  22747. diameterBottom = diameterBottom || 1;
  22748. tessellation = tessellation || 16;
  22749. subdivisions = subdivisions || 1;
  22750. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22751. var getCircleVector = function (i) {
  22752. var angle = (i * 2.0 * Math.PI / tessellation);
  22753. var dx = Math.cos(angle);
  22754. var dz = Math.sin(angle);
  22755. return new BABYLON.Vector3(dx, 0, dz);
  22756. };
  22757. var createCylinderCap = function (isTop) {
  22758. var radius = isTop ? radiusTop : radiusBottom;
  22759. if (radius === 0) {
  22760. return;
  22761. }
  22762. var vbase = positions.length / 3;
  22763. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22764. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22765. if (!isTop) {
  22766. offset.scaleInPlace(-1);
  22767. textureScale.x = -textureScale.x;
  22768. }
  22769. for (var i = 0; i < tessellation; i++) {
  22770. var circleVector = getCircleVector(i);
  22771. var position = circleVector.scale(radius).add(offset);
  22772. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22773. positions.push(position.x, position.y, position.z);
  22774. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22775. }
  22776. for (i = 0; i < tessellation - 2; i++) {
  22777. if (!isTop) {
  22778. indices.push(vbase);
  22779. indices.push(vbase + (i + 2) % tessellation);
  22780. indices.push(vbase + (i + 1) % tessellation);
  22781. }
  22782. else {
  22783. indices.push(vbase);
  22784. indices.push(vbase + (i + 1) % tessellation);
  22785. indices.push(vbase + (i + 2) % tessellation);
  22786. }
  22787. }
  22788. };
  22789. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22790. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22791. var stride = tessellation + 1;
  22792. for (var i = 0; i <= tessellation; i++) {
  22793. var circleVector = getCircleVector(i);
  22794. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22795. var position, radius = radiusBottom;
  22796. for (var s = 0; s <= subdivisions; s++) {
  22797. // Update variables
  22798. position = circleVector.scale(radius);
  22799. position.addInPlace(base.add(offset.scale(s)));
  22800. textureCoordinate.y += 1 / subdivisions;
  22801. radius += (radiusTop - radiusBottom) / subdivisions;
  22802. // Push in arrays
  22803. positions.push(position.x, position.y, position.z);
  22804. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22805. }
  22806. }
  22807. subdivisions += 1;
  22808. for (s = 0; s < subdivisions - 1; s++) {
  22809. for (i = 0; i <= tessellation; i++) {
  22810. indices.push(i * subdivisions + s);
  22811. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22812. indices.push(i * subdivisions + (s + 1));
  22813. indices.push(i * subdivisions + (s + 1));
  22814. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22815. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22816. }
  22817. }
  22818. // Create flat triangle fan caps to seal the top and bottom.
  22819. createCylinderCap(true);
  22820. createCylinderCap(false);
  22821. // Normals
  22822. VertexData.ComputeNormals(positions, indices, normals);
  22823. // Sides
  22824. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22825. // Result
  22826. var vertexData = new VertexData();
  22827. vertexData.indices = indices;
  22828. vertexData.positions = positions;
  22829. vertexData.normals = normals;
  22830. vertexData.uvs = uvs;
  22831. return vertexData;
  22832. };
  22833. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22834. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22835. var indices = [];
  22836. var positions = [];
  22837. var normals = [];
  22838. var uvs = [];
  22839. diameter = diameter || 1;
  22840. thickness = thickness || 0.5;
  22841. tessellation = tessellation || 16;
  22842. var stride = tessellation + 1;
  22843. for (var i = 0; i <= tessellation; i++) {
  22844. var u = i / tessellation;
  22845. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22846. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22847. for (var j = 0; j <= tessellation; j++) {
  22848. var v = 1 - j / tessellation;
  22849. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22850. var dx = Math.cos(innerAngle);
  22851. var dy = Math.sin(innerAngle);
  22852. // Create a vertex.
  22853. var normal = new BABYLON.Vector3(dx, dy, 0);
  22854. var position = normal.scale(thickness / 2);
  22855. var textureCoordinate = new BABYLON.Vector2(u, v);
  22856. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22857. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22858. positions.push(position.x, position.y, position.z);
  22859. normals.push(normal.x, normal.y, normal.z);
  22860. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22861. // And create indices for two triangles.
  22862. var nextI = (i + 1) % stride;
  22863. var nextJ = (j + 1) % stride;
  22864. indices.push(i * stride + j);
  22865. indices.push(i * stride + nextJ);
  22866. indices.push(nextI * stride + j);
  22867. indices.push(i * stride + nextJ);
  22868. indices.push(nextI * stride + nextJ);
  22869. indices.push(nextI * stride + j);
  22870. }
  22871. }
  22872. // Sides
  22873. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22874. // Result
  22875. var vertexData = new VertexData();
  22876. vertexData.indices = indices;
  22877. vertexData.positions = positions;
  22878. vertexData.normals = normals;
  22879. vertexData.uvs = uvs;
  22880. return vertexData;
  22881. };
  22882. VertexData.CreateLines = function (points) {
  22883. var indices = [];
  22884. var positions = [];
  22885. for (var index = 0; index < points.length; index++) {
  22886. positions.push(points[index].x, points[index].y, points[index].z);
  22887. if (index > 0) {
  22888. indices.push(index - 1);
  22889. indices.push(index);
  22890. }
  22891. }
  22892. // Result
  22893. var vertexData = new VertexData();
  22894. vertexData.indices = indices;
  22895. vertexData.positions = positions;
  22896. return vertexData;
  22897. };
  22898. VertexData.CreateGround = function (width, height, subdivisions) {
  22899. var indices = [];
  22900. var positions = [];
  22901. var normals = [];
  22902. var uvs = [];
  22903. var row, col;
  22904. width = width || 1;
  22905. height = height || 1;
  22906. subdivisions = subdivisions || 1;
  22907. for (row = 0; row <= subdivisions; row++) {
  22908. for (col = 0; col <= subdivisions; col++) {
  22909. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22910. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22911. positions.push(position.x, position.y, position.z);
  22912. normals.push(normal.x, normal.y, normal.z);
  22913. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22914. }
  22915. }
  22916. for (row = 0; row < subdivisions; row++) {
  22917. for (col = 0; col < subdivisions; col++) {
  22918. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22919. indices.push(col + 1 + row * (subdivisions + 1));
  22920. indices.push(col + row * (subdivisions + 1));
  22921. indices.push(col + (row + 1) * (subdivisions + 1));
  22922. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22923. indices.push(col + row * (subdivisions + 1));
  22924. }
  22925. }
  22926. // Result
  22927. var vertexData = new VertexData();
  22928. vertexData.indices = indices;
  22929. vertexData.positions = positions;
  22930. vertexData.normals = normals;
  22931. vertexData.uvs = uvs;
  22932. return vertexData;
  22933. };
  22934. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22935. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22936. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22937. var indices = [];
  22938. var positions = [];
  22939. var normals = [];
  22940. var uvs = [];
  22941. var row, col, tileRow, tileCol;
  22942. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22943. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22944. precision.w = (precision.w < 1) ? 1 : precision.w;
  22945. precision.h = (precision.h < 1) ? 1 : precision.h;
  22946. var tileSize = {
  22947. 'w': (xmax - xmin) / subdivisions.w,
  22948. 'h': (zmax - zmin) / subdivisions.h
  22949. };
  22950. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22951. // Indices
  22952. var base = positions.length / 3;
  22953. var rowLength = precision.w + 1;
  22954. for (row = 0; row < precision.h; row++) {
  22955. for (col = 0; col < precision.w; col++) {
  22956. var square = [
  22957. base + col + row * rowLength,
  22958. base + (col + 1) + row * rowLength,
  22959. base + (col + 1) + (row + 1) * rowLength,
  22960. base + col + (row + 1) * rowLength
  22961. ];
  22962. indices.push(square[1]);
  22963. indices.push(square[2]);
  22964. indices.push(square[3]);
  22965. indices.push(square[0]);
  22966. indices.push(square[1]);
  22967. indices.push(square[3]);
  22968. }
  22969. }
  22970. // Position, normals and uvs
  22971. var position = BABYLON.Vector3.Zero();
  22972. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22973. for (row = 0; row <= precision.h; row++) {
  22974. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22975. for (col = 0; col <= precision.w; col++) {
  22976. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22977. position.y = 0;
  22978. positions.push(position.x, position.y, position.z);
  22979. normals.push(normal.x, normal.y, normal.z);
  22980. uvs.push(col / precision.w, row / precision.h);
  22981. }
  22982. }
  22983. }
  22984. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22985. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22986. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22987. }
  22988. }
  22989. // Result
  22990. var vertexData = new VertexData();
  22991. vertexData.indices = indices;
  22992. vertexData.positions = positions;
  22993. vertexData.normals = normals;
  22994. vertexData.uvs = uvs;
  22995. return vertexData;
  22996. };
  22997. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22998. var indices = [];
  22999. var positions = [];
  23000. var normals = [];
  23001. var uvs = [];
  23002. var row, col;
  23003. for (row = 0; row <= subdivisions; row++) {
  23004. for (col = 0; col <= subdivisions; col++) {
  23005. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23006. // Compute height
  23007. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  23008. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  23009. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  23010. var r = buffer[pos] / 255.0;
  23011. var g = buffer[pos + 1] / 255.0;
  23012. var b = buffer[pos + 2] / 255.0;
  23013. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23014. position.y = minHeight + (maxHeight - minHeight) * gradient;
  23015. // Add vertex
  23016. positions.push(position.x, position.y, position.z);
  23017. normals.push(0, 0, 0);
  23018. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23019. }
  23020. }
  23021. for (row = 0; row < subdivisions; row++) {
  23022. for (col = 0; col < subdivisions; col++) {
  23023. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23024. indices.push(col + 1 + row * (subdivisions + 1));
  23025. indices.push(col + row * (subdivisions + 1));
  23026. indices.push(col + (row + 1) * (subdivisions + 1));
  23027. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23028. indices.push(col + row * (subdivisions + 1));
  23029. }
  23030. }
  23031. // Normals
  23032. VertexData.ComputeNormals(positions, indices, normals);
  23033. // Result
  23034. var vertexData = new VertexData();
  23035. vertexData.indices = indices;
  23036. vertexData.positions = positions;
  23037. vertexData.normals = normals;
  23038. vertexData.uvs = uvs;
  23039. return vertexData;
  23040. };
  23041. VertexData.CreatePlane = function (size, sideOrientation) {
  23042. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23043. var indices = [];
  23044. var positions = [];
  23045. var normals = [];
  23046. var uvs = [];
  23047. size = size || 1;
  23048. // Vertices
  23049. var halfSize = size / 2.0;
  23050. positions.push(-halfSize, -halfSize, 0);
  23051. normals.push(0, 0, -1.0);
  23052. uvs.push(0.0, 0.0);
  23053. positions.push(halfSize, -halfSize, 0);
  23054. normals.push(0, 0, -1.0);
  23055. uvs.push(1.0, 0.0);
  23056. positions.push(halfSize, halfSize, 0);
  23057. normals.push(0, 0, -1.0);
  23058. uvs.push(1.0, 1.0);
  23059. positions.push(-halfSize, halfSize, 0);
  23060. normals.push(0, 0, -1.0);
  23061. uvs.push(0.0, 1.0);
  23062. // Indices
  23063. indices.push(0);
  23064. indices.push(1);
  23065. indices.push(2);
  23066. indices.push(0);
  23067. indices.push(2);
  23068. indices.push(3);
  23069. // Sides
  23070. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  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.CreateDisc = function (radius, tessellation, sideOrientation) {
  23080. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23081. var positions = [];
  23082. var indices = [];
  23083. var normals = [];
  23084. var uvs = [];
  23085. // positions and uvs
  23086. positions.push(0, 0, 0); // disc center first
  23087. uvs.push(0.5, 0.5);
  23088. var step = Math.PI * 2 / tessellation;
  23089. for (var a = 0; a < Math.PI * 2; a += step) {
  23090. var x = Math.cos(a);
  23091. var y = Math.sin(a);
  23092. var u = (x + 1) / 2;
  23093. var v = (1 - y) / 2;
  23094. positions.push(radius * x, radius * y, 0);
  23095. uvs.push(u, v);
  23096. }
  23097. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23098. uvs.push(uvs[2], uvs[3]);
  23099. //indices
  23100. var vertexNb = positions.length / 3;
  23101. for (var i = 1; i < vertexNb - 1; i++) {
  23102. indices.push(i + 1, 0, i);
  23103. }
  23104. // result
  23105. VertexData.ComputeNormals(positions, indices, normals);
  23106. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23107. var vertexData = new VertexData();
  23108. vertexData.indices = indices;
  23109. vertexData.positions = positions;
  23110. vertexData.normals = normals;
  23111. vertexData.uvs = uvs;
  23112. return vertexData;
  23113. };
  23114. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23115. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  23116. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23117. var indices = [];
  23118. var positions = [];
  23119. var normals = [];
  23120. var uvs = [];
  23121. radius = radius || 2;
  23122. tube = tube || 0.5;
  23123. radialSegments = radialSegments || 32;
  23124. tubularSegments = tubularSegments || 32;
  23125. p = p || 2;
  23126. q = q || 3;
  23127. // Helper
  23128. var getPos = function (angle) {
  23129. var cu = Math.cos(angle);
  23130. var su = Math.sin(angle);
  23131. var quOverP = q / p * angle;
  23132. var cs = Math.cos(quOverP);
  23133. var tx = radius * (2 + cs) * 0.5 * cu;
  23134. var ty = radius * (2 + cs) * su * 0.5;
  23135. var tz = radius * Math.sin(quOverP) * 0.5;
  23136. return new BABYLON.Vector3(tx, ty, tz);
  23137. };
  23138. for (var i = 0; i <= radialSegments; i++) {
  23139. var modI = i % radialSegments;
  23140. var u = modI / radialSegments * 2 * p * Math.PI;
  23141. var p1 = getPos(u);
  23142. var p2 = getPos(u + 0.01);
  23143. var tang = p2.subtract(p1);
  23144. var n = p2.add(p1);
  23145. var bitan = BABYLON.Vector3.Cross(tang, n);
  23146. n = BABYLON.Vector3.Cross(bitan, tang);
  23147. bitan.normalize();
  23148. n.normalize();
  23149. for (var j = 0; j < tubularSegments; j++) {
  23150. var modJ = j % tubularSegments;
  23151. var v = modJ / tubularSegments * 2 * Math.PI;
  23152. var cx = -tube * Math.cos(v);
  23153. var cy = tube * Math.sin(v);
  23154. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23155. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23156. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23157. uvs.push(i / radialSegments);
  23158. uvs.push(j / tubularSegments);
  23159. }
  23160. }
  23161. for (i = 0; i < radialSegments; i++) {
  23162. for (j = 0; j < tubularSegments; j++) {
  23163. var jNext = (j + 1) % tubularSegments;
  23164. var a = i * tubularSegments + j;
  23165. var b = (i + 1) * tubularSegments + j;
  23166. var c = (i + 1) * tubularSegments + jNext;
  23167. var d = i * tubularSegments + jNext;
  23168. indices.push(d);
  23169. indices.push(b);
  23170. indices.push(a);
  23171. indices.push(d);
  23172. indices.push(c);
  23173. indices.push(b);
  23174. }
  23175. }
  23176. // Normals
  23177. VertexData.ComputeNormals(positions, indices, normals);
  23178. // Sides
  23179. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23180. // Result
  23181. var vertexData = new VertexData();
  23182. vertexData.indices = indices;
  23183. vertexData.positions = positions;
  23184. vertexData.normals = normals;
  23185. vertexData.uvs = uvs;
  23186. return vertexData;
  23187. };
  23188. // Tools
  23189. /**
  23190. * @param {any} - positions (number[] or Float32Array)
  23191. * @param {any} - indices (number[] or Uint16Array)
  23192. * @param {any} - normals (number[] or Float32Array)
  23193. */
  23194. VertexData.ComputeNormals = function (positions, indices, normals) {
  23195. var positionVectors = [];
  23196. var facesOfVertices = [];
  23197. var index;
  23198. for (index = 0; index < positions.length; index += 3) {
  23199. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  23200. positionVectors.push(vector3);
  23201. facesOfVertices.push([]);
  23202. }
  23203. // Compute normals
  23204. var facesNormals = [];
  23205. for (index = 0; index < indices.length / 3; index++) {
  23206. var i1 = indices[index * 3];
  23207. var i2 = indices[index * 3 + 1];
  23208. var i3 = indices[index * 3 + 2];
  23209. var p1 = positionVectors[i1];
  23210. var p2 = positionVectors[i2];
  23211. var p3 = positionVectors[i3];
  23212. var p1p2 = p1.subtract(p2);
  23213. var p3p2 = p3.subtract(p2);
  23214. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23215. facesOfVertices[i1].push(index);
  23216. facesOfVertices[i2].push(index);
  23217. facesOfVertices[i3].push(index);
  23218. }
  23219. for (index = 0; index < positionVectors.length; index++) {
  23220. var faces = facesOfVertices[index];
  23221. var normal = BABYLON.Vector3.Zero();
  23222. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  23223. normal.addInPlace(facesNormals[faces[faceIndex]]);
  23224. }
  23225. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  23226. normals[index * 3] = normal.x;
  23227. normals[index * 3 + 1] = normal.y;
  23228. normals[index * 3 + 2] = normal.z;
  23229. }
  23230. };
  23231. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23232. var li = indices.length;
  23233. var ln = normals.length;
  23234. var i;
  23235. var n;
  23236. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23237. switch (sideOrientation) {
  23238. case BABYLON.Mesh.FRONTSIDE:
  23239. break;
  23240. case BABYLON.Mesh.BACKSIDE:
  23241. var tmp;
  23242. for (i = 0; i < li; i += 3) {
  23243. tmp = indices[i];
  23244. indices[i] = indices[i + 2];
  23245. indices[i + 2] = tmp;
  23246. }
  23247. for (n = 0; n < ln; n++) {
  23248. normals[n] = -normals[n];
  23249. }
  23250. break;
  23251. case BABYLON.Mesh.DOUBLESIDE:
  23252. // positions
  23253. var lp = positions.length;
  23254. var l = lp / 3;
  23255. for (var p = 0; p < lp; p++) {
  23256. positions[lp + p] = positions[p];
  23257. }
  23258. for (i = 0; i < li; i += 3) {
  23259. indices[i + li] = indices[i + 2] + l;
  23260. indices[i + 1 + li] = indices[i + 1] + l;
  23261. indices[i + 2 + li] = indices[i] + l;
  23262. }
  23263. for (n = 0; n < ln; n++) {
  23264. normals[ln + n] = -normals[n];
  23265. }
  23266. // uvs
  23267. var lu = uvs.length;
  23268. for (var u = 0; u < lu; u++) {
  23269. uvs[u + lu] = uvs[u];
  23270. }
  23271. break;
  23272. }
  23273. };
  23274. return VertexData;
  23275. })();
  23276. BABYLON.VertexData = VertexData;
  23277. })(BABYLON || (BABYLON = {}));
  23278. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23279. var BABYLON;
  23280. (function (BABYLON) {
  23281. var buildCamera = function (that, name) {
  23282. that._leftCamera.isIntermediate = true;
  23283. that.subCameras.push(that._leftCamera);
  23284. that.subCameras.push(that._rightCamera);
  23285. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23286. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23287. that._anaglyphPostProcess.onApply = function (effect) {
  23288. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23289. };
  23290. that._update();
  23291. };
  23292. var AnaglyphArcRotateCamera = (function (_super) {
  23293. __extends(AnaglyphArcRotateCamera, _super);
  23294. // ANY
  23295. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23296. _super.call(this, name, alpha, beta, radius, target, scene);
  23297. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23298. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23299. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23300. buildCamera(this, name);
  23301. }
  23302. AnaglyphArcRotateCamera.prototype._update = function () {
  23303. this._updateCamera(this._leftCamera);
  23304. this._updateCamera(this._rightCamera);
  23305. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23306. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23307. _super.prototype._update.call(this);
  23308. };
  23309. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23310. camera.beta = this.beta;
  23311. camera.radius = this.radius;
  23312. camera.minZ = this.minZ;
  23313. camera.maxZ = this.maxZ;
  23314. camera.fov = this.fov;
  23315. camera.target = this.target;
  23316. };
  23317. return AnaglyphArcRotateCamera;
  23318. })(BABYLON.ArcRotateCamera);
  23319. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23320. var AnaglyphFreeCamera = (function (_super) {
  23321. __extends(AnaglyphFreeCamera, _super);
  23322. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23323. _super.call(this, name, position, scene);
  23324. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23325. this._transformMatrix = new BABYLON.Matrix();
  23326. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23327. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23328. buildCamera(this, name);
  23329. }
  23330. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23331. var target = this.getTarget();
  23332. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23333. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23334. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23335. };
  23336. AnaglyphFreeCamera.prototype._update = function () {
  23337. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23338. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23339. this._updateCamera(this._leftCamera);
  23340. this._updateCamera(this._rightCamera);
  23341. _super.prototype._update.call(this);
  23342. };
  23343. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23344. camera.minZ = this.minZ;
  23345. camera.maxZ = this.maxZ;
  23346. camera.fov = this.fov;
  23347. camera.viewport = this.viewport;
  23348. camera.setTarget(this.getTarget());
  23349. };
  23350. return AnaglyphFreeCamera;
  23351. })(BABYLON.FreeCamera);
  23352. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23353. })(BABYLON || (BABYLON = {}));
  23354. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23355. var BABYLON;
  23356. (function (BABYLON) {
  23357. var AnaglyphPostProcess = (function (_super) {
  23358. __extends(AnaglyphPostProcess, _super);
  23359. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23360. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23361. }
  23362. return AnaglyphPostProcess;
  23363. })(BABYLON.PostProcess);
  23364. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23365. })(BABYLON || (BABYLON = {}));
  23366. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23367. (function (BABYLON) {
  23368. var Tags = (function () {
  23369. function Tags() {
  23370. }
  23371. Tags.EnableFor = function (obj) {
  23372. obj._tags = obj._tags || {};
  23373. obj.hasTags = function () {
  23374. return Tags.HasTags(obj);
  23375. };
  23376. obj.addTags = function (tagsString) {
  23377. return Tags.AddTagsTo(obj, tagsString);
  23378. };
  23379. obj.removeTags = function (tagsString) {
  23380. return Tags.RemoveTagsFrom(obj, tagsString);
  23381. };
  23382. obj.matchesTagsQuery = function (tagsQuery) {
  23383. return Tags.MatchesQuery(obj, tagsQuery);
  23384. };
  23385. };
  23386. Tags.DisableFor = function (obj) {
  23387. delete obj._tags;
  23388. delete obj.hasTags;
  23389. delete obj.addTags;
  23390. delete obj.removeTags;
  23391. delete obj.matchesTagsQuery;
  23392. };
  23393. Tags.HasTags = function (obj) {
  23394. if (!obj._tags) {
  23395. return false;
  23396. }
  23397. return !BABYLON.Tools.IsEmpty(obj._tags);
  23398. };
  23399. Tags.GetTags = function (obj) {
  23400. if (!obj._tags) {
  23401. return null;
  23402. }
  23403. return obj._tags;
  23404. };
  23405. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23406. // a tag cannot start with '||', '&&', and '!'
  23407. // it cannot contain whitespaces
  23408. Tags.AddTagsTo = function (obj, tagsString) {
  23409. if (!tagsString) {
  23410. return;
  23411. }
  23412. var tags = tagsString.split(" ");
  23413. for (var t in tags) {
  23414. Tags._AddTagTo(obj, tags[t]);
  23415. }
  23416. };
  23417. Tags._AddTagTo = function (obj, tag) {
  23418. tag = tag.trim();
  23419. if (tag === "" || tag === "true" || tag === "false") {
  23420. return;
  23421. }
  23422. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23423. return;
  23424. }
  23425. Tags.EnableFor(obj);
  23426. obj._tags[tag] = true;
  23427. };
  23428. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23429. if (!Tags.HasTags(obj)) {
  23430. return;
  23431. }
  23432. var tags = tagsString.split(" ");
  23433. for (var t in tags) {
  23434. Tags._RemoveTagFrom(obj, tags[t]);
  23435. }
  23436. };
  23437. Tags._RemoveTagFrom = function (obj, tag) {
  23438. delete obj._tags[tag];
  23439. };
  23440. Tags.MatchesQuery = function (obj, tagsQuery) {
  23441. if (tagsQuery === undefined) {
  23442. return true;
  23443. }
  23444. if (tagsQuery === "") {
  23445. return Tags.HasTags(obj);
  23446. }
  23447. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23448. };
  23449. return Tags;
  23450. })();
  23451. BABYLON.Tags = Tags;
  23452. })(BABYLON || (BABYLON = {}));
  23453. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23454. (function (BABYLON) {
  23455. var Internals;
  23456. (function (Internals) {
  23457. var AndOrNotEvaluator = (function () {
  23458. function AndOrNotEvaluator() {
  23459. }
  23460. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23461. if (!query.match(/\([^\(\)]*\)/g)) {
  23462. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23463. }
  23464. else {
  23465. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23466. // remove parenthesis
  23467. r = r.slice(1, r.length - 1);
  23468. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23469. });
  23470. }
  23471. if (query === "true") {
  23472. return true;
  23473. }
  23474. if (query === "false") {
  23475. return false;
  23476. }
  23477. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23478. };
  23479. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23480. evaluateCallback = evaluateCallback || (function (r) {
  23481. return r === "true" ? true : false;
  23482. });
  23483. var result;
  23484. var or = parenthesisContent.split("||");
  23485. for (var i in or) {
  23486. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23487. var and = ori.split("&&");
  23488. if (and.length > 1) {
  23489. for (var j = 0; j < and.length; ++j) {
  23490. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23491. if (andj !== "true" && andj !== "false") {
  23492. if (andj[0] === "!") {
  23493. result = !evaluateCallback(andj.substring(1));
  23494. }
  23495. else {
  23496. result = evaluateCallback(andj);
  23497. }
  23498. }
  23499. else {
  23500. result = andj === "true" ? true : false;
  23501. }
  23502. if (!result) {
  23503. ori = "false";
  23504. break;
  23505. }
  23506. }
  23507. }
  23508. if (result || ori === "true") {
  23509. result = true;
  23510. break;
  23511. }
  23512. // result equals false (or undefined)
  23513. if (ori !== "true" && ori !== "false") {
  23514. if (ori[0] === "!") {
  23515. result = !evaluateCallback(ori.substring(1));
  23516. }
  23517. else {
  23518. result = evaluateCallback(ori);
  23519. }
  23520. }
  23521. else {
  23522. result = ori === "true" ? true : false;
  23523. }
  23524. }
  23525. // the whole parenthesis scope is replaced by 'true' or 'false'
  23526. return result ? "true" : "false";
  23527. };
  23528. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23529. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23530. // remove whitespaces
  23531. r = r.replace(/[\s]/g, function () { return ""; });
  23532. return r.length % 2 ? "!" : "";
  23533. });
  23534. booleanString = booleanString.trim();
  23535. if (booleanString === "!true") {
  23536. booleanString = "false";
  23537. }
  23538. else if (booleanString === "!false") {
  23539. booleanString = "true";
  23540. }
  23541. return booleanString;
  23542. };
  23543. return AndOrNotEvaluator;
  23544. })();
  23545. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23546. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23547. })(BABYLON || (BABYLON = {}));
  23548. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23549. (function (BABYLON) {
  23550. var PostProcessRenderPass = (function () {
  23551. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23552. this._enabled = true;
  23553. this._refCount = 0;
  23554. this._name = name;
  23555. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23556. this.setRenderList(renderList);
  23557. this._renderTexture.onBeforeRender = beforeRender;
  23558. this._renderTexture.onAfterRender = afterRender;
  23559. this._scene = scene;
  23560. this._renderList = renderList;
  23561. }
  23562. // private
  23563. PostProcessRenderPass.prototype._incRefCount = function () {
  23564. if (this._refCount === 0) {
  23565. this._scene.customRenderTargets.push(this._renderTexture);
  23566. }
  23567. return ++this._refCount;
  23568. };
  23569. PostProcessRenderPass.prototype._decRefCount = function () {
  23570. this._refCount--;
  23571. if (this._refCount <= 0) {
  23572. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23573. }
  23574. return this._refCount;
  23575. };
  23576. PostProcessRenderPass.prototype._update = function () {
  23577. this.setRenderList(this._renderList);
  23578. };
  23579. // public
  23580. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23581. this._renderTexture.renderList = renderList;
  23582. };
  23583. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23584. return this._renderTexture;
  23585. };
  23586. return PostProcessRenderPass;
  23587. })();
  23588. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23589. })(BABYLON || (BABYLON = {}));
  23590. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23591. (function (BABYLON) {
  23592. var PostProcessRenderEffect = (function () {
  23593. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23594. this._engine = engine;
  23595. this._name = name;
  23596. this._singleInstance = singleInstance || true;
  23597. this._getPostProcess = getPostProcess;
  23598. this._cameras = [];
  23599. this._indicesForCamera = [];
  23600. this._postProcesses = {};
  23601. this._renderPasses = {};
  23602. this._renderEffectAsPasses = {};
  23603. }
  23604. PostProcessRenderEffect.prototype._update = function () {
  23605. for (var renderPassName in this._renderPasses) {
  23606. this._renderPasses[renderPassName]._update();
  23607. }
  23608. };
  23609. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23610. this._renderPasses[renderPass._name] = renderPass;
  23611. this._linkParameters();
  23612. };
  23613. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23614. delete this._renderPasses[renderPass._name];
  23615. this._linkParameters();
  23616. };
  23617. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23618. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23619. this._linkParameters();
  23620. };
  23621. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23622. for (var renderPassName in this._renderPasses) {
  23623. if (renderPassName === passName) {
  23624. return this._renderPasses[passName];
  23625. }
  23626. }
  23627. };
  23628. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23629. this._renderPasses = {};
  23630. this._linkParameters();
  23631. };
  23632. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23633. var cameraKey;
  23634. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23635. for (var i = 0; i < _cam.length; i++) {
  23636. var camera = _cam[i];
  23637. var cameraName = camera.name;
  23638. if (this._singleInstance) {
  23639. cameraKey = 0;
  23640. }
  23641. else {
  23642. cameraKey = cameraName;
  23643. }
  23644. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23645. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23646. if (!this._indicesForCamera[cameraName]) {
  23647. this._indicesForCamera[cameraName] = [];
  23648. }
  23649. this._indicesForCamera[cameraName].push(index);
  23650. if (this._cameras.indexOf(camera) === -1) {
  23651. this._cameras[cameraName] = camera;
  23652. }
  23653. for (var passName in this._renderPasses) {
  23654. this._renderPasses[passName]._incRefCount();
  23655. }
  23656. }
  23657. this._linkParameters();
  23658. };
  23659. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23660. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23661. for (var i = 0; i < _cam.length; i++) {
  23662. var camera = _cam[i];
  23663. var cameraName = camera.name;
  23664. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23665. var index = this._cameras.indexOf(cameraName);
  23666. this._indicesForCamera.splice(index, 1);
  23667. this._cameras.splice(index, 1);
  23668. for (var passName in this._renderPasses) {
  23669. this._renderPasses[passName]._decRefCount();
  23670. }
  23671. }
  23672. };
  23673. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23674. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23675. for (var i = 0; i < _cam.length; i++) {
  23676. var camera = _cam[i];
  23677. var cameraName = camera.name;
  23678. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23679. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23680. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23681. }
  23682. }
  23683. for (var passName in this._renderPasses) {
  23684. this._renderPasses[passName]._incRefCount();
  23685. }
  23686. }
  23687. };
  23688. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23689. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23690. for (var i = 0; i < _cam.length; i++) {
  23691. var camera = _cam[i];
  23692. var cameraName = camera.Name;
  23693. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23694. for (var passName in this._renderPasses) {
  23695. this._renderPasses[passName]._decRefCount();
  23696. }
  23697. }
  23698. };
  23699. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23700. if (this._singleInstance) {
  23701. return this._postProcesses[0];
  23702. }
  23703. else {
  23704. return this._postProcesses[camera.name];
  23705. }
  23706. };
  23707. PostProcessRenderEffect.prototype._linkParameters = function () {
  23708. var _this = this;
  23709. for (var index in this._postProcesses) {
  23710. if (this.applyParameters) {
  23711. this.applyParameters(this._postProcesses[index]);
  23712. }
  23713. this._postProcesses[index].onBeforeRender = function (effect) {
  23714. _this._linkTextures(effect);
  23715. };
  23716. }
  23717. };
  23718. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23719. for (var renderPassName in this._renderPasses) {
  23720. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23721. }
  23722. for (var renderEffectName in this._renderEffectAsPasses) {
  23723. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23724. }
  23725. };
  23726. return PostProcessRenderEffect;
  23727. })();
  23728. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23729. })(BABYLON || (BABYLON = {}));
  23730. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23731. (function (BABYLON) {
  23732. var PostProcessRenderPipeline = (function () {
  23733. function PostProcessRenderPipeline(engine, name) {
  23734. this._engine = engine;
  23735. this._name = name;
  23736. this._renderEffects = {};
  23737. this._renderEffectsForIsolatedPass = {};
  23738. this._cameras = [];
  23739. }
  23740. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23741. this._renderEffects[renderEffect._name] = renderEffect;
  23742. };
  23743. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23744. var renderEffects = this._renderEffects[renderEffectName];
  23745. if (!renderEffects) {
  23746. return;
  23747. }
  23748. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23749. };
  23750. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23751. var renderEffects = this._renderEffects[renderEffectName];
  23752. if (!renderEffects) {
  23753. return;
  23754. }
  23755. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23756. };
  23757. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23758. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23759. var indicesToDelete = [];
  23760. for (var i = 0; i < _cam.length; i++) {
  23761. var camera = _cam[i];
  23762. var cameraName = camera.name;
  23763. if (this._cameras.indexOf(camera) === -1) {
  23764. this._cameras[cameraName] = camera;
  23765. }
  23766. else if (unique) {
  23767. indicesToDelete.push(i);
  23768. }
  23769. }
  23770. for (var i = 0; i < indicesToDelete.length; i++) {
  23771. cameras.splice(indicesToDelete[i], 1);
  23772. }
  23773. for (var renderEffectName in this._renderEffects) {
  23774. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23775. }
  23776. };
  23777. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23778. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23779. for (var renderEffectName in this._renderEffects) {
  23780. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23781. }
  23782. for (var i = 0; i < _cam.length; i++) {
  23783. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23784. }
  23785. };
  23786. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23787. var _this = this;
  23788. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23789. var pass = null;
  23790. for (var renderEffectName in this._renderEffects) {
  23791. pass = this._renderEffects[renderEffectName].getPass(passName);
  23792. if (pass != null) {
  23793. break;
  23794. }
  23795. }
  23796. if (pass === null) {
  23797. return;
  23798. }
  23799. for (var renderEffectName in this._renderEffects) {
  23800. this._renderEffects[renderEffectName]._disable(_cam);
  23801. }
  23802. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23803. for (var i = 0; i < _cam.length; i++) {
  23804. var camera = _cam[i];
  23805. var cameraName = camera.name;
  23806. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23807. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23808. });
  23809. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23810. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23811. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23812. }
  23813. };
  23814. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23815. var _this = this;
  23816. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23817. for (var i = 0; i < _cam.length; i++) {
  23818. var camera = _cam[i];
  23819. var cameraName = camera.name;
  23820. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23821. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23822. });
  23823. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23824. }
  23825. for (var renderEffectName in this._renderEffects) {
  23826. this._renderEffects[renderEffectName]._enable(_cam);
  23827. }
  23828. };
  23829. PostProcessRenderPipeline.prototype._update = function () {
  23830. for (var renderEffectName in this._renderEffects) {
  23831. this._renderEffects[renderEffectName]._update();
  23832. }
  23833. for (var i = 0; i < this._cameras.length; i++) {
  23834. var cameraName = this._cameras[i].name;
  23835. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23836. this._renderEffectsForIsolatedPass[cameraName]._update();
  23837. }
  23838. }
  23839. };
  23840. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23841. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23842. return PostProcessRenderPipeline;
  23843. })();
  23844. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23845. })(BABYLON || (BABYLON = {}));
  23846. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23847. (function (BABYLON) {
  23848. var PostProcessRenderPipelineManager = (function () {
  23849. function PostProcessRenderPipelineManager() {
  23850. this._renderPipelines = {};
  23851. }
  23852. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23853. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23854. };
  23855. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23856. var renderPipeline = this._renderPipelines[renderPipelineName];
  23857. if (!renderPipeline) {
  23858. return;
  23859. }
  23860. renderPipeline._attachCameras(cameras, unique);
  23861. };
  23862. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23863. var renderPipeline = this._renderPipelines[renderPipelineName];
  23864. if (!renderPipeline) {
  23865. return;
  23866. }
  23867. renderPipeline._detachCameras(cameras);
  23868. };
  23869. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23870. var renderPipeline = this._renderPipelines[renderPipelineName];
  23871. if (!renderPipeline) {
  23872. return;
  23873. }
  23874. renderPipeline._enableEffect(renderEffectName, cameras);
  23875. };
  23876. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23877. var renderPipeline = this._renderPipelines[renderPipelineName];
  23878. if (!renderPipeline) {
  23879. return;
  23880. }
  23881. renderPipeline._disableEffect(renderEffectName, cameras);
  23882. };
  23883. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23884. var renderPipeline = this._renderPipelines[renderPipelineName];
  23885. if (!renderPipeline) {
  23886. return;
  23887. }
  23888. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23889. };
  23890. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23891. var renderPipeline = this._renderPipelines[renderPipelineName];
  23892. if (!renderPipeline) {
  23893. return;
  23894. }
  23895. renderPipeline._disableDisplayOnlyPass(cameras);
  23896. };
  23897. PostProcessRenderPipelineManager.prototype.update = function () {
  23898. for (var renderPipelineName in this._renderPipelines) {
  23899. this._renderPipelines[renderPipelineName]._update();
  23900. }
  23901. };
  23902. return PostProcessRenderPipelineManager;
  23903. })();
  23904. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23905. })(BABYLON || (BABYLON = {}));
  23906. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23907. var BABYLON;
  23908. (function (BABYLON) {
  23909. var DisplayPassPostProcess = (function (_super) {
  23910. __extends(DisplayPassPostProcess, _super);
  23911. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23912. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23913. }
  23914. return DisplayPassPostProcess;
  23915. })(BABYLON.PostProcess);
  23916. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23917. })(BABYLON || (BABYLON = {}));
  23918. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23919. (function (BABYLON) {
  23920. var BoundingBoxRenderer = (function () {
  23921. function BoundingBoxRenderer(scene) {
  23922. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23923. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23924. this.showBackLines = true;
  23925. this.renderList = new BABYLON.SmartArray(32);
  23926. this._scene = scene;
  23927. }
  23928. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23929. if (this._colorShader) {
  23930. return;
  23931. }
  23932. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23933. attributes: ["position"],
  23934. uniforms: ["worldViewProjection", "color"]
  23935. });
  23936. var engine = this._scene.getEngine();
  23937. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23938. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23939. 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]);
  23940. };
  23941. BoundingBoxRenderer.prototype.reset = function () {
  23942. this.renderList.reset();
  23943. };
  23944. BoundingBoxRenderer.prototype.render = function () {
  23945. if (this.renderList.length === 0) {
  23946. return;
  23947. }
  23948. this._prepareRessources();
  23949. if (!this._colorShader.isReady()) {
  23950. return;
  23951. }
  23952. var engine = this._scene.getEngine();
  23953. engine.setDepthWrite(false);
  23954. this._colorShader._preBind();
  23955. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23956. var boundingBox = this.renderList.data[boundingBoxIndex];
  23957. var min = boundingBox.minimum;
  23958. var max = boundingBox.maximum;
  23959. var diff = max.subtract(min);
  23960. var median = min.add(diff.scale(0.5));
  23961. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23962. // VBOs
  23963. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23964. if (this.showBackLines) {
  23965. // Back
  23966. engine.setDepthFunctionToGreaterOrEqual();
  23967. this._scene.resetCachedMaterial();
  23968. this._colorShader.setColor4("color", this.backColor.toColor4());
  23969. this._colorShader.bind(worldMatrix);
  23970. // Draw order
  23971. engine.draw(false, 0, 24);
  23972. }
  23973. // Front
  23974. engine.setDepthFunctionToLess();
  23975. this._scene.resetCachedMaterial();
  23976. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23977. this._colorShader.bind(worldMatrix);
  23978. // Draw order
  23979. engine.draw(false, 0, 24);
  23980. }
  23981. this._colorShader.unbind();
  23982. engine.setDepthFunctionToLessOrEqual();
  23983. engine.setDepthWrite(true);
  23984. };
  23985. BoundingBoxRenderer.prototype.dispose = function () {
  23986. if (!this._colorShader) {
  23987. return;
  23988. }
  23989. this._colorShader.dispose();
  23990. this._vb.dispose();
  23991. this._scene.getEngine()._releaseBuffer(this._ib);
  23992. };
  23993. return BoundingBoxRenderer;
  23994. })();
  23995. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23996. })(BABYLON || (BABYLON = {}));
  23997. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23998. (function (BABYLON) {
  23999. var Internals;
  24000. (function (Internals) {
  24001. /*
  24002. * Based on jsTGALoader - Javascript loader for TGA file
  24003. * By Vincent Thibault
  24004. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  24005. */
  24006. var TGATools = (function () {
  24007. function TGATools() {
  24008. }
  24009. TGATools.GetTGAHeader = function (data) {
  24010. var offset = 0;
  24011. var header = {
  24012. id_length: data[offset++],
  24013. colormap_type: data[offset++],
  24014. image_type: data[offset++],
  24015. colormap_index: data[offset++] | data[offset++] << 8,
  24016. colormap_length: data[offset++] | data[offset++] << 8,
  24017. colormap_size: data[offset++],
  24018. origin: [
  24019. data[offset++] | data[offset++] << 8,
  24020. data[offset++] | data[offset++] << 8
  24021. ],
  24022. width: data[offset++] | data[offset++] << 8,
  24023. height: data[offset++] | data[offset++] << 8,
  24024. pixel_size: data[offset++],
  24025. flags: data[offset++]
  24026. };
  24027. return header;
  24028. };
  24029. TGATools.UploadContent = function (gl, data) {
  24030. // Not enough data to contain header ?
  24031. if (data.length < 19) {
  24032. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  24033. return;
  24034. }
  24035. // Read Header
  24036. var offset = 18;
  24037. var header = TGATools.GetTGAHeader(data);
  24038. // Assume it's a valid Targa file.
  24039. if (header.id_length + offset > data.length) {
  24040. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  24041. return;
  24042. }
  24043. // Skip not needed data
  24044. offset += header.id_length;
  24045. var use_rle = false;
  24046. var use_pal = false;
  24047. var use_rgb = false;
  24048. var use_grey = false;
  24049. switch (header.image_type) {
  24050. case TGATools._TYPE_RLE_INDEXED:
  24051. use_rle = true;
  24052. case TGATools._TYPE_INDEXED:
  24053. use_pal = true;
  24054. break;
  24055. case TGATools._TYPE_RLE_RGB:
  24056. use_rle = true;
  24057. case TGATools._TYPE_RGB:
  24058. use_rgb = true;
  24059. break;
  24060. case TGATools._TYPE_RLE_GREY:
  24061. use_rle = true;
  24062. case TGATools._TYPE_GREY:
  24063. use_grey = true;
  24064. break;
  24065. }
  24066. var pixel_data;
  24067. var numAlphaBits = header.flags & 0xf;
  24068. var pixel_size = header.pixel_size >> 3;
  24069. var pixel_total = header.width * header.height * pixel_size;
  24070. // Read palettes
  24071. var palettes;
  24072. if (use_pal) {
  24073. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  24074. }
  24075. // Read LRE
  24076. if (use_rle) {
  24077. pixel_data = new Uint8Array(pixel_total);
  24078. var c, count, i;
  24079. var localOffset = 0;
  24080. var pixels = new Uint8Array(pixel_size);
  24081. while (offset < pixel_total && localOffset < pixel_total) {
  24082. c = data[offset++];
  24083. count = (c & 0x7f) + 1;
  24084. // RLE pixels
  24085. if (c & 0x80) {
  24086. for (i = 0; i < pixel_size; ++i) {
  24087. pixels[i] = data[offset++];
  24088. }
  24089. for (i = 0; i < count; ++i) {
  24090. pixel_data.set(pixels, localOffset + i * pixel_size);
  24091. }
  24092. localOffset += pixel_size * count;
  24093. }
  24094. else {
  24095. count *= pixel_size;
  24096. for (i = 0; i < count; ++i) {
  24097. pixel_data[localOffset + i] = data[offset++];
  24098. }
  24099. localOffset += count;
  24100. }
  24101. }
  24102. }
  24103. else {
  24104. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  24105. }
  24106. // Load to texture
  24107. var x_start, y_start, x_step, y_step, y_end, x_end;
  24108. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  24109. default:
  24110. case TGATools._ORIGIN_UL:
  24111. x_start = 0;
  24112. x_step = 1;
  24113. x_end = header.width;
  24114. y_start = 0;
  24115. y_step = 1;
  24116. y_end = header.height;
  24117. break;
  24118. case TGATools._ORIGIN_BL:
  24119. x_start = 0;
  24120. x_step = 1;
  24121. x_end = header.width;
  24122. y_start = header.height - 1;
  24123. y_step = -1;
  24124. y_end = -1;
  24125. break;
  24126. case TGATools._ORIGIN_UR:
  24127. x_start = header.width - 1;
  24128. x_step = -1;
  24129. x_end = -1;
  24130. y_start = 0;
  24131. y_step = 1;
  24132. y_end = header.height;
  24133. break;
  24134. case TGATools._ORIGIN_BR:
  24135. x_start = header.width - 1;
  24136. x_step = -1;
  24137. x_end = -1;
  24138. y_start = header.height - 1;
  24139. y_step = -1;
  24140. y_end = -1;
  24141. break;
  24142. }
  24143. // Load the specify method
  24144. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  24145. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  24146. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  24147. };
  24148. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24149. var image = pixel_data, colormap = palettes;
  24150. var width = header.width, height = header.height;
  24151. var color, i = 0, x, y;
  24152. var imageData = new Uint8Array(width * height * 4);
  24153. for (y = y_start; y !== y_end; y += y_step) {
  24154. for (x = x_start; x !== x_end; x += x_step, i++) {
  24155. color = image[i];
  24156. imageData[(x + width * y) * 4 + 3] = 255;
  24157. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  24158. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  24159. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  24160. }
  24161. }
  24162. return imageData;
  24163. };
  24164. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24165. var image = pixel_data;
  24166. var width = header.width, height = header.height;
  24167. var color, i = 0, x, y;
  24168. var imageData = new Uint8Array(width * height * 4);
  24169. for (y = y_start; y !== y_end; y += y_step) {
  24170. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24171. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  24172. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  24173. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  24174. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  24175. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  24176. }
  24177. }
  24178. return imageData;
  24179. };
  24180. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24181. var image = pixel_data;
  24182. var width = header.width, height = header.height;
  24183. var i = 0, x, y;
  24184. var imageData = new Uint8Array(width * height * 4);
  24185. for (y = y_start; y !== y_end; y += y_step) {
  24186. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  24187. imageData[(x + width * y) * 4 + 3] = 255;
  24188. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24189. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24190. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24191. }
  24192. }
  24193. return imageData;
  24194. };
  24195. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24196. var image = pixel_data;
  24197. var width = header.width, height = header.height;
  24198. var i = 0, x, y;
  24199. var imageData = new Uint8Array(width * height * 4);
  24200. for (y = y_start; y !== y_end; y += y_step) {
  24201. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  24202. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24203. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24204. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24205. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  24206. }
  24207. }
  24208. return imageData;
  24209. };
  24210. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24211. var image = pixel_data;
  24212. var width = header.width, height = header.height;
  24213. var color, i = 0, x, y;
  24214. var imageData = new Uint8Array(width * height * 4);
  24215. for (y = y_start; y !== y_end; y += y_step) {
  24216. for (x = x_start; x !== x_end; x += x_step, i++) {
  24217. color = image[i];
  24218. imageData[(x + width * y) * 4 + 0] = color;
  24219. imageData[(x + width * y) * 4 + 1] = color;
  24220. imageData[(x + width * y) * 4 + 2] = color;
  24221. imageData[(x + width * y) * 4 + 3] = 255;
  24222. }
  24223. }
  24224. return imageData;
  24225. };
  24226. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24227. var image = pixel_data;
  24228. var width = header.width, height = header.height;
  24229. var i = 0, x, y;
  24230. var imageData = new Uint8Array(width * height * 4);
  24231. for (y = y_start; y !== y_end; y += y_step) {
  24232. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24233. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  24234. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  24235. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24236. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  24237. }
  24238. }
  24239. return imageData;
  24240. };
  24241. TGATools._TYPE_NO_DATA = 0;
  24242. TGATools._TYPE_INDEXED = 1;
  24243. TGATools._TYPE_RGB = 2;
  24244. TGATools._TYPE_GREY = 3;
  24245. TGATools._TYPE_RLE_INDEXED = 9;
  24246. TGATools._TYPE_RLE_RGB = 10;
  24247. TGATools._TYPE_RLE_GREY = 11;
  24248. TGATools._ORIGIN_MASK = 0x30;
  24249. TGATools._ORIGIN_SHIFT = 0x04;
  24250. TGATools._ORIGIN_BL = 0x00;
  24251. TGATools._ORIGIN_BR = 0x01;
  24252. TGATools._ORIGIN_UL = 0x02;
  24253. TGATools._ORIGIN_UR = 0x03;
  24254. return TGATools;
  24255. })();
  24256. Internals.TGATools = TGATools;
  24257. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24258. })(BABYLON || (BABYLON = {}));
  24259. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24260. (function (BABYLON) {
  24261. var Internals;
  24262. (function (Internals) {
  24263. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24264. // All values and structures referenced from:
  24265. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24266. var DDS_MAGIC = 0x20534444;
  24267. 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;
  24268. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24269. 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;
  24270. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24271. function FourCCToInt32(value) {
  24272. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24273. }
  24274. function Int32ToFourCC(value) {
  24275. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24276. }
  24277. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24278. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24279. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24280. var headerLengthInt = 31; // The header length in 32 bit ints
  24281. // Offsets into the header array
  24282. var off_magic = 0;
  24283. var off_size = 1;
  24284. var off_flags = 2;
  24285. var off_height = 3;
  24286. var off_width = 4;
  24287. var off_mipmapCount = 7;
  24288. var off_pfFlags = 20;
  24289. var off_pfFourCC = 21;
  24290. var off_RGBbpp = 22;
  24291. var off_RMask = 23;
  24292. var off_GMask = 24;
  24293. var off_BMask = 25;
  24294. var off_AMask = 26;
  24295. var off_caps1 = 27;
  24296. var off_caps2 = 28;
  24297. ;
  24298. var DDSTools = (function () {
  24299. function DDSTools() {
  24300. }
  24301. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24302. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24303. var mipmapCount = 1;
  24304. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24305. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24306. }
  24307. return {
  24308. width: header[off_width],
  24309. height: header[off_height],
  24310. mipmapCount: mipmapCount,
  24311. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24312. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24313. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24314. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24315. };
  24316. };
  24317. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24318. var byteArray = new Uint8Array(dataLength);
  24319. var srcData = new Uint8Array(arrayBuffer);
  24320. var index = 0;
  24321. for (var y = height - 1; y >= 0; y--) {
  24322. for (var x = 0; x < width; x++) {
  24323. var srcPos = dataOffset + (x + y * width) * 4;
  24324. byteArray[index + 2] = srcData[srcPos];
  24325. byteArray[index + 1] = srcData[srcPos + 1];
  24326. byteArray[index] = srcData[srcPos + 2];
  24327. byteArray[index + 3] = srcData[srcPos + 3];
  24328. index += 4;
  24329. }
  24330. }
  24331. return byteArray;
  24332. };
  24333. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24334. var byteArray = new Uint8Array(dataLength);
  24335. var srcData = new Uint8Array(arrayBuffer);
  24336. var index = 0;
  24337. for (var y = height - 1; y >= 0; y--) {
  24338. for (var x = 0; x < width; x++) {
  24339. var srcPos = dataOffset + (x + y * width) * 3;
  24340. byteArray[index + 2] = srcData[srcPos];
  24341. byteArray[index + 1] = srcData[srcPos + 1];
  24342. byteArray[index] = srcData[srcPos + 2];
  24343. index += 3;
  24344. }
  24345. }
  24346. return byteArray;
  24347. };
  24348. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24349. var byteArray = new Uint8Array(dataLength);
  24350. var srcData = new Uint8Array(arrayBuffer);
  24351. var index = 0;
  24352. for (var y = height - 1; y >= 0; y--) {
  24353. for (var x = 0; x < width; x++) {
  24354. var srcPos = dataOffset + (x + y * width);
  24355. byteArray[index] = srcData[srcPos];
  24356. index++;
  24357. }
  24358. }
  24359. return byteArray;
  24360. };
  24361. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24362. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24363. if (header[off_magic] != DDS_MAGIC) {
  24364. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24365. return;
  24366. }
  24367. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24368. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24369. return;
  24370. }
  24371. if (info.isFourCC) {
  24372. fourCC = header[off_pfFourCC];
  24373. switch (fourCC) {
  24374. case FOURCC_DXT1:
  24375. blockBytes = 8;
  24376. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24377. break;
  24378. case FOURCC_DXT3:
  24379. blockBytes = 16;
  24380. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24381. break;
  24382. case FOURCC_DXT5:
  24383. blockBytes = 16;
  24384. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24385. break;
  24386. default:
  24387. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24388. return;
  24389. }
  24390. }
  24391. mipmapCount = 1;
  24392. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24393. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24394. }
  24395. var bpp = header[off_RGBbpp];
  24396. for (var face = 0; face < faces; face++) {
  24397. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24398. width = header[off_width];
  24399. height = header[off_height];
  24400. dataOffset = header[off_size] + 4;
  24401. for (i = 0; i < mipmapCount; ++i) {
  24402. if (info.isRGB) {
  24403. if (bpp == 24) {
  24404. dataLength = width * height * 3;
  24405. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24406. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24407. }
  24408. else {
  24409. dataLength = width * height * 4;
  24410. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24411. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24412. }
  24413. }
  24414. else if (info.isLuminance) {
  24415. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24416. var unpaddedRowSize = width;
  24417. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24418. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24419. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24420. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24421. }
  24422. else {
  24423. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24424. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24425. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24426. }
  24427. dataOffset += dataLength;
  24428. width *= 0.5;
  24429. height *= 0.5;
  24430. width = Math.max(1.0, width);
  24431. height = Math.max(1.0, height);
  24432. }
  24433. }
  24434. };
  24435. return DDSTools;
  24436. })();
  24437. Internals.DDSTools = DDSTools;
  24438. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24439. })(BABYLON || (BABYLON = {}));
  24440. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24441. (function (BABYLON) {
  24442. var SmartArray = (function () {
  24443. function SmartArray(capacity) {
  24444. this.length = 0;
  24445. this._duplicateId = 0;
  24446. this.data = new Array(capacity);
  24447. this._id = SmartArray._GlobalId++;
  24448. }
  24449. SmartArray.prototype.push = function (value) {
  24450. this.data[this.length++] = value;
  24451. if (this.length > this.data.length) {
  24452. this.data.length *= 2;
  24453. }
  24454. if (!value.__smartArrayFlags) {
  24455. value.__smartArrayFlags = {};
  24456. }
  24457. value.__smartArrayFlags[this._id] = this._duplicateId;
  24458. };
  24459. SmartArray.prototype.pushNoDuplicate = function (value) {
  24460. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24461. return;
  24462. }
  24463. this.push(value);
  24464. };
  24465. SmartArray.prototype.sort = function (compareFn) {
  24466. this.data.sort(compareFn);
  24467. };
  24468. SmartArray.prototype.reset = function () {
  24469. this.length = 0;
  24470. this._duplicateId++;
  24471. };
  24472. SmartArray.prototype.concat = function (array) {
  24473. if (array.length === 0) {
  24474. return;
  24475. }
  24476. if (this.length + array.length > this.data.length) {
  24477. this.data.length = (this.length + array.length) * 2;
  24478. }
  24479. for (var index = 0; index < array.length; index++) {
  24480. this.data[this.length++] = (array.data || array)[index];
  24481. }
  24482. };
  24483. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24484. if (array.length === 0) {
  24485. return;
  24486. }
  24487. if (this.length + array.length > this.data.length) {
  24488. this.data.length = (this.length + array.length) * 2;
  24489. }
  24490. for (var index = 0; index < array.length; index++) {
  24491. var item = (array.data || array)[index];
  24492. this.pushNoDuplicate(item);
  24493. }
  24494. };
  24495. SmartArray.prototype.indexOf = function (value) {
  24496. var position = this.data.indexOf(value);
  24497. if (position >= this.length) {
  24498. return -1;
  24499. }
  24500. return position;
  24501. };
  24502. // Statics
  24503. SmartArray._GlobalId = 0;
  24504. return SmartArray;
  24505. })();
  24506. BABYLON.SmartArray = SmartArray;
  24507. })(BABYLON || (BABYLON = {}));
  24508. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24509. (function (BABYLON) {
  24510. var CannonJSPlugin = (function () {
  24511. function CannonJSPlugin() {
  24512. this._registeredMeshes = [];
  24513. this._physicsMaterials = [];
  24514. this.updateBodyPosition = function (mesh) {
  24515. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24516. var registeredMesh = this._registeredMeshes[index];
  24517. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24518. var body = registeredMesh.body;
  24519. var center = mesh.getBoundingInfo().boundingBox.center;
  24520. body.position.set(center.x, center.z, center.y);
  24521. body.quaternion.x = mesh.rotationQuaternion.x;
  24522. body.quaternion.z = mesh.rotationQuaternion.y;
  24523. body.quaternion.y = mesh.rotationQuaternion.z;
  24524. body.quaternion.w = -mesh.rotationQuaternion.w;
  24525. return;
  24526. }
  24527. }
  24528. };
  24529. }
  24530. CannonJSPlugin.prototype.initialize = function (iterations) {
  24531. if (iterations === void 0) { iterations = 10; }
  24532. this._world = new CANNON.World();
  24533. this._world.broadphase = new CANNON.NaiveBroadphase();
  24534. this._world.solver.iterations = iterations;
  24535. };
  24536. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24537. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24538. };
  24539. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24540. this._world.step(delta);
  24541. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24542. var registeredMesh = this._registeredMeshes[index];
  24543. if (registeredMesh.isChild) {
  24544. continue;
  24545. }
  24546. // Body position
  24547. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24548. var deltaPos = registeredMesh.delta;
  24549. if (deltaPos) {
  24550. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24551. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24552. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24553. }
  24554. else {
  24555. registeredMesh.mesh.position.x = bodyX;
  24556. registeredMesh.mesh.position.y = bodyZ;
  24557. registeredMesh.mesh.position.z = bodyY;
  24558. }
  24559. if (!registeredMesh.mesh.rotationQuaternion) {
  24560. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24561. }
  24562. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24563. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24564. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24565. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24566. }
  24567. };
  24568. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24569. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24570. };
  24571. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24572. this.unregisterMesh(mesh);
  24573. mesh.computeWorldMatrix(true);
  24574. switch (impostor) {
  24575. case BABYLON.PhysicsEngine.SphereImpostor:
  24576. var bbox = mesh.getBoundingInfo().boundingBox;
  24577. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24578. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24579. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24580. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24581. case BABYLON.PhysicsEngine.BoxImpostor:
  24582. bbox = mesh.getBoundingInfo().boundingBox;
  24583. var min = bbox.minimumWorld;
  24584. var max = bbox.maximumWorld;
  24585. var box = max.subtract(min).scale(0.5);
  24586. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24587. case BABYLON.PhysicsEngine.PlaneImpostor:
  24588. return this._createPlane(mesh, options);
  24589. case BABYLON.PhysicsEngine.MeshImpostor:
  24590. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24591. var rawFaces = mesh.getIndices();
  24592. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24593. }
  24594. return null;
  24595. };
  24596. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24597. var shape = new CANNON.Sphere(radius);
  24598. if (!options) {
  24599. return shape;
  24600. }
  24601. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24602. };
  24603. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24604. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24605. if (!options) {
  24606. return shape;
  24607. }
  24608. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24609. };
  24610. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24611. var shape = new CANNON.Plane();
  24612. if (!options) {
  24613. return shape;
  24614. }
  24615. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24616. };
  24617. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24618. var verts = [], faces = [];
  24619. mesh.computeWorldMatrix(true);
  24620. for (var i = 0; i < rawVerts.length; i += 3) {
  24621. var transformed = BABYLON.Vector3.Zero();
  24622. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24623. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24624. }
  24625. for (var j = 0; j < rawFaces.length; j += 3) {
  24626. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24627. }
  24628. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24629. if (!options) {
  24630. return shape;
  24631. }
  24632. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24633. };
  24634. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24635. var index;
  24636. var mat;
  24637. for (index = 0; index < this._physicsMaterials.length; index++) {
  24638. mat = this._physicsMaterials[index];
  24639. if (mat.friction === friction && mat.restitution === restitution) {
  24640. return mat;
  24641. }
  24642. }
  24643. var currentMat = new CANNON.Material();
  24644. currentMat.friction = friction;
  24645. currentMat.restitution = restitution;
  24646. this._physicsMaterials.push(currentMat);
  24647. for (index = 0; index < this._physicsMaterials.length; index++) {
  24648. mat = this._physicsMaterials[index];
  24649. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24650. contactMaterial.contactEquationStiffness = 1e10;
  24651. contactMaterial.contactEquationRegularizationTime = 10;
  24652. this._world.addContactMaterial(contactMaterial);
  24653. }
  24654. return currentMat;
  24655. };
  24656. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24657. var initialRotation = null;
  24658. if (mesh.rotationQuaternion) {
  24659. initialRotation = mesh.rotationQuaternion.clone();
  24660. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24661. }
  24662. // The delta between the mesh position and the mesh bounding box center
  24663. var bbox = mesh.getBoundingInfo().boundingBox;
  24664. var deltaPosition = mesh.position.subtract(bbox.center);
  24665. var material = this._addMaterial(friction, restitution);
  24666. var body = new CANNON.RigidBody(mass, shape, material);
  24667. if (initialRotation) {
  24668. body.quaternion.x = initialRotation.x;
  24669. body.quaternion.z = initialRotation.y;
  24670. body.quaternion.y = initialRotation.z;
  24671. body.quaternion.w = -initialRotation.w;
  24672. }
  24673. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24674. this._world.add(body);
  24675. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24676. return body;
  24677. };
  24678. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24679. var compoundShape = new CANNON.Compound();
  24680. for (var index = 0; index < parts.length; index++) {
  24681. var mesh = parts[index].mesh;
  24682. var shape = this.registerMesh(mesh, parts[index].impostor);
  24683. if (index == 0) {
  24684. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24685. }
  24686. else {
  24687. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24688. }
  24689. }
  24690. var initialMesh = parts[0].mesh;
  24691. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24692. body.parts = parts;
  24693. return body;
  24694. };
  24695. CannonJSPlugin.prototype._unbindBody = function (body) {
  24696. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24697. var registeredMesh = this._registeredMeshes[index];
  24698. if (registeredMesh.body === body) {
  24699. registeredMesh.body = null;
  24700. registeredMesh.delta = 0;
  24701. }
  24702. }
  24703. };
  24704. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24705. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24706. var registeredMesh = this._registeredMeshes[index];
  24707. if (registeredMesh.mesh === mesh) {
  24708. // Remove body
  24709. if (registeredMesh.body) {
  24710. this._world.remove(registeredMesh.body);
  24711. this._unbindBody(registeredMesh.body);
  24712. }
  24713. this._registeredMeshes.splice(index, 1);
  24714. return;
  24715. }
  24716. }
  24717. };
  24718. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24719. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24720. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24721. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24722. var registeredMesh = this._registeredMeshes[index];
  24723. if (registeredMesh.mesh === mesh) {
  24724. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24725. return;
  24726. }
  24727. }
  24728. };
  24729. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24730. var body1 = null, body2 = null;
  24731. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24732. var registeredMesh = this._registeredMeshes[index];
  24733. if (registeredMesh.mesh === mesh1) {
  24734. body1 = registeredMesh.body;
  24735. }
  24736. else if (registeredMesh.mesh === mesh2) {
  24737. body2 = registeredMesh.body;
  24738. }
  24739. }
  24740. if (!body1 || !body2) {
  24741. return false;
  24742. }
  24743. 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));
  24744. this._world.addConstraint(constraint);
  24745. return true;
  24746. };
  24747. CannonJSPlugin.prototype.dispose = function () {
  24748. while (this._registeredMeshes.length) {
  24749. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24750. }
  24751. };
  24752. CannonJSPlugin.prototype.isSupported = function () {
  24753. return window.CANNON !== undefined;
  24754. };
  24755. return CannonJSPlugin;
  24756. })();
  24757. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24758. })(BABYLON || (BABYLON = {}));
  24759. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24760. var BABYLON;
  24761. (function (BABYLON) {
  24762. var Condition = (function () {
  24763. function Condition(actionManager) {
  24764. this._actionManager = actionManager;
  24765. }
  24766. Condition.prototype.isValid = function () {
  24767. return true;
  24768. };
  24769. Condition.prototype._getProperty = function (propertyPath) {
  24770. return this._actionManager._getProperty(propertyPath);
  24771. };
  24772. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24773. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24774. };
  24775. return Condition;
  24776. })();
  24777. BABYLON.Condition = Condition;
  24778. var ValueCondition = (function (_super) {
  24779. __extends(ValueCondition, _super);
  24780. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24781. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24782. _super.call(this, actionManager);
  24783. this.propertyPath = propertyPath;
  24784. this.value = value;
  24785. this.operator = operator;
  24786. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24787. this._property = this._getProperty(this.propertyPath);
  24788. }
  24789. Object.defineProperty(ValueCondition, "IsEqual", {
  24790. get: function () {
  24791. return ValueCondition._IsEqual;
  24792. },
  24793. enumerable: true,
  24794. configurable: true
  24795. });
  24796. Object.defineProperty(ValueCondition, "IsDifferent", {
  24797. get: function () {
  24798. return ValueCondition._IsDifferent;
  24799. },
  24800. enumerable: true,
  24801. configurable: true
  24802. });
  24803. Object.defineProperty(ValueCondition, "IsGreater", {
  24804. get: function () {
  24805. return ValueCondition._IsGreater;
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. Object.defineProperty(ValueCondition, "IsLesser", {
  24811. get: function () {
  24812. return ValueCondition._IsLesser;
  24813. },
  24814. enumerable: true,
  24815. configurable: true
  24816. });
  24817. // Methods
  24818. ValueCondition.prototype.isValid = function () {
  24819. switch (this.operator) {
  24820. case ValueCondition.IsGreater:
  24821. return this._target[this._property] > this.value;
  24822. case ValueCondition.IsLesser:
  24823. return this._target[this._property] < this.value;
  24824. case ValueCondition.IsEqual:
  24825. case ValueCondition.IsDifferent:
  24826. var check;
  24827. if (this.value.equals) {
  24828. check = this.value.equals(this._target[this._property]);
  24829. }
  24830. else {
  24831. check = this.value === this._target[this._property];
  24832. }
  24833. return this.operator === ValueCondition.IsEqual ? check : !check;
  24834. }
  24835. return false;
  24836. };
  24837. // Statics
  24838. ValueCondition._IsEqual = 0;
  24839. ValueCondition._IsDifferent = 1;
  24840. ValueCondition._IsGreater = 2;
  24841. ValueCondition._IsLesser = 3;
  24842. return ValueCondition;
  24843. })(Condition);
  24844. BABYLON.ValueCondition = ValueCondition;
  24845. var PredicateCondition = (function (_super) {
  24846. __extends(PredicateCondition, _super);
  24847. function PredicateCondition(actionManager, predicate) {
  24848. _super.call(this, actionManager);
  24849. this.predicate = predicate;
  24850. }
  24851. PredicateCondition.prototype.isValid = function () {
  24852. return this.predicate();
  24853. };
  24854. return PredicateCondition;
  24855. })(Condition);
  24856. BABYLON.PredicateCondition = PredicateCondition;
  24857. var StateCondition = (function (_super) {
  24858. __extends(StateCondition, _super);
  24859. function StateCondition(actionManager, target, value) {
  24860. _super.call(this, actionManager);
  24861. this.value = value;
  24862. this._target = target;
  24863. }
  24864. // Methods
  24865. StateCondition.prototype.isValid = function () {
  24866. return this._target.state === this.value;
  24867. };
  24868. return StateCondition;
  24869. })(Condition);
  24870. BABYLON.StateCondition = StateCondition;
  24871. })(BABYLON || (BABYLON = {}));
  24872. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24873. (function (BABYLON) {
  24874. var Action = (function () {
  24875. function Action(triggerOptions, condition) {
  24876. this.triggerOptions = triggerOptions;
  24877. if (triggerOptions.parameter) {
  24878. this.trigger = triggerOptions.trigger;
  24879. this._triggerParameter = triggerOptions.parameter;
  24880. }
  24881. else {
  24882. this.trigger = triggerOptions;
  24883. }
  24884. this._nextActiveAction = this;
  24885. this._condition = condition;
  24886. }
  24887. // Methods
  24888. Action.prototype._prepare = function () {
  24889. };
  24890. Action.prototype.getTriggerParameter = function () {
  24891. return this._triggerParameter;
  24892. };
  24893. Action.prototype._executeCurrent = function (evt) {
  24894. if (this._nextActiveAction._condition) {
  24895. var condition = this._nextActiveAction._condition;
  24896. var currentRenderId = this._actionManager.getScene().getRenderId();
  24897. // We cache the current evaluation for the current frame
  24898. if (condition._evaluationId === currentRenderId) {
  24899. if (!condition._currentResult) {
  24900. return;
  24901. }
  24902. }
  24903. else {
  24904. condition._evaluationId = currentRenderId;
  24905. if (!condition.isValid()) {
  24906. condition._currentResult = false;
  24907. return;
  24908. }
  24909. condition._currentResult = true;
  24910. }
  24911. }
  24912. this._nextActiveAction.execute(evt);
  24913. if (this._nextActiveAction._child) {
  24914. if (!this._nextActiveAction._child._actionManager) {
  24915. this._nextActiveAction._child._actionManager = this._actionManager;
  24916. }
  24917. this._nextActiveAction = this._nextActiveAction._child;
  24918. }
  24919. else {
  24920. this._nextActiveAction = this;
  24921. }
  24922. };
  24923. Action.prototype.execute = function (evt) {
  24924. };
  24925. Action.prototype.then = function (action) {
  24926. this._child = action;
  24927. action._actionManager = this._actionManager;
  24928. action._prepare();
  24929. return action;
  24930. };
  24931. Action.prototype._getProperty = function (propertyPath) {
  24932. return this._actionManager._getProperty(propertyPath);
  24933. };
  24934. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24935. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24936. };
  24937. return Action;
  24938. })();
  24939. BABYLON.Action = Action;
  24940. })(BABYLON || (BABYLON = {}));
  24941. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24942. (function (BABYLON) {
  24943. /**
  24944. * ActionEvent is the event beint sent when an action is triggered.
  24945. */
  24946. var ActionEvent = (function () {
  24947. /**
  24948. * @constructor
  24949. * @param source The mesh that triggered the action.
  24950. * @param pointerX the X mouse cursor position at the time of the event
  24951. * @param pointerY the Y mouse cursor position at the time of the event
  24952. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24953. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24954. */
  24955. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24956. this.source = source;
  24957. this.pointerX = pointerX;
  24958. this.pointerY = pointerY;
  24959. this.meshUnderPointer = meshUnderPointer;
  24960. this.sourceEvent = sourceEvent;
  24961. }
  24962. /**
  24963. * Helper function to auto-create an ActionEvent from a source mesh.
  24964. * @param source the source mesh that triggered the event
  24965. * @param evt {Event} The original (browser) event
  24966. */
  24967. ActionEvent.CreateNew = function (source, evt) {
  24968. var scene = source.getScene();
  24969. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24970. };
  24971. /**
  24972. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24973. * @param scene the scene where the event occurred
  24974. * @param evt {Event} The original (browser) event
  24975. */
  24976. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24977. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24978. };
  24979. return ActionEvent;
  24980. })();
  24981. BABYLON.ActionEvent = ActionEvent;
  24982. /**
  24983. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24984. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24985. */
  24986. var ActionManager = (function () {
  24987. function ActionManager(scene) {
  24988. // Members
  24989. this.actions = new Array();
  24990. this._scene = scene;
  24991. scene._actionManagers.push(this);
  24992. }
  24993. Object.defineProperty(ActionManager, "NothingTrigger", {
  24994. get: function () {
  24995. return ActionManager._NothingTrigger;
  24996. },
  24997. enumerable: true,
  24998. configurable: true
  24999. });
  25000. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25001. get: function () {
  25002. return ActionManager._OnPickTrigger;
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25008. get: function () {
  25009. return ActionManager._OnLeftPickTrigger;
  25010. },
  25011. enumerable: true,
  25012. configurable: true
  25013. });
  25014. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25015. get: function () {
  25016. return ActionManager._OnRightPickTrigger;
  25017. },
  25018. enumerable: true,
  25019. configurable: true
  25020. });
  25021. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25022. get: function () {
  25023. return ActionManager._OnCenterPickTrigger;
  25024. },
  25025. enumerable: true,
  25026. configurable: true
  25027. });
  25028. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25029. get: function () {
  25030. return ActionManager._OnPointerOverTrigger;
  25031. },
  25032. enumerable: true,
  25033. configurable: true
  25034. });
  25035. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25036. get: function () {
  25037. return ActionManager._OnPointerOutTrigger;
  25038. },
  25039. enumerable: true,
  25040. configurable: true
  25041. });
  25042. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25043. get: function () {
  25044. return ActionManager._OnEveryFrameTrigger;
  25045. },
  25046. enumerable: true,
  25047. configurable: true
  25048. });
  25049. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25050. get: function () {
  25051. return ActionManager._OnIntersectionEnterTrigger;
  25052. },
  25053. enumerable: true,
  25054. configurable: true
  25055. });
  25056. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25057. get: function () {
  25058. return ActionManager._OnIntersectionExitTrigger;
  25059. },
  25060. enumerable: true,
  25061. configurable: true
  25062. });
  25063. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25064. get: function () {
  25065. return ActionManager._OnKeyDownTrigger;
  25066. },
  25067. enumerable: true,
  25068. configurable: true
  25069. });
  25070. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25071. get: function () {
  25072. return ActionManager._OnKeyUpTrigger;
  25073. },
  25074. enumerable: true,
  25075. configurable: true
  25076. });
  25077. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25078. get: function () {
  25079. return ActionManager._OnPickUpTrigger;
  25080. },
  25081. enumerable: true,
  25082. configurable: true
  25083. });
  25084. // Methods
  25085. ActionManager.prototype.dispose = function () {
  25086. var index = this._scene._actionManagers.indexOf(this);
  25087. if (index > -1) {
  25088. this._scene._actionManagers.splice(index, 1);
  25089. }
  25090. };
  25091. ActionManager.prototype.getScene = function () {
  25092. return this._scene;
  25093. };
  25094. /**
  25095. * Does this action manager handles actions of any of the given triggers
  25096. * @param {number[]} triggers - the triggers to be tested
  25097. * @return {boolean} whether one (or more) of the triggers is handeled
  25098. */
  25099. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25100. for (var index = 0; index < this.actions.length; index++) {
  25101. var action = this.actions[index];
  25102. if (triggers.indexOf(action.trigger) > -1) {
  25103. return true;
  25104. }
  25105. }
  25106. return false;
  25107. };
  25108. /**
  25109. * Does this action manager handles actions of a given trigger
  25110. * @param {number} trigger - the trigger to be tested
  25111. * @return {boolean} whether the trigger is handeled
  25112. */
  25113. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25114. for (var index = 0; index < this.actions.length; index++) {
  25115. var action = this.actions[index];
  25116. if (action.trigger === trigger) {
  25117. return true;
  25118. }
  25119. }
  25120. return false;
  25121. };
  25122. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25123. /**
  25124. * Does this action manager has pointer triggers
  25125. * @return {boolean} whether or not it has pointer triggers
  25126. */
  25127. get: function () {
  25128. for (var index = 0; index < this.actions.length; index++) {
  25129. var action = this.actions[index];
  25130. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25131. return true;
  25132. }
  25133. if (action.trigger == ActionManager._OnPickUpTrigger) {
  25134. return true;
  25135. }
  25136. }
  25137. return false;
  25138. },
  25139. enumerable: true,
  25140. configurable: true
  25141. });
  25142. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25143. /**
  25144. * Does this action manager has pick triggers
  25145. * @return {boolean} whether or not it has pick triggers
  25146. */
  25147. get: function () {
  25148. for (var index = 0; index < this.actions.length; index++) {
  25149. var action = this.actions[index];
  25150. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25151. return true;
  25152. }
  25153. }
  25154. return false;
  25155. },
  25156. enumerable: true,
  25157. configurable: true
  25158. });
  25159. /**
  25160. * Registers an action to this action manager
  25161. * @param {BABYLON.Action} action - the action to be registered
  25162. * @return {BABYLON.Action} the action amended (prepared) after registration
  25163. */
  25164. ActionManager.prototype.registerAction = function (action) {
  25165. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25166. if (this.getScene().actionManager !== this) {
  25167. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25168. return null;
  25169. }
  25170. }
  25171. this.actions.push(action);
  25172. action._actionManager = this;
  25173. action._prepare();
  25174. return action;
  25175. };
  25176. /**
  25177. * Process a specific trigger
  25178. * @param {number} trigger - the trigger to process
  25179. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25180. */
  25181. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25182. for (var index = 0; index < this.actions.length; index++) {
  25183. var action = this.actions[index];
  25184. if (action.trigger === trigger) {
  25185. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  25186. var parameter = action.getTriggerParameter();
  25187. if (parameter) {
  25188. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25189. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25190. if (actualkey !== parameter.toLowerCase()) {
  25191. continue;
  25192. }
  25193. }
  25194. }
  25195. action._executeCurrent(evt);
  25196. }
  25197. }
  25198. };
  25199. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25200. var properties = propertyPath.split(".");
  25201. for (var index = 0; index < properties.length - 1; index++) {
  25202. target = target[properties[index]];
  25203. }
  25204. return target;
  25205. };
  25206. ActionManager.prototype._getProperty = function (propertyPath) {
  25207. var properties = propertyPath.split(".");
  25208. return properties[properties.length - 1];
  25209. };
  25210. // Statics
  25211. ActionManager._NothingTrigger = 0;
  25212. ActionManager._OnPickTrigger = 1;
  25213. ActionManager._OnLeftPickTrigger = 2;
  25214. ActionManager._OnRightPickTrigger = 3;
  25215. ActionManager._OnCenterPickTrigger = 4;
  25216. ActionManager._OnPointerOverTrigger = 5;
  25217. ActionManager._OnPointerOutTrigger = 6;
  25218. ActionManager._OnEveryFrameTrigger = 7;
  25219. ActionManager._OnIntersectionEnterTrigger = 8;
  25220. ActionManager._OnIntersectionExitTrigger = 9;
  25221. ActionManager._OnKeyDownTrigger = 10;
  25222. ActionManager._OnKeyUpTrigger = 11;
  25223. ActionManager._OnPickUpTrigger = 12;
  25224. return ActionManager;
  25225. })();
  25226. BABYLON.ActionManager = ActionManager;
  25227. })(BABYLON || (BABYLON = {}));
  25228. //# sourceMappingURL=babylon.actionManager.js.map
  25229. var BABYLON;
  25230. (function (BABYLON) {
  25231. var InterpolateValueAction = (function (_super) {
  25232. __extends(InterpolateValueAction, _super);
  25233. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  25234. if (duration === void 0) { duration = 1000; }
  25235. _super.call(this, triggerOptions, condition);
  25236. this.propertyPath = propertyPath;
  25237. this.value = value;
  25238. this.duration = duration;
  25239. this.stopOtherAnimations = stopOtherAnimations;
  25240. this._target = target;
  25241. }
  25242. InterpolateValueAction.prototype._prepare = function () {
  25243. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25244. this._property = this._getProperty(this.propertyPath);
  25245. };
  25246. InterpolateValueAction.prototype.execute = function () {
  25247. var scene = this._actionManager.getScene();
  25248. var keys = [
  25249. {
  25250. frame: 0,
  25251. value: this._target[this._property]
  25252. },
  25253. {
  25254. frame: 100,
  25255. value: this.value
  25256. }
  25257. ];
  25258. var dataType;
  25259. if (typeof this.value === "number") {
  25260. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25261. }
  25262. else if (this.value instanceof BABYLON.Color3) {
  25263. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25264. }
  25265. else if (this.value instanceof BABYLON.Vector3) {
  25266. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25267. }
  25268. else if (this.value instanceof BABYLON.Matrix) {
  25269. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25270. }
  25271. else if (this.value instanceof BABYLON.Quaternion) {
  25272. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25273. }
  25274. else {
  25275. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25276. return;
  25277. }
  25278. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25279. animation.setKeys(keys);
  25280. if (this.stopOtherAnimations) {
  25281. scene.stopAnimation(this._target);
  25282. }
  25283. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25284. };
  25285. return InterpolateValueAction;
  25286. })(BABYLON.Action);
  25287. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25288. })(BABYLON || (BABYLON = {}));
  25289. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25290. var BABYLON;
  25291. (function (BABYLON) {
  25292. var SwitchBooleanAction = (function (_super) {
  25293. __extends(SwitchBooleanAction, _super);
  25294. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25295. _super.call(this, triggerOptions, condition);
  25296. this.propertyPath = propertyPath;
  25297. this._target = target;
  25298. }
  25299. SwitchBooleanAction.prototype._prepare = function () {
  25300. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25301. this._property = this._getProperty(this.propertyPath);
  25302. };
  25303. SwitchBooleanAction.prototype.execute = function () {
  25304. this._target[this._property] = !this._target[this._property];
  25305. };
  25306. return SwitchBooleanAction;
  25307. })(BABYLON.Action);
  25308. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25309. var SetStateAction = (function (_super) {
  25310. __extends(SetStateAction, _super);
  25311. function SetStateAction(triggerOptions, target, value, condition) {
  25312. _super.call(this, triggerOptions, condition);
  25313. this.value = value;
  25314. this._target = target;
  25315. }
  25316. SetStateAction.prototype.execute = function () {
  25317. this._target.state = this.value;
  25318. };
  25319. return SetStateAction;
  25320. })(BABYLON.Action);
  25321. BABYLON.SetStateAction = SetStateAction;
  25322. var SetValueAction = (function (_super) {
  25323. __extends(SetValueAction, _super);
  25324. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25325. _super.call(this, triggerOptions, condition);
  25326. this.propertyPath = propertyPath;
  25327. this.value = value;
  25328. this._target = target;
  25329. }
  25330. SetValueAction.prototype._prepare = function () {
  25331. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25332. this._property = this._getProperty(this.propertyPath);
  25333. };
  25334. SetValueAction.prototype.execute = function () {
  25335. this._target[this._property] = this.value;
  25336. };
  25337. return SetValueAction;
  25338. })(BABYLON.Action);
  25339. BABYLON.SetValueAction = SetValueAction;
  25340. var IncrementValueAction = (function (_super) {
  25341. __extends(IncrementValueAction, _super);
  25342. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25343. _super.call(this, triggerOptions, condition);
  25344. this.propertyPath = propertyPath;
  25345. this.value = value;
  25346. this._target = target;
  25347. }
  25348. IncrementValueAction.prototype._prepare = function () {
  25349. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25350. this._property = this._getProperty(this.propertyPath);
  25351. if (typeof this._target[this._property] !== "number") {
  25352. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25353. }
  25354. };
  25355. IncrementValueAction.prototype.execute = function () {
  25356. this._target[this._property] += this.value;
  25357. };
  25358. return IncrementValueAction;
  25359. })(BABYLON.Action);
  25360. BABYLON.IncrementValueAction = IncrementValueAction;
  25361. var PlayAnimationAction = (function (_super) {
  25362. __extends(PlayAnimationAction, _super);
  25363. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25364. _super.call(this, triggerOptions, condition);
  25365. this.from = from;
  25366. this.to = to;
  25367. this.loop = loop;
  25368. this._target = target;
  25369. }
  25370. PlayAnimationAction.prototype._prepare = function () {
  25371. };
  25372. PlayAnimationAction.prototype.execute = function () {
  25373. var scene = this._actionManager.getScene();
  25374. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25375. };
  25376. return PlayAnimationAction;
  25377. })(BABYLON.Action);
  25378. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25379. var StopAnimationAction = (function (_super) {
  25380. __extends(StopAnimationAction, _super);
  25381. function StopAnimationAction(triggerOptions, target, condition) {
  25382. _super.call(this, triggerOptions, condition);
  25383. this._target = target;
  25384. }
  25385. StopAnimationAction.prototype._prepare = function () {
  25386. };
  25387. StopAnimationAction.prototype.execute = function () {
  25388. var scene = this._actionManager.getScene();
  25389. scene.stopAnimation(this._target);
  25390. };
  25391. return StopAnimationAction;
  25392. })(BABYLON.Action);
  25393. BABYLON.StopAnimationAction = StopAnimationAction;
  25394. var DoNothingAction = (function (_super) {
  25395. __extends(DoNothingAction, _super);
  25396. function DoNothingAction(triggerOptions, condition) {
  25397. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25398. _super.call(this, triggerOptions, condition);
  25399. }
  25400. DoNothingAction.prototype.execute = function () {
  25401. };
  25402. return DoNothingAction;
  25403. })(BABYLON.Action);
  25404. BABYLON.DoNothingAction = DoNothingAction;
  25405. var CombineAction = (function (_super) {
  25406. __extends(CombineAction, _super);
  25407. function CombineAction(triggerOptions, children, condition) {
  25408. _super.call(this, triggerOptions, condition);
  25409. this.children = children;
  25410. }
  25411. CombineAction.prototype._prepare = function () {
  25412. for (var index = 0; index < this.children.length; index++) {
  25413. this.children[index]._actionManager = this._actionManager;
  25414. this.children[index]._prepare();
  25415. }
  25416. };
  25417. CombineAction.prototype.execute = function (evt) {
  25418. for (var index = 0; index < this.children.length; index++) {
  25419. this.children[index].execute(evt);
  25420. }
  25421. };
  25422. return CombineAction;
  25423. })(BABYLON.Action);
  25424. BABYLON.CombineAction = CombineAction;
  25425. var ExecuteCodeAction = (function (_super) {
  25426. __extends(ExecuteCodeAction, _super);
  25427. function ExecuteCodeAction(triggerOptions, func, condition) {
  25428. _super.call(this, triggerOptions, condition);
  25429. this.func = func;
  25430. }
  25431. ExecuteCodeAction.prototype.execute = function (evt) {
  25432. this.func(evt);
  25433. };
  25434. return ExecuteCodeAction;
  25435. })(BABYLON.Action);
  25436. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25437. var SetParentAction = (function (_super) {
  25438. __extends(SetParentAction, _super);
  25439. function SetParentAction(triggerOptions, target, parent, condition) {
  25440. _super.call(this, triggerOptions, condition);
  25441. this._target = target;
  25442. this._parent = parent;
  25443. }
  25444. SetParentAction.prototype._prepare = function () {
  25445. };
  25446. SetParentAction.prototype.execute = function () {
  25447. if (this._target.parent === this._parent) {
  25448. return;
  25449. }
  25450. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25451. invertParentWorldMatrix.invert();
  25452. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25453. this._target.parent = this._parent;
  25454. };
  25455. return SetParentAction;
  25456. })(BABYLON.Action);
  25457. BABYLON.SetParentAction = SetParentAction;
  25458. var PlaySoundAction = (function (_super) {
  25459. __extends(PlaySoundAction, _super);
  25460. function PlaySoundAction(triggerOptions, sound, condition) {
  25461. _super.call(this, triggerOptions, condition);
  25462. this._sound = sound;
  25463. }
  25464. PlaySoundAction.prototype._prepare = function () {
  25465. };
  25466. PlaySoundAction.prototype.execute = function () {
  25467. if (this._sound !== undefined)
  25468. this._sound.play();
  25469. };
  25470. return PlaySoundAction;
  25471. })(BABYLON.Action);
  25472. BABYLON.PlaySoundAction = PlaySoundAction;
  25473. var StopSoundAction = (function (_super) {
  25474. __extends(StopSoundAction, _super);
  25475. function StopSoundAction(triggerOptions, sound, condition) {
  25476. _super.call(this, triggerOptions, condition);
  25477. this._sound = sound;
  25478. }
  25479. StopSoundAction.prototype._prepare = function () {
  25480. };
  25481. StopSoundAction.prototype.execute = function () {
  25482. if (this._sound !== undefined)
  25483. this._sound.stop();
  25484. };
  25485. return StopSoundAction;
  25486. })(BABYLON.Action);
  25487. BABYLON.StopSoundAction = StopSoundAction;
  25488. })(BABYLON || (BABYLON = {}));
  25489. //# sourceMappingURL=babylon.directActions.js.map
  25490. var BABYLON;
  25491. (function (BABYLON) {
  25492. var Geometry = (function () {
  25493. function Geometry(id, scene, vertexData, updatable, mesh) {
  25494. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25495. this._totalVertices = 0;
  25496. this._indices = [];
  25497. this._isDisposed = false;
  25498. this.id = id;
  25499. this._engine = scene.getEngine();
  25500. this._meshes = [];
  25501. this._scene = scene;
  25502. // vertexData
  25503. if (vertexData) {
  25504. this.setAllVerticesData(vertexData, updatable);
  25505. }
  25506. else {
  25507. this._totalVertices = 0;
  25508. this._indices = [];
  25509. }
  25510. // applyToMesh
  25511. if (mesh) {
  25512. this.applyToMesh(mesh);
  25513. mesh.computeWorldMatrix(true);
  25514. }
  25515. }
  25516. Geometry.prototype.getScene = function () {
  25517. return this._scene;
  25518. };
  25519. Geometry.prototype.getEngine = function () {
  25520. return this._engine;
  25521. };
  25522. Geometry.prototype.isReady = function () {
  25523. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25524. };
  25525. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25526. vertexData.applyToGeometry(this, updatable);
  25527. this.notifyUpdate();
  25528. };
  25529. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25530. this._vertexBuffers = this._vertexBuffers || {};
  25531. if (this._vertexBuffers[kind]) {
  25532. this._vertexBuffers[kind].dispose();
  25533. }
  25534. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25535. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25536. stride = this._vertexBuffers[kind].getStrideSize();
  25537. this._totalVertices = data.length / stride;
  25538. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25539. var meshes = this._meshes;
  25540. var numOfMeshes = meshes.length;
  25541. for (var index = 0; index < numOfMeshes; index++) {
  25542. var mesh = meshes[index];
  25543. mesh._resetPointsArrayCache();
  25544. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25545. mesh._createGlobalSubMesh();
  25546. mesh.computeWorldMatrix(true);
  25547. }
  25548. }
  25549. this.notifyUpdate(kind);
  25550. };
  25551. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25552. var vertexBuffer = this.getVertexBuffer(kind);
  25553. if (!vertexBuffer) {
  25554. return;
  25555. }
  25556. vertexBuffer.updateDirectly(data, offset);
  25557. this.notifyUpdate(kind);
  25558. };
  25559. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25560. var vertexBuffer = this.getVertexBuffer(kind);
  25561. if (!vertexBuffer) {
  25562. return;
  25563. }
  25564. vertexBuffer.update(data);
  25565. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25566. var extend;
  25567. var stride = vertexBuffer.getStrideSize();
  25568. this._totalVertices = data.length / stride;
  25569. if (updateExtends) {
  25570. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25571. }
  25572. var meshes = this._meshes;
  25573. var numOfMeshes = meshes.length;
  25574. for (var index = 0; index < numOfMeshes; index++) {
  25575. var mesh = meshes[index];
  25576. mesh._resetPointsArrayCache();
  25577. if (updateExtends) {
  25578. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25579. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25580. var subMesh = mesh.subMeshes[subIndex];
  25581. subMesh.refreshBoundingInfo();
  25582. }
  25583. }
  25584. }
  25585. }
  25586. this.notifyUpdate(kind);
  25587. };
  25588. Geometry.prototype.getTotalVertices = function () {
  25589. if (!this.isReady()) {
  25590. return 0;
  25591. }
  25592. return this._totalVertices;
  25593. };
  25594. Geometry.prototype.getVerticesData = function (kind) {
  25595. var vertexBuffer = this.getVertexBuffer(kind);
  25596. if (!vertexBuffer) {
  25597. return null;
  25598. }
  25599. return vertexBuffer.getData();
  25600. };
  25601. Geometry.prototype.getVertexBuffer = function (kind) {
  25602. if (!this.isReady()) {
  25603. return null;
  25604. }
  25605. return this._vertexBuffers[kind];
  25606. };
  25607. Geometry.prototype.getVertexBuffers = function () {
  25608. if (!this.isReady()) {
  25609. return null;
  25610. }
  25611. return this._vertexBuffers;
  25612. };
  25613. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25614. if (!this._vertexBuffers) {
  25615. if (this._delayInfo) {
  25616. return this._delayInfo.indexOf(kind) !== -1;
  25617. }
  25618. return false;
  25619. }
  25620. return this._vertexBuffers[kind] !== undefined;
  25621. };
  25622. Geometry.prototype.getVerticesDataKinds = function () {
  25623. var result = [];
  25624. if (!this._vertexBuffers && this._delayInfo) {
  25625. for (var kind in this._delayInfo) {
  25626. result.push(kind);
  25627. }
  25628. }
  25629. else {
  25630. for (kind in this._vertexBuffers) {
  25631. result.push(kind);
  25632. }
  25633. }
  25634. return result;
  25635. };
  25636. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25637. if (this._indexBuffer) {
  25638. this._engine._releaseBuffer(this._indexBuffer);
  25639. }
  25640. this._indices = indices;
  25641. if (this._meshes.length !== 0 && this._indices) {
  25642. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25643. }
  25644. if (totalVertices !== undefined) {
  25645. this._totalVertices = totalVertices;
  25646. }
  25647. var meshes = this._meshes;
  25648. var numOfMeshes = meshes.length;
  25649. for (var index = 0; index < numOfMeshes; index++) {
  25650. meshes[index]._createGlobalSubMesh();
  25651. }
  25652. this.notifyUpdate();
  25653. };
  25654. Geometry.prototype.getTotalIndices = function () {
  25655. if (!this.isReady()) {
  25656. return 0;
  25657. }
  25658. return this._indices.length;
  25659. };
  25660. Geometry.prototype.getIndices = function () {
  25661. if (!this.isReady()) {
  25662. return null;
  25663. }
  25664. return this._indices;
  25665. };
  25666. Geometry.prototype.getIndexBuffer = function () {
  25667. if (!this.isReady()) {
  25668. return null;
  25669. }
  25670. return this._indexBuffer;
  25671. };
  25672. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25673. var meshes = this._meshes;
  25674. var index = meshes.indexOf(mesh);
  25675. if (index === -1) {
  25676. return;
  25677. }
  25678. for (var kind in this._vertexBuffers) {
  25679. this._vertexBuffers[kind].dispose();
  25680. }
  25681. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25682. this._indexBuffer = null;
  25683. }
  25684. meshes.splice(index, 1);
  25685. mesh._geometry = null;
  25686. if (meshes.length === 0 && shouldDispose) {
  25687. this.dispose();
  25688. }
  25689. };
  25690. Geometry.prototype.applyToMesh = function (mesh) {
  25691. if (mesh._geometry === this) {
  25692. return;
  25693. }
  25694. var previousGeometry = mesh._geometry;
  25695. if (previousGeometry) {
  25696. previousGeometry.releaseForMesh(mesh);
  25697. }
  25698. var meshes = this._meshes;
  25699. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25700. mesh._geometry = this;
  25701. this._scene.pushGeometry(this);
  25702. meshes.push(mesh);
  25703. if (this.isReady()) {
  25704. this._applyToMesh(mesh);
  25705. }
  25706. else {
  25707. mesh._boundingInfo = this._boundingInfo;
  25708. }
  25709. };
  25710. Geometry.prototype._applyToMesh = function (mesh) {
  25711. var numOfMeshes = this._meshes.length;
  25712. for (var kind in this._vertexBuffers) {
  25713. if (numOfMeshes === 1) {
  25714. this._vertexBuffers[kind].create();
  25715. }
  25716. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25717. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25718. mesh._resetPointsArrayCache();
  25719. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25720. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25721. mesh._createGlobalSubMesh();
  25722. //bounding info was just created again, world matrix should be applied again.
  25723. mesh._updateBoundingInfo();
  25724. }
  25725. }
  25726. // indexBuffer
  25727. if (numOfMeshes === 1 && this._indices) {
  25728. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25729. }
  25730. if (this._indexBuffer) {
  25731. this._indexBuffer.references = numOfMeshes;
  25732. }
  25733. };
  25734. Geometry.prototype.notifyUpdate = function (kind) {
  25735. if (this.onGeometryUpdated) {
  25736. this.onGeometryUpdated(this, kind);
  25737. }
  25738. };
  25739. Geometry.prototype.load = function (scene, onLoaded) {
  25740. var _this = this;
  25741. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25742. return;
  25743. }
  25744. if (this.isReady()) {
  25745. if (onLoaded) {
  25746. onLoaded();
  25747. }
  25748. return;
  25749. }
  25750. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25751. scene._addPendingData(this);
  25752. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25753. _this._delayLoadingFunction(JSON.parse(data), _this);
  25754. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25755. _this._delayInfo = [];
  25756. scene._removePendingData(_this);
  25757. var meshes = _this._meshes;
  25758. var numOfMeshes = meshes.length;
  25759. for (var index = 0; index < numOfMeshes; index++) {
  25760. _this._applyToMesh(meshes[index]);
  25761. }
  25762. if (onLoaded) {
  25763. onLoaded();
  25764. }
  25765. }, function () {
  25766. }, scene.database);
  25767. };
  25768. Geometry.prototype.isDisposed = function () {
  25769. return this._isDisposed;
  25770. };
  25771. Geometry.prototype.dispose = function () {
  25772. var meshes = this._meshes;
  25773. var numOfMeshes = meshes.length;
  25774. var index;
  25775. for (index = 0; index < numOfMeshes; index++) {
  25776. this.releaseForMesh(meshes[index]);
  25777. }
  25778. this._meshes = [];
  25779. for (var kind in this._vertexBuffers) {
  25780. this._vertexBuffers[kind].dispose();
  25781. }
  25782. this._vertexBuffers = [];
  25783. this._totalVertices = 0;
  25784. if (this._indexBuffer) {
  25785. this._engine._releaseBuffer(this._indexBuffer);
  25786. }
  25787. this._indexBuffer = null;
  25788. this._indices = [];
  25789. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25790. this.delayLoadingFile = null;
  25791. this._delayLoadingFunction = null;
  25792. this._delayInfo = [];
  25793. this._boundingInfo = null; // todo: .dispose()
  25794. this._scene.removeGeometry(this);
  25795. this._isDisposed = true;
  25796. };
  25797. Geometry.prototype.copy = function (id) {
  25798. var vertexData = new BABYLON.VertexData();
  25799. vertexData.indices = [];
  25800. var indices = this.getIndices();
  25801. for (var index = 0; index < indices.length; index++) {
  25802. vertexData.indices.push(indices[index]);
  25803. }
  25804. var updatable = false;
  25805. var stopChecking = false;
  25806. for (var kind in this._vertexBuffers) {
  25807. // using slice() to make a copy of the array and not just reference it
  25808. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25809. if (!stopChecking) {
  25810. updatable = this.getVertexBuffer(kind).isUpdatable();
  25811. stopChecking = !updatable;
  25812. }
  25813. }
  25814. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25815. geometry.delayLoadState = this.delayLoadState;
  25816. geometry.delayLoadingFile = this.delayLoadingFile;
  25817. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25818. for (kind in this._delayInfo) {
  25819. geometry._delayInfo = geometry._delayInfo || [];
  25820. geometry._delayInfo.push(kind);
  25821. }
  25822. // Bounding info
  25823. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25824. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25825. return geometry;
  25826. };
  25827. // Statics
  25828. Geometry.ExtractFromMesh = function (mesh, id) {
  25829. var geometry = mesh._geometry;
  25830. if (!geometry) {
  25831. return null;
  25832. }
  25833. return geometry.copy(id);
  25834. };
  25835. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25836. // be aware Math.random() could cause collisions
  25837. Geometry.RandomId = function () {
  25838. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25839. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25840. return v.toString(16);
  25841. });
  25842. };
  25843. return Geometry;
  25844. })();
  25845. BABYLON.Geometry = Geometry;
  25846. /////// Primitives //////////////////////////////////////////////
  25847. var Geometry;
  25848. (function (Geometry) {
  25849. var Primitives;
  25850. (function (Primitives) {
  25851. /// Abstract class
  25852. var _Primitive = (function (_super) {
  25853. __extends(_Primitive, _super);
  25854. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25855. this._beingRegenerated = true;
  25856. this._canBeRegenerated = canBeRegenerated;
  25857. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25858. this._beingRegenerated = false;
  25859. }
  25860. _Primitive.prototype.canBeRegenerated = function () {
  25861. return this._canBeRegenerated;
  25862. };
  25863. _Primitive.prototype.regenerate = function () {
  25864. if (!this._canBeRegenerated) {
  25865. return;
  25866. }
  25867. this._beingRegenerated = true;
  25868. this.setAllVerticesData(this._regenerateVertexData(), false);
  25869. this._beingRegenerated = false;
  25870. };
  25871. _Primitive.prototype.asNewGeometry = function (id) {
  25872. return _super.prototype.copy.call(this, id);
  25873. };
  25874. // overrides
  25875. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25876. if (!this._beingRegenerated) {
  25877. return;
  25878. }
  25879. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25880. };
  25881. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25882. if (!this._beingRegenerated) {
  25883. return;
  25884. }
  25885. _super.prototype.setVerticesData.call(this, kind, data, false);
  25886. };
  25887. // to override
  25888. // protected
  25889. _Primitive.prototype._regenerateVertexData = function () {
  25890. throw new Error("Abstract method");
  25891. };
  25892. _Primitive.prototype.copy = function (id) {
  25893. throw new Error("Must be overriden in sub-classes.");
  25894. };
  25895. return _Primitive;
  25896. })(Geometry);
  25897. Primitives._Primitive = _Primitive;
  25898. var Ribbon = (function (_super) {
  25899. __extends(Ribbon, _super);
  25900. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25901. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25902. this.pathArray = pathArray;
  25903. this.closeArray = closeArray;
  25904. this.closePath = closePath;
  25905. this.offset = offset;
  25906. this.side = side;
  25907. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25908. }
  25909. Ribbon.prototype._regenerateVertexData = function () {
  25910. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25911. };
  25912. Ribbon.prototype.copy = function (id) {
  25913. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25914. };
  25915. return Ribbon;
  25916. })(_Primitive);
  25917. Primitives.Ribbon = Ribbon;
  25918. var Box = (function (_super) {
  25919. __extends(Box, _super);
  25920. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25921. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25922. this.size = size;
  25923. this.side = side;
  25924. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25925. }
  25926. Box.prototype._regenerateVertexData = function () {
  25927. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25928. };
  25929. Box.prototype.copy = function (id) {
  25930. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25931. };
  25932. return Box;
  25933. })(_Primitive);
  25934. Primitives.Box = Box;
  25935. var Sphere = (function (_super) {
  25936. __extends(Sphere, _super);
  25937. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25938. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25939. this.segments = segments;
  25940. this.diameter = diameter;
  25941. this.side = side;
  25942. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25943. }
  25944. Sphere.prototype._regenerateVertexData = function () {
  25945. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25946. };
  25947. Sphere.prototype.copy = function (id) {
  25948. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25949. };
  25950. return Sphere;
  25951. })(_Primitive);
  25952. Primitives.Sphere = Sphere;
  25953. var Cylinder = (function (_super) {
  25954. __extends(Cylinder, _super);
  25955. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25956. if (subdivisions === void 0) { subdivisions = 1; }
  25957. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25958. this.height = height;
  25959. this.diameterTop = diameterTop;
  25960. this.diameterBottom = diameterBottom;
  25961. this.tessellation = tessellation;
  25962. this.subdivisions = subdivisions;
  25963. this.side = side;
  25964. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25965. }
  25966. Cylinder.prototype._regenerateVertexData = function () {
  25967. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25968. };
  25969. Cylinder.prototype.copy = function (id) {
  25970. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25971. };
  25972. return Cylinder;
  25973. })(_Primitive);
  25974. Primitives.Cylinder = Cylinder;
  25975. var Torus = (function (_super) {
  25976. __extends(Torus, _super);
  25977. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25978. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25979. this.diameter = diameter;
  25980. this.thickness = thickness;
  25981. this.tessellation = tessellation;
  25982. this.side = side;
  25983. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25984. }
  25985. Torus.prototype._regenerateVertexData = function () {
  25986. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25987. };
  25988. Torus.prototype.copy = function (id) {
  25989. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25990. };
  25991. return Torus;
  25992. })(_Primitive);
  25993. Primitives.Torus = Torus;
  25994. var Ground = (function (_super) {
  25995. __extends(Ground, _super);
  25996. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25997. this.width = width;
  25998. this.height = height;
  25999. this.subdivisions = subdivisions;
  26000. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26001. }
  26002. Ground.prototype._regenerateVertexData = function () {
  26003. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  26004. };
  26005. Ground.prototype.copy = function (id) {
  26006. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26007. };
  26008. return Ground;
  26009. })(_Primitive);
  26010. Primitives.Ground = Ground;
  26011. var TiledGround = (function (_super) {
  26012. __extends(TiledGround, _super);
  26013. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26014. this.xmin = xmin;
  26015. this.zmin = zmin;
  26016. this.xmax = xmax;
  26017. this.zmax = zmax;
  26018. this.subdivisions = subdivisions;
  26019. this.precision = precision;
  26020. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26021. }
  26022. TiledGround.prototype._regenerateVertexData = function () {
  26023. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  26024. };
  26025. TiledGround.prototype.copy = function (id) {
  26026. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26027. };
  26028. return TiledGround;
  26029. })(_Primitive);
  26030. Primitives.TiledGround = TiledGround;
  26031. var Plane = (function (_super) {
  26032. __extends(Plane, _super);
  26033. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26034. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26035. this.size = size;
  26036. this.side = side;
  26037. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26038. }
  26039. Plane.prototype._regenerateVertexData = function () {
  26040. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  26041. };
  26042. Plane.prototype.copy = function (id) {
  26043. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26044. };
  26045. return Plane;
  26046. })(_Primitive);
  26047. Primitives.Plane = Plane;
  26048. var TorusKnot = (function (_super) {
  26049. __extends(TorusKnot, _super);
  26050. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26051. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26052. this.radius = radius;
  26053. this.tube = tube;
  26054. this.radialSegments = radialSegments;
  26055. this.tubularSegments = tubularSegments;
  26056. this.p = p;
  26057. this.q = q;
  26058. this.side = side;
  26059. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26060. }
  26061. TorusKnot.prototype._regenerateVertexData = function () {
  26062. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  26063. };
  26064. TorusKnot.prototype.copy = function (id) {
  26065. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26066. };
  26067. return TorusKnot;
  26068. })(_Primitive);
  26069. Primitives.TorusKnot = TorusKnot;
  26070. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26071. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26072. })(BABYLON || (BABYLON = {}));
  26073. //# sourceMappingURL=babylon.geometry.js.map
  26074. var BABYLON;
  26075. (function (BABYLON) {
  26076. var Gamepads = (function () {
  26077. function Gamepads(ongamedpadconnected) {
  26078. var _this = this;
  26079. this.babylonGamepads = [];
  26080. this.oneGamepadConnected = false;
  26081. this.isMonitoring = false;
  26082. this.gamepadEventSupported = 'GamepadEvent' in window;
  26083. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  26084. 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=";
  26085. this._callbackGamepadConnected = ongamedpadconnected;
  26086. if (this.gamepadSupportAvailable) {
  26087. // Checking if the gamepad connected event is supported (like in Firefox)
  26088. if (this.gamepadEventSupported) {
  26089. window.addEventListener('gamepadconnected', function (evt) {
  26090. _this._onGamepadConnected(evt);
  26091. }, false);
  26092. window.addEventListener('gamepaddisconnected', function (evt) {
  26093. _this._onGamepadDisconnected(evt);
  26094. }, false);
  26095. }
  26096. else {
  26097. this._startMonitoringGamepads();
  26098. }
  26099. if (!this.oneGamepadConnected) {
  26100. this._insertGamepadDOMInstructions();
  26101. }
  26102. }
  26103. else {
  26104. this._insertGamepadDOMNotSupported();
  26105. }
  26106. }
  26107. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  26108. Gamepads.gamepadDOMInfo = document.createElement("div");
  26109. var buttonAImage = document.createElement("img");
  26110. buttonAImage.src = this.buttonADataURL;
  26111. var spanMessage = document.createElement("span");
  26112. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  26113. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  26114. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26115. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26116. Gamepads.gamepadDOMInfo.style.width = "100%";
  26117. Gamepads.gamepadDOMInfo.style.height = "48px";
  26118. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26119. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26120. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26121. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26122. buttonAImage.style.position = "relative";
  26123. buttonAImage.style.bottom = "8px";
  26124. spanMessage.style.position = "relative";
  26125. spanMessage.style.fontSize = "32px";
  26126. spanMessage.style.bottom = "32px";
  26127. spanMessage.style.color = "green";
  26128. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26129. };
  26130. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  26131. Gamepads.gamepadDOMInfo = document.createElement("div");
  26132. var spanMessage = document.createElement("span");
  26133. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  26134. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26135. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26136. Gamepads.gamepadDOMInfo.style.width = "100%";
  26137. Gamepads.gamepadDOMInfo.style.height = "40px";
  26138. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26139. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26140. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26141. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26142. spanMessage.style.position = "relative";
  26143. spanMessage.style.fontSize = "32px";
  26144. spanMessage.style.color = "red";
  26145. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26146. };
  26147. Gamepads.prototype.dispose = function () {
  26148. if (Gamepads.gamepadDOMInfo) {
  26149. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26150. }
  26151. };
  26152. Gamepads.prototype._onGamepadConnected = function (evt) {
  26153. var newGamepad = this._addNewGamepad(evt.gamepad);
  26154. if (this._callbackGamepadConnected)
  26155. this._callbackGamepadConnected(newGamepad);
  26156. this._startMonitoringGamepads();
  26157. };
  26158. Gamepads.prototype._addNewGamepad = function (gamepad) {
  26159. if (!this.oneGamepadConnected) {
  26160. this.oneGamepadConnected = true;
  26161. if (Gamepads.gamepadDOMInfo) {
  26162. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26163. Gamepads.gamepadDOMInfo = null;
  26164. }
  26165. }
  26166. var newGamepad;
  26167. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  26168. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  26169. }
  26170. else {
  26171. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  26172. }
  26173. this.babylonGamepads.push(newGamepad);
  26174. return newGamepad;
  26175. };
  26176. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  26177. for (var i in this.babylonGamepads) {
  26178. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  26179. this.babylonGamepads.splice(i, 1);
  26180. break;
  26181. }
  26182. }
  26183. // If no gamepads are left, stop the polling loop.
  26184. if (this.babylonGamepads.length == 0) {
  26185. this._stopMonitoringGamepads();
  26186. }
  26187. };
  26188. Gamepads.prototype._startMonitoringGamepads = function () {
  26189. if (!this.isMonitoring) {
  26190. this.isMonitoring = true;
  26191. this._checkGamepadsStatus();
  26192. }
  26193. };
  26194. Gamepads.prototype._stopMonitoringGamepads = function () {
  26195. this.isMonitoring = false;
  26196. };
  26197. Gamepads.prototype._checkGamepadsStatus = function () {
  26198. var _this = this;
  26199. // updating gamepad objects
  26200. this._updateGamepadObjects();
  26201. for (var i in this.babylonGamepads) {
  26202. this.babylonGamepads[i].update();
  26203. }
  26204. if (this.isMonitoring) {
  26205. if (window.requestAnimationFrame) {
  26206. window.requestAnimationFrame(function () {
  26207. _this._checkGamepadsStatus();
  26208. });
  26209. }
  26210. else if (window.mozRequestAnimationFrame) {
  26211. window.mozRequestAnimationFrame(function () {
  26212. _this._checkGamepadsStatus();
  26213. });
  26214. }
  26215. else if (window.webkitRequestAnimationFrame) {
  26216. window.webkitRequestAnimationFrame(function () {
  26217. _this._checkGamepadsStatus();
  26218. });
  26219. }
  26220. }
  26221. };
  26222. // This function is called only on Chrome, which does not yet support
  26223. // connection/disconnection events, but requires you to monitor
  26224. // an array for changes.
  26225. Gamepads.prototype._updateGamepadObjects = function () {
  26226. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  26227. for (var i = 0; i < gamepads.length; i++) {
  26228. if (gamepads[i]) {
  26229. if (!(gamepads[i].index in this.babylonGamepads)) {
  26230. var newGamepad = this._addNewGamepad(gamepads[i]);
  26231. if (this._callbackGamepadConnected) {
  26232. this._callbackGamepadConnected(newGamepad);
  26233. }
  26234. }
  26235. else {
  26236. this.babylonGamepads[i].browserGamepad = gamepads[i];
  26237. }
  26238. }
  26239. }
  26240. };
  26241. return Gamepads;
  26242. })();
  26243. BABYLON.Gamepads = Gamepads;
  26244. var StickValues = (function () {
  26245. function StickValues(x, y) {
  26246. this.x = x;
  26247. this.y = y;
  26248. }
  26249. return StickValues;
  26250. })();
  26251. BABYLON.StickValues = StickValues;
  26252. var Gamepad = (function () {
  26253. function Gamepad(id, index, browserGamepad) {
  26254. this.id = id;
  26255. this.index = index;
  26256. this.browserGamepad = browserGamepad;
  26257. if (this.browserGamepad.axes.length >= 2) {
  26258. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26259. }
  26260. if (this.browserGamepad.axes.length >= 4) {
  26261. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26262. }
  26263. }
  26264. Gamepad.prototype.onleftstickchanged = function (callback) {
  26265. this._onleftstickchanged = callback;
  26266. };
  26267. Gamepad.prototype.onrightstickchanged = function (callback) {
  26268. this._onrightstickchanged = callback;
  26269. };
  26270. Object.defineProperty(Gamepad.prototype, "leftStick", {
  26271. get: function () {
  26272. return this._leftStick;
  26273. },
  26274. set: function (newValues) {
  26275. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26276. this._onleftstickchanged(newValues);
  26277. }
  26278. this._leftStick = newValues;
  26279. },
  26280. enumerable: true,
  26281. configurable: true
  26282. });
  26283. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26284. get: function () {
  26285. return this._rightStick;
  26286. },
  26287. set: function (newValues) {
  26288. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26289. this._onrightstickchanged(newValues);
  26290. }
  26291. this._rightStick = newValues;
  26292. },
  26293. enumerable: true,
  26294. configurable: true
  26295. });
  26296. Gamepad.prototype.update = function () {
  26297. if (this._leftStick) {
  26298. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26299. }
  26300. if (this._rightStick) {
  26301. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26302. }
  26303. };
  26304. return Gamepad;
  26305. })();
  26306. BABYLON.Gamepad = Gamepad;
  26307. var GenericPad = (function (_super) {
  26308. __extends(GenericPad, _super);
  26309. function GenericPad(id, index, gamepad) {
  26310. _super.call(this, id, index, gamepad);
  26311. this.id = id;
  26312. this.index = index;
  26313. this.gamepad = gamepad;
  26314. this._buttons = new Array(gamepad.buttons.length);
  26315. }
  26316. GenericPad.prototype.onbuttondown = function (callback) {
  26317. this._onbuttondown = callback;
  26318. };
  26319. GenericPad.prototype.onbuttonup = function (callback) {
  26320. this._onbuttonup = callback;
  26321. };
  26322. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26323. if (newValue !== currentValue) {
  26324. if (this._onbuttondown && newValue === 1) {
  26325. this._onbuttondown(buttonIndex);
  26326. }
  26327. if (this._onbuttonup && newValue === 0) {
  26328. this._onbuttonup(buttonIndex);
  26329. }
  26330. }
  26331. return newValue;
  26332. };
  26333. GenericPad.prototype.update = function () {
  26334. _super.prototype.update.call(this);
  26335. for (var index = 0; index < this._buttons.length; index++) {
  26336. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26337. }
  26338. };
  26339. return GenericPad;
  26340. })(Gamepad);
  26341. BABYLON.GenericPad = GenericPad;
  26342. (function (Xbox360Button) {
  26343. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26344. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26345. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26346. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26347. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26348. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26349. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26350. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26351. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26352. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26353. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26354. var Xbox360Button = BABYLON.Xbox360Button;
  26355. (function (Xbox360Dpad) {
  26356. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26357. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26358. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26359. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26360. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26361. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26362. var Xbox360Pad = (function (_super) {
  26363. __extends(Xbox360Pad, _super);
  26364. function Xbox360Pad() {
  26365. _super.apply(this, arguments);
  26366. this._leftTrigger = 0;
  26367. this._rightTrigger = 0;
  26368. this._buttonA = 0;
  26369. this._buttonB = 0;
  26370. this._buttonX = 0;
  26371. this._buttonY = 0;
  26372. this._buttonBack = 0;
  26373. this._buttonStart = 0;
  26374. this._buttonLB = 0;
  26375. this._buttonRB = 0;
  26376. this._buttonLeftStick = 0;
  26377. this._buttonRightStick = 0;
  26378. this._dPadUp = 0;
  26379. this._dPadDown = 0;
  26380. this._dPadLeft = 0;
  26381. this._dPadRight = 0;
  26382. }
  26383. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26384. this._onlefttriggerchanged = callback;
  26385. };
  26386. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26387. this._onrighttriggerchanged = callback;
  26388. };
  26389. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26390. get: function () {
  26391. return this._leftTrigger;
  26392. },
  26393. set: function (newValue) {
  26394. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26395. this._onlefttriggerchanged(newValue);
  26396. }
  26397. this._leftTrigger = newValue;
  26398. },
  26399. enumerable: true,
  26400. configurable: true
  26401. });
  26402. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26403. get: function () {
  26404. return this._rightTrigger;
  26405. },
  26406. set: function (newValue) {
  26407. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26408. this._onrighttriggerchanged(newValue);
  26409. }
  26410. this._rightTrigger = newValue;
  26411. },
  26412. enumerable: true,
  26413. configurable: true
  26414. });
  26415. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26416. this._onbuttondown = callback;
  26417. };
  26418. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26419. this._onbuttonup = callback;
  26420. };
  26421. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26422. this._ondpaddown = callback;
  26423. };
  26424. Xbox360Pad.prototype.ondpadup = function (callback) {
  26425. this._ondpadup = callback;
  26426. };
  26427. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26428. if (newValue !== currentValue) {
  26429. if (this._onbuttondown && newValue === 1) {
  26430. this._onbuttondown(buttonType);
  26431. }
  26432. if (this._onbuttonup && newValue === 0) {
  26433. this._onbuttonup(buttonType);
  26434. }
  26435. }
  26436. return newValue;
  26437. };
  26438. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26439. if (newValue !== currentValue) {
  26440. if (this._ondpaddown && newValue === 1) {
  26441. this._ondpaddown(buttonType);
  26442. }
  26443. if (this._ondpadup && newValue === 0) {
  26444. this._ondpadup(buttonType);
  26445. }
  26446. }
  26447. return newValue;
  26448. };
  26449. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26450. get: function () {
  26451. return this._buttonA;
  26452. },
  26453. set: function (value) {
  26454. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26455. },
  26456. enumerable: true,
  26457. configurable: true
  26458. });
  26459. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26460. get: function () {
  26461. return this._buttonB;
  26462. },
  26463. set: function (value) {
  26464. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26465. },
  26466. enumerable: true,
  26467. configurable: true
  26468. });
  26469. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26470. get: function () {
  26471. return this._buttonX;
  26472. },
  26473. set: function (value) {
  26474. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26475. },
  26476. enumerable: true,
  26477. configurable: true
  26478. });
  26479. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26480. get: function () {
  26481. return this._buttonY;
  26482. },
  26483. set: function (value) {
  26484. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26485. },
  26486. enumerable: true,
  26487. configurable: true
  26488. });
  26489. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26490. get: function () {
  26491. return this._buttonStart;
  26492. },
  26493. set: function (value) {
  26494. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26495. },
  26496. enumerable: true,
  26497. configurable: true
  26498. });
  26499. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26500. get: function () {
  26501. return this._buttonBack;
  26502. },
  26503. set: function (value) {
  26504. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26505. },
  26506. enumerable: true,
  26507. configurable: true
  26508. });
  26509. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26510. get: function () {
  26511. return this._buttonLB;
  26512. },
  26513. set: function (value) {
  26514. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26515. },
  26516. enumerable: true,
  26517. configurable: true
  26518. });
  26519. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26520. get: function () {
  26521. return this._buttonRB;
  26522. },
  26523. set: function (value) {
  26524. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26525. },
  26526. enumerable: true,
  26527. configurable: true
  26528. });
  26529. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26530. get: function () {
  26531. return this._buttonLeftStick;
  26532. },
  26533. set: function (value) {
  26534. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26535. },
  26536. enumerable: true,
  26537. configurable: true
  26538. });
  26539. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26540. get: function () {
  26541. return this._buttonRightStick;
  26542. },
  26543. set: function (value) {
  26544. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26545. },
  26546. enumerable: true,
  26547. configurable: true
  26548. });
  26549. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26550. get: function () {
  26551. return this._dPadUp;
  26552. },
  26553. set: function (value) {
  26554. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26555. },
  26556. enumerable: true,
  26557. configurable: true
  26558. });
  26559. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26560. get: function () {
  26561. return this._dPadDown;
  26562. },
  26563. set: function (value) {
  26564. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26565. },
  26566. enumerable: true,
  26567. configurable: true
  26568. });
  26569. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26570. get: function () {
  26571. return this._dPadLeft;
  26572. },
  26573. set: function (value) {
  26574. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26575. },
  26576. enumerable: true,
  26577. configurable: true
  26578. });
  26579. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26580. get: function () {
  26581. return this._dPadRight;
  26582. },
  26583. set: function (value) {
  26584. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26585. },
  26586. enumerable: true,
  26587. configurable: true
  26588. });
  26589. Xbox360Pad.prototype.update = function () {
  26590. _super.prototype.update.call(this);
  26591. this.buttonA = this.browserGamepad.buttons[0].value;
  26592. this.buttonB = this.browserGamepad.buttons[1].value;
  26593. this.buttonX = this.browserGamepad.buttons[2].value;
  26594. this.buttonY = this.browserGamepad.buttons[3].value;
  26595. this.buttonLB = this.browserGamepad.buttons[4].value;
  26596. this.buttonRB = this.browserGamepad.buttons[5].value;
  26597. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26598. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26599. this.buttonBack = this.browserGamepad.buttons[8].value;
  26600. this.buttonStart = this.browserGamepad.buttons[9].value;
  26601. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26602. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26603. this.dPadUp = this.browserGamepad.buttons[12].value;
  26604. this.dPadDown = this.browserGamepad.buttons[13].value;
  26605. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26606. this.dPadRight = this.browserGamepad.buttons[15].value;
  26607. };
  26608. return Xbox360Pad;
  26609. })(Gamepad);
  26610. BABYLON.Xbox360Pad = Xbox360Pad;
  26611. })(BABYLON || (BABYLON = {}));
  26612. //# sourceMappingURL=babylon.gamepads.js.map
  26613. var BABYLON;
  26614. (function (BABYLON) {
  26615. // We're mainly based on the logic defined into the FreeCamera code
  26616. var GamepadCamera = (function (_super) {
  26617. __extends(GamepadCamera, _super);
  26618. function GamepadCamera(name, position, scene) {
  26619. var _this = this;
  26620. _super.call(this, name, position, scene);
  26621. this.angularSensibility = 200;
  26622. this.moveSensibility = 75;
  26623. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26624. _this._onNewGameConnected(gamepad);
  26625. });
  26626. }
  26627. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26628. // Only the first gamepad can control the camera
  26629. if (gamepad.index === 0) {
  26630. this._gamepad = gamepad;
  26631. }
  26632. };
  26633. GamepadCamera.prototype._checkInputs = function () {
  26634. if (!this._gamepad) {
  26635. return;
  26636. }
  26637. var LSValues = this._gamepad.leftStick;
  26638. var normalizedLX = LSValues.x / this.moveSensibility;
  26639. var normalizedLY = LSValues.y / this.moveSensibility;
  26640. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26641. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26642. var RSValues = this._gamepad.rightStick;
  26643. var normalizedRX = RSValues.x / this.angularSensibility;
  26644. var normalizedRY = RSValues.y / this.angularSensibility;
  26645. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26646. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26647. ;
  26648. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26649. var speed = this._computeLocalCameraSpeed() * 50.0;
  26650. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26651. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26652. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26653. };
  26654. GamepadCamera.prototype.dispose = function () {
  26655. this._gamepads.dispose();
  26656. _super.prototype.dispose.call(this);
  26657. };
  26658. return GamepadCamera;
  26659. })(BABYLON.FreeCamera);
  26660. BABYLON.GamepadCamera = GamepadCamera;
  26661. })(BABYLON || (BABYLON = {}));
  26662. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26663. var BABYLON;
  26664. (function (BABYLON) {
  26665. var LinesMesh = (function (_super) {
  26666. __extends(LinesMesh, _super);
  26667. function LinesMesh(name, scene, updatable) {
  26668. if (updatable === void 0) { updatable = false; }
  26669. _super.call(this, name, scene);
  26670. this.color = new BABYLON.Color3(1, 1, 1);
  26671. this.alpha = 1;
  26672. this._indices = new Array();
  26673. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26674. attributes: ["position"],
  26675. uniforms: ["worldViewProjection", "color"],
  26676. needAlphaBlending: true
  26677. });
  26678. }
  26679. Object.defineProperty(LinesMesh.prototype, "material", {
  26680. get: function () {
  26681. return this._colorShader;
  26682. },
  26683. enumerable: true,
  26684. configurable: true
  26685. });
  26686. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26687. get: function () {
  26688. return false;
  26689. },
  26690. enumerable: true,
  26691. configurable: true
  26692. });
  26693. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26694. get: function () {
  26695. return false;
  26696. },
  26697. enumerable: true,
  26698. configurable: true
  26699. });
  26700. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26701. var engine = this.getScene().getEngine();
  26702. var indexToBind = this._geometry.getIndexBuffer();
  26703. // VBOs
  26704. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26705. // Color
  26706. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26707. };
  26708. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26709. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26710. return;
  26711. }
  26712. var engine = this.getScene().getEngine();
  26713. // Draw order
  26714. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26715. };
  26716. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26717. return null;
  26718. };
  26719. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26720. this._colorShader.dispose();
  26721. _super.prototype.dispose.call(this, doNotRecurse);
  26722. };
  26723. return LinesMesh;
  26724. })(BABYLON.Mesh);
  26725. BABYLON.LinesMesh = LinesMesh;
  26726. })(BABYLON || (BABYLON = {}));
  26727. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26728. (function (BABYLON) {
  26729. var OutlineRenderer = (function () {
  26730. function OutlineRenderer(scene) {
  26731. this._scene = scene;
  26732. }
  26733. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26734. var _this = this;
  26735. if (useOverlay === void 0) { useOverlay = false; }
  26736. var scene = this._scene;
  26737. var engine = this._scene.getEngine();
  26738. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26739. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26740. return;
  26741. }
  26742. var mesh = subMesh.getRenderingMesh();
  26743. var material = subMesh.getMaterial();
  26744. engine.enableEffect(this._effect);
  26745. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26746. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26747. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26748. // Bones
  26749. if (mesh.useBones) {
  26750. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26751. }
  26752. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26753. // Alpha test
  26754. if (material && material.needAlphaTesting()) {
  26755. var alphaTexture = material.getAlphaTestTexture();
  26756. this._effect.setTexture("diffuseSampler", alphaTexture);
  26757. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26758. }
  26759. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26760. _this._effect.setMatrix("world", world);
  26761. });
  26762. };
  26763. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26764. var defines = [];
  26765. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26766. var mesh = subMesh.getMesh();
  26767. var material = subMesh.getMaterial();
  26768. // Alpha test
  26769. if (material && material.needAlphaTesting()) {
  26770. defines.push("#define ALPHATEST");
  26771. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26772. attribs.push(BABYLON.VertexBuffer.UVKind);
  26773. defines.push("#define UV1");
  26774. }
  26775. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26776. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26777. defines.push("#define UV2");
  26778. }
  26779. }
  26780. // Bones
  26781. if (mesh.useBones) {
  26782. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26783. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26784. defines.push("#define BONES");
  26785. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26786. }
  26787. // Instances
  26788. if (useInstances) {
  26789. defines.push("#define INSTANCES");
  26790. attribs.push("world0");
  26791. attribs.push("world1");
  26792. attribs.push("world2");
  26793. attribs.push("world3");
  26794. }
  26795. // Get correct effect
  26796. var join = defines.join("\n");
  26797. if (this._cachedDefines !== join) {
  26798. this._cachedDefines = join;
  26799. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26800. }
  26801. return this._effect.isReady();
  26802. };
  26803. return OutlineRenderer;
  26804. })();
  26805. BABYLON.OutlineRenderer = OutlineRenderer;
  26806. })(BABYLON || (BABYLON = {}));
  26807. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26808. (function (BABYLON) {
  26809. var MeshAssetTask = (function () {
  26810. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26811. this.name = name;
  26812. this.meshesNames = meshesNames;
  26813. this.rootUrl = rootUrl;
  26814. this.sceneFilename = sceneFilename;
  26815. this.isCompleted = false;
  26816. }
  26817. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26818. var _this = this;
  26819. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26820. _this.loadedMeshes = meshes;
  26821. _this.loadedParticleSystems = particleSystems;
  26822. _this.loadedSkeletons = skeletons;
  26823. _this.isCompleted = true;
  26824. if (_this.onSuccess) {
  26825. _this.onSuccess(_this);
  26826. }
  26827. onSuccess();
  26828. }, null, function () {
  26829. if (_this.onError) {
  26830. _this.onError(_this);
  26831. }
  26832. onError();
  26833. });
  26834. };
  26835. return MeshAssetTask;
  26836. })();
  26837. BABYLON.MeshAssetTask = MeshAssetTask;
  26838. var TextFileAssetTask = (function () {
  26839. function TextFileAssetTask(name, url) {
  26840. this.name = name;
  26841. this.url = url;
  26842. this.isCompleted = false;
  26843. }
  26844. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26845. var _this = this;
  26846. BABYLON.Tools.LoadFile(this.url, function (data) {
  26847. _this.text = data;
  26848. _this.isCompleted = true;
  26849. if (_this.onSuccess) {
  26850. _this.onSuccess(_this);
  26851. }
  26852. onSuccess();
  26853. }, null, scene.database, false, function () {
  26854. if (_this.onError) {
  26855. _this.onError(_this);
  26856. }
  26857. onError();
  26858. });
  26859. };
  26860. return TextFileAssetTask;
  26861. })();
  26862. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26863. var BinaryFileAssetTask = (function () {
  26864. function BinaryFileAssetTask(name, url) {
  26865. this.name = name;
  26866. this.url = url;
  26867. this.isCompleted = false;
  26868. }
  26869. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26870. var _this = this;
  26871. BABYLON.Tools.LoadFile(this.url, function (data) {
  26872. _this.data = data;
  26873. _this.isCompleted = true;
  26874. if (_this.onSuccess) {
  26875. _this.onSuccess(_this);
  26876. }
  26877. onSuccess();
  26878. }, null, scene.database, true, function () {
  26879. if (_this.onError) {
  26880. _this.onError(_this);
  26881. }
  26882. onError();
  26883. });
  26884. };
  26885. return BinaryFileAssetTask;
  26886. })();
  26887. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26888. var ImageAssetTask = (function () {
  26889. function ImageAssetTask(name, url) {
  26890. this.name = name;
  26891. this.url = url;
  26892. this.isCompleted = false;
  26893. }
  26894. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26895. var _this = this;
  26896. var img = new Image();
  26897. img.onload = function () {
  26898. _this.image = img;
  26899. _this.isCompleted = true;
  26900. if (_this.onSuccess) {
  26901. _this.onSuccess(_this);
  26902. }
  26903. onSuccess();
  26904. };
  26905. img.onerror = function () {
  26906. if (_this.onError) {
  26907. _this.onError(_this);
  26908. }
  26909. onError();
  26910. };
  26911. img.src = this.url;
  26912. };
  26913. return ImageAssetTask;
  26914. })();
  26915. BABYLON.ImageAssetTask = ImageAssetTask;
  26916. var TextureAssetTask = (function () {
  26917. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26919. this.name = name;
  26920. this.url = url;
  26921. this.noMipmap = noMipmap;
  26922. this.invertY = invertY;
  26923. this.samplingMode = samplingMode;
  26924. this.isCompleted = false;
  26925. }
  26926. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26927. var _this = this;
  26928. var onload = function () {
  26929. _this.isCompleted = true;
  26930. if (_this.onSuccess) {
  26931. _this.onSuccess(_this);
  26932. }
  26933. onSuccess();
  26934. };
  26935. var onerror = function () {
  26936. if (_this.onError) {
  26937. _this.onError(_this);
  26938. }
  26939. onError();
  26940. };
  26941. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26942. };
  26943. return TextureAssetTask;
  26944. })();
  26945. BABYLON.TextureAssetTask = TextureAssetTask;
  26946. var AssetsManager = (function () {
  26947. function AssetsManager(scene) {
  26948. this._tasks = new Array();
  26949. this._waitingTasksCount = 0;
  26950. this.useDefaultLoadingScreen = true;
  26951. this._scene = scene;
  26952. }
  26953. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26954. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26955. this._tasks.push(task);
  26956. return task;
  26957. };
  26958. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26959. var task = new TextFileAssetTask(taskName, url);
  26960. this._tasks.push(task);
  26961. return task;
  26962. };
  26963. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26964. var task = new BinaryFileAssetTask(taskName, url);
  26965. this._tasks.push(task);
  26966. return task;
  26967. };
  26968. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26969. var task = new ImageAssetTask(taskName, url);
  26970. this._tasks.push(task);
  26971. return task;
  26972. };
  26973. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26974. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26975. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26976. this._tasks.push(task);
  26977. return task;
  26978. };
  26979. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26980. this._waitingTasksCount--;
  26981. if (this._waitingTasksCount === 0) {
  26982. if (this.onFinish) {
  26983. this.onFinish(this._tasks);
  26984. }
  26985. this._scene.getEngine().hideLoadingUI();
  26986. }
  26987. };
  26988. AssetsManager.prototype._runTask = function (task) {
  26989. var _this = this;
  26990. task.run(this._scene, function () {
  26991. if (_this.onTaskSuccess) {
  26992. _this.onTaskSuccess(task);
  26993. }
  26994. _this._decreaseWaitingTasksCount();
  26995. }, function () {
  26996. if (_this.onTaskError) {
  26997. _this.onTaskError(task);
  26998. }
  26999. _this._decreaseWaitingTasksCount();
  27000. });
  27001. };
  27002. AssetsManager.prototype.reset = function () {
  27003. this._tasks = new Array();
  27004. return this;
  27005. };
  27006. AssetsManager.prototype.load = function () {
  27007. this._waitingTasksCount = this._tasks.length;
  27008. if (this._waitingTasksCount === 0) {
  27009. if (this.onFinish) {
  27010. this.onFinish(this._tasks);
  27011. }
  27012. return this;
  27013. }
  27014. if (this.useDefaultLoadingScreen) {
  27015. this._scene.getEngine().displayLoadingUI();
  27016. }
  27017. for (var index = 0; index < this._tasks.length; index++) {
  27018. var task = this._tasks[index];
  27019. this._runTask(task);
  27020. }
  27021. return this;
  27022. };
  27023. return AssetsManager;
  27024. })();
  27025. BABYLON.AssetsManager = AssetsManager;
  27026. })(BABYLON || (BABYLON = {}));
  27027. //# sourceMappingURL=babylon.assetsManager.js.map
  27028. var BABYLON;
  27029. (function (BABYLON) {
  27030. var VRDeviceOrientationCamera = (function (_super) {
  27031. __extends(VRDeviceOrientationCamera, _super);
  27032. function VRDeviceOrientationCamera(name, position, scene) {
  27033. _super.call(this, name, position, scene);
  27034. this._alpha = 0;
  27035. this._beta = 0;
  27036. this._gamma = 0;
  27037. }
  27038. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  27039. this._alpha = +evt.alpha | 0;
  27040. this._beta = +evt.beta | 0;
  27041. this._gamma = +evt.gamma | 0;
  27042. if (this._gamma < 0) {
  27043. this._gamma = 90 + this._gamma;
  27044. }
  27045. else {
  27046. // Incline it in the correct angle.
  27047. this._gamma = 270 - this._gamma;
  27048. }
  27049. this.rotation.x = this._gamma / 180.0 * Math.PI;
  27050. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  27051. this.rotation.z = this._beta / 180.0 * Math.PI;
  27052. };
  27053. return VRDeviceOrientationCamera;
  27054. })(BABYLON.OculusCamera);
  27055. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  27056. })(BABYLON || (BABYLON = {}));
  27057. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  27058. var BABYLON;
  27059. (function (BABYLON) {
  27060. var WebVRCamera = (function (_super) {
  27061. __extends(WebVRCamera, _super);
  27062. function WebVRCamera(name, position, scene) {
  27063. _super.call(this, name, position, scene);
  27064. this._hmdDevice = null;
  27065. this._sensorDevice = null;
  27066. this._cacheState = null;
  27067. this._cacheQuaternion = new BABYLON.Quaternion();
  27068. this._cacheRotation = BABYLON.Vector3.Zero();
  27069. this._vrEnabled = false;
  27070. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  27071. }
  27072. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  27073. var size = devices.length;
  27074. var i = 0;
  27075. // Reset devices.
  27076. this._sensorDevice = null;
  27077. this._hmdDevice = null;
  27078. while (i < size && this._hmdDevice === null) {
  27079. if (devices[i] instanceof HMDVRDevice) {
  27080. this._hmdDevice = devices[i];
  27081. }
  27082. i++;
  27083. }
  27084. i = 0;
  27085. while (i < size && this._sensorDevice === null) {
  27086. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  27087. this._sensorDevice = devices[i];
  27088. }
  27089. i++;
  27090. }
  27091. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  27092. };
  27093. WebVRCamera.prototype._update = function () {
  27094. if (this._vrEnabled) {
  27095. this._cacheState = this._sensorDevice.getState();
  27096. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  27097. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  27098. this.rotation.x = -this._cacheRotation.z;
  27099. this.rotation.y = -this._cacheRotation.y;
  27100. this.rotation.z = this._cacheRotation.x;
  27101. }
  27102. _super.prototype._update.call(this);
  27103. };
  27104. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  27105. _super.prototype.attachControl.call(this, element, noPreventDefault);
  27106. if (navigator.getVRDevices) {
  27107. navigator.getVRDevices().then(this._getWebVRDevices);
  27108. }
  27109. else if (navigator.mozGetVRDevices) {
  27110. navigator.mozGetVRDevices(this._getWebVRDevices);
  27111. }
  27112. };
  27113. WebVRCamera.prototype.detachControl = function (element) {
  27114. _super.prototype.detachControl.call(this, element);
  27115. this._vrEnabled = false;
  27116. };
  27117. return WebVRCamera;
  27118. })(BABYLON.OculusCamera);
  27119. BABYLON.WebVRCamera = WebVRCamera;
  27120. })(BABYLON || (BABYLON = {}));
  27121. //# sourceMappingURL=babylon.webVRCamera.js.map
  27122. var BABYLON;
  27123. (function (BABYLON) {
  27124. // Standard optimizations
  27125. var SceneOptimization = (function () {
  27126. function SceneOptimization(priority) {
  27127. if (priority === void 0) { priority = 0; }
  27128. this.priority = priority;
  27129. this.apply = function (scene) {
  27130. return true; // Return true if everything that can be done was applied
  27131. };
  27132. }
  27133. return SceneOptimization;
  27134. })();
  27135. BABYLON.SceneOptimization = SceneOptimization;
  27136. var TextureOptimization = (function (_super) {
  27137. __extends(TextureOptimization, _super);
  27138. function TextureOptimization(priority, maximumSize) {
  27139. var _this = this;
  27140. if (priority === void 0) { priority = 0; }
  27141. if (maximumSize === void 0) { maximumSize = 1024; }
  27142. _super.call(this, priority);
  27143. this.priority = priority;
  27144. this.maximumSize = maximumSize;
  27145. this.apply = function (scene) {
  27146. var allDone = true;
  27147. for (var index = 0; index < scene.textures.length; index++) {
  27148. var texture = scene.textures[index];
  27149. if (!texture.canRescale) {
  27150. continue;
  27151. }
  27152. var currentSize = texture.getSize();
  27153. var maxDimension = Math.max(currentSize.width, currentSize.height);
  27154. if (maxDimension > _this.maximumSize) {
  27155. texture.scale(0.5);
  27156. allDone = false;
  27157. }
  27158. }
  27159. return allDone;
  27160. };
  27161. }
  27162. return TextureOptimization;
  27163. })(SceneOptimization);
  27164. BABYLON.TextureOptimization = TextureOptimization;
  27165. var HardwareScalingOptimization = (function (_super) {
  27166. __extends(HardwareScalingOptimization, _super);
  27167. function HardwareScalingOptimization(priority, maximumScale) {
  27168. var _this = this;
  27169. if (priority === void 0) { priority = 0; }
  27170. if (maximumScale === void 0) { maximumScale = 2; }
  27171. _super.call(this, priority);
  27172. this.priority = priority;
  27173. this.maximumScale = maximumScale;
  27174. this._currentScale = 1;
  27175. this.apply = function (scene) {
  27176. _this._currentScale++;
  27177. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  27178. return _this._currentScale >= _this.maximumScale;
  27179. };
  27180. }
  27181. return HardwareScalingOptimization;
  27182. })(SceneOptimization);
  27183. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  27184. var ShadowsOptimization = (function (_super) {
  27185. __extends(ShadowsOptimization, _super);
  27186. function ShadowsOptimization() {
  27187. _super.apply(this, arguments);
  27188. this.apply = function (scene) {
  27189. scene.shadowsEnabled = false;
  27190. return true;
  27191. };
  27192. }
  27193. return ShadowsOptimization;
  27194. })(SceneOptimization);
  27195. BABYLON.ShadowsOptimization = ShadowsOptimization;
  27196. var PostProcessesOptimization = (function (_super) {
  27197. __extends(PostProcessesOptimization, _super);
  27198. function PostProcessesOptimization() {
  27199. _super.apply(this, arguments);
  27200. this.apply = function (scene) {
  27201. scene.postProcessesEnabled = false;
  27202. return true;
  27203. };
  27204. }
  27205. return PostProcessesOptimization;
  27206. })(SceneOptimization);
  27207. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  27208. var LensFlaresOptimization = (function (_super) {
  27209. __extends(LensFlaresOptimization, _super);
  27210. function LensFlaresOptimization() {
  27211. _super.apply(this, arguments);
  27212. this.apply = function (scene) {
  27213. scene.lensFlaresEnabled = false;
  27214. return true;
  27215. };
  27216. }
  27217. return LensFlaresOptimization;
  27218. })(SceneOptimization);
  27219. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  27220. var ParticlesOptimization = (function (_super) {
  27221. __extends(ParticlesOptimization, _super);
  27222. function ParticlesOptimization() {
  27223. _super.apply(this, arguments);
  27224. this.apply = function (scene) {
  27225. scene.particlesEnabled = false;
  27226. return true;
  27227. };
  27228. }
  27229. return ParticlesOptimization;
  27230. })(SceneOptimization);
  27231. BABYLON.ParticlesOptimization = ParticlesOptimization;
  27232. var RenderTargetsOptimization = (function (_super) {
  27233. __extends(RenderTargetsOptimization, _super);
  27234. function RenderTargetsOptimization() {
  27235. _super.apply(this, arguments);
  27236. this.apply = function (scene) {
  27237. scene.renderTargetsEnabled = false;
  27238. return true;
  27239. };
  27240. }
  27241. return RenderTargetsOptimization;
  27242. })(SceneOptimization);
  27243. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  27244. var MergeMeshesOptimization = (function (_super) {
  27245. __extends(MergeMeshesOptimization, _super);
  27246. function MergeMeshesOptimization() {
  27247. var _this = this;
  27248. _super.apply(this, arguments);
  27249. this._canBeMerged = function (abstractMesh) {
  27250. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  27251. return false;
  27252. }
  27253. var mesh = abstractMesh;
  27254. if (!mesh.isVisible || !mesh.isEnabled()) {
  27255. return false;
  27256. }
  27257. if (mesh.instances.length > 0) {
  27258. return false;
  27259. }
  27260. if (mesh.skeleton || mesh.hasLODLevels) {
  27261. return false;
  27262. }
  27263. return true;
  27264. };
  27265. this.apply = function (scene) {
  27266. var globalPool = scene.meshes.slice(0);
  27267. var globalLength = globalPool.length;
  27268. for (var index = 0; index < globalLength; index++) {
  27269. var currentPool = new Array();
  27270. var current = globalPool[index];
  27271. // Checks
  27272. if (!_this._canBeMerged(current)) {
  27273. continue;
  27274. }
  27275. currentPool.push(current);
  27276. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27277. var otherMesh = globalPool[subIndex];
  27278. if (!_this._canBeMerged(otherMesh)) {
  27279. continue;
  27280. }
  27281. if (otherMesh.material !== current.material) {
  27282. continue;
  27283. }
  27284. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27285. continue;
  27286. }
  27287. currentPool.push(otherMesh);
  27288. globalLength--;
  27289. globalPool.splice(subIndex, 1);
  27290. subIndex--;
  27291. }
  27292. if (currentPool.length < 2) {
  27293. continue;
  27294. }
  27295. // Merge meshes
  27296. BABYLON.Mesh.MergeMeshes(currentPool);
  27297. }
  27298. return true;
  27299. };
  27300. }
  27301. return MergeMeshesOptimization;
  27302. })(SceneOptimization);
  27303. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27304. // Options
  27305. var SceneOptimizerOptions = (function () {
  27306. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27307. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27308. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27309. this.targetFrameRate = targetFrameRate;
  27310. this.trackerDuration = trackerDuration;
  27311. this.optimizations = new Array();
  27312. }
  27313. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27314. var result = new SceneOptimizerOptions(targetFrameRate);
  27315. var priority = 0;
  27316. result.optimizations.push(new MergeMeshesOptimization(priority));
  27317. result.optimizations.push(new ShadowsOptimization(priority));
  27318. result.optimizations.push(new LensFlaresOptimization(priority));
  27319. // Next priority
  27320. priority++;
  27321. result.optimizations.push(new PostProcessesOptimization(priority));
  27322. result.optimizations.push(new ParticlesOptimization(priority));
  27323. // Next priority
  27324. priority++;
  27325. result.optimizations.push(new TextureOptimization(priority, 1024));
  27326. return result;
  27327. };
  27328. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27329. var result = new SceneOptimizerOptions(targetFrameRate);
  27330. var priority = 0;
  27331. result.optimizations.push(new MergeMeshesOptimization(priority));
  27332. result.optimizations.push(new ShadowsOptimization(priority));
  27333. result.optimizations.push(new LensFlaresOptimization(priority));
  27334. // Next priority
  27335. priority++;
  27336. result.optimizations.push(new PostProcessesOptimization(priority));
  27337. result.optimizations.push(new ParticlesOptimization(priority));
  27338. // Next priority
  27339. priority++;
  27340. result.optimizations.push(new TextureOptimization(priority, 512));
  27341. // Next priority
  27342. priority++;
  27343. result.optimizations.push(new RenderTargetsOptimization(priority));
  27344. // Next priority
  27345. priority++;
  27346. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27347. return result;
  27348. };
  27349. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27350. var result = new SceneOptimizerOptions(targetFrameRate);
  27351. var priority = 0;
  27352. result.optimizations.push(new MergeMeshesOptimization(priority));
  27353. result.optimizations.push(new ShadowsOptimization(priority));
  27354. result.optimizations.push(new LensFlaresOptimization(priority));
  27355. // Next priority
  27356. priority++;
  27357. result.optimizations.push(new PostProcessesOptimization(priority));
  27358. result.optimizations.push(new ParticlesOptimization(priority));
  27359. // Next priority
  27360. priority++;
  27361. result.optimizations.push(new TextureOptimization(priority, 256));
  27362. // Next priority
  27363. priority++;
  27364. result.optimizations.push(new RenderTargetsOptimization(priority));
  27365. // Next priority
  27366. priority++;
  27367. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27368. return result;
  27369. };
  27370. return SceneOptimizerOptions;
  27371. })();
  27372. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27373. // Scene optimizer tool
  27374. var SceneOptimizer = (function () {
  27375. function SceneOptimizer() {
  27376. }
  27377. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27378. // TODO: add an epsilon
  27379. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27380. if (onSuccess) {
  27381. onSuccess();
  27382. }
  27383. return;
  27384. }
  27385. // Apply current level of optimizations
  27386. var allDone = true;
  27387. var noOptimizationApplied = true;
  27388. for (var index = 0; index < options.optimizations.length; index++) {
  27389. var optimization = options.optimizations[index];
  27390. if (optimization.priority === currentPriorityLevel) {
  27391. noOptimizationApplied = false;
  27392. allDone = allDone && optimization.apply(scene);
  27393. }
  27394. }
  27395. // If no optimization was applied, this is a failure :(
  27396. if (noOptimizationApplied) {
  27397. if (onFailure) {
  27398. onFailure();
  27399. }
  27400. return;
  27401. }
  27402. // If all optimizations were done, move to next level
  27403. if (allDone) {
  27404. currentPriorityLevel++;
  27405. }
  27406. // Let's the system running for a specific amount of time before checking FPS
  27407. scene.executeWhenReady(function () {
  27408. setTimeout(function () {
  27409. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27410. }, options.trackerDuration);
  27411. });
  27412. };
  27413. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27414. if (!options) {
  27415. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27416. }
  27417. // Let's the system running for a specific amount of time before checking FPS
  27418. scene.executeWhenReady(function () {
  27419. setTimeout(function () {
  27420. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27421. }, options.trackerDuration);
  27422. });
  27423. };
  27424. return SceneOptimizer;
  27425. })();
  27426. BABYLON.SceneOptimizer = SceneOptimizer;
  27427. })(BABYLON || (BABYLON = {}));
  27428. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27429. (function (BABYLON) {
  27430. var Internals;
  27431. (function (Internals) {
  27432. var MeshLODLevel = (function () {
  27433. function MeshLODLevel(distance, mesh) {
  27434. this.distance = distance;
  27435. this.mesh = mesh;
  27436. }
  27437. return MeshLODLevel;
  27438. })();
  27439. Internals.MeshLODLevel = MeshLODLevel;
  27440. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27441. })(BABYLON || (BABYLON = {}));
  27442. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27443. (function (BABYLON) {
  27444. var AudioEngine = (function () {
  27445. function AudioEngine() {
  27446. this._audioContext = null;
  27447. this._audioContextInitialized = false;
  27448. this.canUseWebAudio = false;
  27449. this.WarnedWebAudioUnsupported = false;
  27450. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  27451. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  27452. this.canUseWebAudio = true;
  27453. }
  27454. }
  27455. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  27456. get: function () {
  27457. if (!this._audioContextInitialized) {
  27458. this._initializeAudioContext();
  27459. }
  27460. return this._audioContext;
  27461. },
  27462. enumerable: true,
  27463. configurable: true
  27464. });
  27465. AudioEngine.prototype._initializeAudioContext = function () {
  27466. try {
  27467. if (this.canUseWebAudio) {
  27468. this._audioContext = new AudioContext();
  27469. // create a global volume gain node
  27470. this.masterGain = this._audioContext.createGain();
  27471. this.masterGain.gain.value = 1;
  27472. this.masterGain.connect(this._audioContext.destination);
  27473. this._audioContextInitialized = true;
  27474. }
  27475. }
  27476. catch (e) {
  27477. this.canUseWebAudio = false;
  27478. BABYLON.Tools.Error("Web Audio: " + e.message);
  27479. }
  27480. };
  27481. AudioEngine.prototype.dispose = function () {
  27482. if (this.canUseWebAudio && this._audioContextInitialized) {
  27483. if (this._connectedAnalyser) {
  27484. this._connectedAnalyser.stopDebugCanvas();
  27485. this._connectedAnalyser.dispose();
  27486. this.masterGain.disconnect();
  27487. this.masterGain.connect(this._audioContext.destination);
  27488. this._connectedAnalyser = null;
  27489. }
  27490. this.masterGain.gain.value = 1;
  27491. }
  27492. this.WarnedWebAudioUnsupported = false;
  27493. };
  27494. AudioEngine.prototype.getGlobalVolume = function () {
  27495. if (this.canUseWebAudio && this._audioContextInitialized) {
  27496. return this.masterGain.gain.value;
  27497. }
  27498. else {
  27499. return -1;
  27500. }
  27501. };
  27502. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27503. if (this.canUseWebAudio && this._audioContextInitialized) {
  27504. this.masterGain.gain.value = newVolume;
  27505. }
  27506. };
  27507. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27508. if (this._connectedAnalyser) {
  27509. this._connectedAnalyser.stopDebugCanvas();
  27510. }
  27511. if (this.canUseWebAudio && this._audioContextInitialized) {
  27512. this._connectedAnalyser = analyser;
  27513. this.masterGain.disconnect();
  27514. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  27515. }
  27516. };
  27517. return AudioEngine;
  27518. })();
  27519. BABYLON.AudioEngine = AudioEngine;
  27520. })(BABYLON || (BABYLON = {}));
  27521. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27522. (function (BABYLON) {
  27523. var Sound = (function () {
  27524. /**
  27525. * Create a sound and attach it to a scene
  27526. * @param name Name of your sound
  27527. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27528. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27529. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27530. */
  27531. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27532. var _this = this;
  27533. this.autoplay = false;
  27534. this.loop = false;
  27535. this.useCustomAttenuation = false;
  27536. this.spatialSound = false;
  27537. this.refDistance = 1;
  27538. this.rolloffFactor = 1;
  27539. this.maxDistance = 100;
  27540. this.distanceModel = "linear";
  27541. this._panningModel = "equalpower";
  27542. this._playbackRate = 1;
  27543. this._startTime = 0;
  27544. this._startOffset = 0;
  27545. this._position = BABYLON.Vector3.Zero();
  27546. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27547. this._volume = 1;
  27548. this._isLoaded = false;
  27549. this._isReadyToPlay = false;
  27550. this.isPlaying = false;
  27551. this.isPaused = false;
  27552. this._isDirectional = false;
  27553. // Used if you'd like to create a directional sound.
  27554. // If not set, the sound will be omnidirectional
  27555. this._coneInnerAngle = 360;
  27556. this._coneOuterAngle = 360;
  27557. this._coneOuterGain = 0;
  27558. this.name = name;
  27559. this._scene = scene;
  27560. this._readyToPlayCallback = readyToPlayCallback;
  27561. // Default custom attenuation function is a linear attenuation
  27562. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27563. if (currentDistance < maxDistance) {
  27564. return currentVolume * (1 - currentDistance / maxDistance);
  27565. }
  27566. else {
  27567. return 0;
  27568. }
  27569. };
  27570. if (options) {
  27571. this.autoplay = options.autoplay || false;
  27572. this.loop = options.loop || false;
  27573. // if volume === 0, we need another way to check this option
  27574. if (options.volume !== undefined) {
  27575. this._volume = options.volume;
  27576. }
  27577. this.spatialSound = options.spatialSound || false;
  27578. this.maxDistance = options.maxDistance || 100;
  27579. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27580. this.rolloffFactor = options.rolloffFactor || 1;
  27581. this.refDistance = options.refDistance || 1;
  27582. this.distanceModel = options.distanceModel || "linear";
  27583. this._playbackRate = options.playbackRate || 1;
  27584. }
  27585. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27586. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27587. this._soundGain.gain.value = this._volume;
  27588. this._inputAudioNode = this._soundGain;
  27589. this._ouputAudioNode = this._soundGain;
  27590. if (this.spatialSound) {
  27591. this._createSpatialParameters();
  27592. }
  27593. this._scene.mainSoundTrack.AddSound(this);
  27594. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27595. if (urlOrArrayBuffer) {
  27596. // If it's an URL
  27597. if (typeof (urlOrArrayBuffer) === "string") {
  27598. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27599. _this._soundLoaded(data);
  27600. }, null, null, true);
  27601. }
  27602. else {
  27603. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27604. this._soundLoaded(urlOrArrayBuffer);
  27605. }
  27606. else {
  27607. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27608. }
  27609. }
  27610. }
  27611. }
  27612. else {
  27613. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27614. this._scene.mainSoundTrack.AddSound(this);
  27615. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27616. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27617. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27618. }
  27619. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27620. if (this._readyToPlayCallback) {
  27621. window.setTimeout(function () {
  27622. _this._readyToPlayCallback();
  27623. }, 1000);
  27624. }
  27625. }
  27626. }
  27627. Sound.prototype.dispose = function () {
  27628. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27629. if (this.isPlaying) {
  27630. this.stop();
  27631. }
  27632. this._isReadyToPlay = false;
  27633. if (this.soundTrackId === -1) {
  27634. this._scene.mainSoundTrack.RemoveSound(this);
  27635. }
  27636. else {
  27637. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27638. }
  27639. if (this._soundGain) {
  27640. this._soundGain.disconnect();
  27641. this._soundGain = null;
  27642. }
  27643. if (this._soundPanner) {
  27644. this._soundPanner.disconnect();
  27645. this._soundPanner = null;
  27646. }
  27647. if (this._soundSource) {
  27648. this._soundSource.disconnect();
  27649. this._soundSource = null;
  27650. }
  27651. this._audioBuffer = null;
  27652. if (this._connectedMesh) {
  27653. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27654. this._connectedMesh = null;
  27655. }
  27656. }
  27657. };
  27658. Sound.prototype._soundLoaded = function (audioData) {
  27659. var _this = this;
  27660. this._isLoaded = true;
  27661. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27662. _this._audioBuffer = buffer;
  27663. _this._isReadyToPlay = true;
  27664. if (_this.autoplay) {
  27665. _this.play();
  27666. }
  27667. if (_this._readyToPlayCallback) {
  27668. _this._readyToPlayCallback();
  27669. }
  27670. }, function (error) {
  27671. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27672. });
  27673. };
  27674. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27675. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27676. this._audioBuffer = audioBuffer;
  27677. this._isReadyToPlay = true;
  27678. }
  27679. };
  27680. Sound.prototype.updateOptions = function (options) {
  27681. if (options) {
  27682. this.loop = options.loop || this.loop;
  27683. this.maxDistance = options.maxDistance || this.maxDistance;
  27684. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27685. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27686. this.refDistance = options.refDistance || this.refDistance;
  27687. this.distanceModel = options.distanceModel || this.distanceModel;
  27688. this._playbackRate = options.playbackRate || this._playbackRate;
  27689. }
  27690. };
  27691. Sound.prototype._createSpatialParameters = function () {
  27692. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27693. if (this._scene.headphone) {
  27694. this._panningModel = "HRTF";
  27695. }
  27696. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27697. if (this.useCustomAttenuation) {
  27698. // Tricks to disable in a way embedded Web Audio attenuation
  27699. this._soundPanner.distanceModel = "linear";
  27700. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27701. this._soundPanner.refDistance = 1;
  27702. this._soundPanner.rolloffFactor = 1;
  27703. this._soundPanner.panningModel = this._panningModel;
  27704. }
  27705. else {
  27706. this._soundPanner.distanceModel = this.distanceModel;
  27707. this._soundPanner.maxDistance = this.maxDistance;
  27708. this._soundPanner.refDistance = this.refDistance;
  27709. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27710. this._soundPanner.panningModel = this._panningModel;
  27711. }
  27712. this._soundPanner.connect(this._ouputAudioNode);
  27713. this._inputAudioNode = this._soundPanner;
  27714. }
  27715. };
  27716. Sound.prototype.switchPanningModelToHRTF = function () {
  27717. this._panningModel = "HRTF";
  27718. this._switchPanningModel();
  27719. };
  27720. Sound.prototype.switchPanningModelToEqualPower = function () {
  27721. this._panningModel = "equalpower";
  27722. this._switchPanningModel();
  27723. };
  27724. Sound.prototype._switchPanningModel = function () {
  27725. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27726. this._soundPanner.panningModel = this._panningModel;
  27727. }
  27728. };
  27729. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27730. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27731. this._ouputAudioNode.disconnect();
  27732. this._ouputAudioNode.connect(soundTrackAudioNode);
  27733. }
  27734. };
  27735. /**
  27736. * Transform this sound into a directional source
  27737. * @param coneInnerAngle Size of the inner cone in degree
  27738. * @param coneOuterAngle Size of the outer cone in degree
  27739. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27740. */
  27741. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27742. if (coneOuterAngle < coneInnerAngle) {
  27743. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27744. return;
  27745. }
  27746. this._coneInnerAngle = coneInnerAngle;
  27747. this._coneOuterAngle = coneOuterAngle;
  27748. this._coneOuterGain = coneOuterGain;
  27749. this._isDirectional = true;
  27750. if (this.isPlaying && this.loop) {
  27751. this.stop();
  27752. this.play();
  27753. }
  27754. };
  27755. Sound.prototype.setPosition = function (newPosition) {
  27756. this._position = newPosition;
  27757. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27758. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27759. }
  27760. };
  27761. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27762. this._localDirection = newLocalDirection;
  27763. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27764. this._updateDirection();
  27765. }
  27766. };
  27767. Sound.prototype._updateDirection = function () {
  27768. var mat = this._connectedMesh.getWorldMatrix();
  27769. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27770. direction.normalize();
  27771. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27772. };
  27773. Sound.prototype.updateDistanceFromListener = function () {
  27774. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27775. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27776. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27777. }
  27778. };
  27779. Sound.prototype.setAttenuationFunction = function (callback) {
  27780. this._customAttenuationFunction = callback;
  27781. };
  27782. /**
  27783. * Play the sound
  27784. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27785. */
  27786. Sound.prototype.play = function (time) {
  27787. var _this = this;
  27788. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27789. try {
  27790. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27791. if (!this._soundSource) {
  27792. if (this.spatialSound) {
  27793. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27794. if (this._isDirectional) {
  27795. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27796. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27797. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27798. if (this._connectedMesh) {
  27799. this._updateDirection();
  27800. }
  27801. else {
  27802. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27803. }
  27804. }
  27805. }
  27806. }
  27807. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27808. this._soundSource.buffer = this._audioBuffer;
  27809. this._soundSource.connect(this._inputAudioNode);
  27810. this._soundSource.loop = this.loop;
  27811. this._soundSource.playbackRate.value = this._playbackRate;
  27812. this._startTime = startTime;
  27813. this._soundSource.onended = function () {
  27814. _this._onended();
  27815. };
  27816. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27817. this.isPlaying = true;
  27818. this.isPaused = false;
  27819. }
  27820. catch (ex) {
  27821. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27822. }
  27823. }
  27824. };
  27825. Sound.prototype._onended = function () {
  27826. this.isPlaying = false;
  27827. if (this.onended) {
  27828. this.onended();
  27829. }
  27830. };
  27831. /**
  27832. * Stop the sound
  27833. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27834. */
  27835. Sound.prototype.stop = function (time) {
  27836. if (this.isPlaying) {
  27837. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27838. this._soundSource.stop(stopTime);
  27839. this.isPlaying = false;
  27840. }
  27841. };
  27842. Sound.prototype.pause = function () {
  27843. if (this.isPlaying) {
  27844. this.stop(0);
  27845. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27846. this.isPaused = true;
  27847. }
  27848. };
  27849. Sound.prototype.setVolume = function (newVolume, time) {
  27850. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27851. if (time) {
  27852. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27853. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27854. }
  27855. else {
  27856. this._soundGain.gain.value = newVolume;
  27857. }
  27858. }
  27859. this._volume = newVolume;
  27860. };
  27861. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27862. this._playbackRate = newPlaybackRate;
  27863. if (this.isPlaying) {
  27864. this._soundSource.playbackRate.value = this._playbackRate;
  27865. }
  27866. };
  27867. Sound.prototype.getVolume = function () {
  27868. return this._volume;
  27869. };
  27870. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27871. var _this = this;
  27872. this._connectedMesh = meshToConnectTo;
  27873. if (!this.spatialSound) {
  27874. this._createSpatialParameters();
  27875. this.spatialSound = true;
  27876. if (this.isPlaying && this.loop) {
  27877. this.stop();
  27878. this.play();
  27879. }
  27880. }
  27881. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27882. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27883. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27884. };
  27885. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27886. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27887. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27888. this._updateDirection();
  27889. }
  27890. };
  27891. return Sound;
  27892. })();
  27893. BABYLON.Sound = Sound;
  27894. })(BABYLON || (BABYLON = {}));
  27895. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27896. (function (BABYLON) {
  27897. var SoundTrack = (function () {
  27898. function SoundTrack(scene, options) {
  27899. this.id = -1;
  27900. this._isMainTrack = false;
  27901. this._scene = scene;
  27902. this._audioEngine = BABYLON.Engine.audioEngine;
  27903. this.soundCollection = new Array();
  27904. if (this._audioEngine.canUseWebAudio) {
  27905. this._trackGain = this._audioEngine.audioContext.createGain();
  27906. this._trackGain.connect(this._audioEngine.masterGain);
  27907. if (options) {
  27908. if (options.volume) {
  27909. this._trackGain.gain.value = options.volume;
  27910. }
  27911. if (options.mainTrack) {
  27912. this._isMainTrack = options.mainTrack;
  27913. }
  27914. }
  27915. }
  27916. if (!this._isMainTrack) {
  27917. this._scene.soundTracks.push(this);
  27918. this.id = this._scene.soundTracks.length - 1;
  27919. }
  27920. }
  27921. SoundTrack.prototype.dispose = function () {
  27922. if (this._audioEngine.canUseWebAudio) {
  27923. if (this._connectedAnalyser) {
  27924. this._connectedAnalyser.stopDebugCanvas();
  27925. }
  27926. while (this.soundCollection.length) {
  27927. this.soundCollection[0].dispose();
  27928. }
  27929. this._trackGain.disconnect();
  27930. this._trackGain = null;
  27931. }
  27932. };
  27933. SoundTrack.prototype.AddSound = function (sound) {
  27934. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27935. sound.connectToSoundTrackAudioNode(this._trackGain);
  27936. }
  27937. if (sound.soundTrackId) {
  27938. if (sound.soundTrackId === -1) {
  27939. this._scene.mainSoundTrack.RemoveSound(sound);
  27940. }
  27941. else {
  27942. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27943. }
  27944. }
  27945. this.soundCollection.push(sound);
  27946. sound.soundTrackId = this.id;
  27947. };
  27948. SoundTrack.prototype.RemoveSound = function (sound) {
  27949. var index = this.soundCollection.indexOf(sound);
  27950. if (index !== -1) {
  27951. this.soundCollection.splice(index, 1);
  27952. }
  27953. };
  27954. SoundTrack.prototype.setVolume = function (newVolume) {
  27955. if (this._audioEngine.canUseWebAudio) {
  27956. this._trackGain.gain.value = newVolume;
  27957. }
  27958. };
  27959. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27960. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27961. for (var i = 0; i < this.soundCollection.length; i++) {
  27962. this.soundCollection[i].switchPanningModelToHRTF();
  27963. }
  27964. }
  27965. };
  27966. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27967. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27968. for (var i = 0; i < this.soundCollection.length; i++) {
  27969. this.soundCollection[i].switchPanningModelToEqualPower();
  27970. }
  27971. }
  27972. };
  27973. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27974. if (this._connectedAnalyser) {
  27975. this._connectedAnalyser.stopDebugCanvas();
  27976. }
  27977. this._connectedAnalyser = analyser;
  27978. if (this._audioEngine.canUseWebAudio) {
  27979. this._trackGain.disconnect();
  27980. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27981. }
  27982. };
  27983. return SoundTrack;
  27984. })();
  27985. BABYLON.SoundTrack = SoundTrack;
  27986. })(BABYLON || (BABYLON = {}));
  27987. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27988. (function (BABYLON) {
  27989. var DebugLayer = (function () {
  27990. function DebugLayer(scene) {
  27991. var _this = this;
  27992. this._transformationMatrix = BABYLON.Matrix.Identity();
  27993. this._enabled = false;
  27994. this._labelsEnabled = false;
  27995. this._displayStatistics = true;
  27996. this._displayTree = false;
  27997. this._displayLogs = false;
  27998. this._identityMatrix = BABYLON.Matrix.Identity();
  27999. this.axisRatio = 0.02;
  28000. this.accentColor = "orange";
  28001. this._scene = scene;
  28002. this._syncPositions = function () {
  28003. var engine = _this._scene.getEngine();
  28004. var canvasRect = engine.getRenderingCanvasClientRect();
  28005. if (_this._showUI) {
  28006. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28007. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28008. _this._statsDiv.style.width = "400px";
  28009. _this._statsDiv.style.height = "auto";
  28010. _this._statsSubsetDiv.style.maxHeight = "240px";
  28011. _this._optionsDiv.style.left = "0px";
  28012. _this._optionsDiv.style.top = "10px";
  28013. _this._optionsDiv.style.width = "200px";
  28014. _this._optionsDiv.style.height = "auto";
  28015. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28016. _this._logDiv.style.left = "0px";
  28017. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28018. _this._logDiv.style.width = "600px";
  28019. _this._logDiv.style.height = "160px";
  28020. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28021. _this._treeDiv.style.top = "10px";
  28022. _this._treeDiv.style.width = "300px";
  28023. _this._treeDiv.style.height = "auto";
  28024. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28025. }
  28026. _this._globalDiv.style.left = canvasRect.left + "px";
  28027. _this._globalDiv.style.top = canvasRect.top + "px";
  28028. _this._drawingCanvas.style.left = "0px";
  28029. _this._drawingCanvas.style.top = "0px";
  28030. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28031. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28032. var devicePixelRatio = window.devicePixelRatio || 1;
  28033. var context = _this._drawingContext;
  28034. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  28035. _this._ratio = devicePixelRatio / backingStoreRatio;
  28036. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28037. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28038. };
  28039. this._onCanvasClick = function (evt) {
  28040. _this._clickPosition = {
  28041. x: evt.clientX * _this._ratio,
  28042. y: evt.clientY * _this._ratio
  28043. };
  28044. };
  28045. this._syncUI = function () {
  28046. if (_this._showUI) {
  28047. if (_this._displayStatistics) {
  28048. _this._displayStats();
  28049. _this._statsDiv.style.display = "";
  28050. }
  28051. else {
  28052. _this._statsDiv.style.display = "none";
  28053. }
  28054. if (_this._displayLogs) {
  28055. _this._logDiv.style.display = "";
  28056. }
  28057. else {
  28058. _this._logDiv.style.display = "none";
  28059. }
  28060. if (_this._displayTree) {
  28061. _this._treeDiv.style.display = "";
  28062. if (_this._needToRefreshMeshesTree) {
  28063. _this._needToRefreshMeshesTree = false;
  28064. _this._refreshMeshesTreeContent();
  28065. }
  28066. }
  28067. else {
  28068. _this._treeDiv.style.display = "none";
  28069. }
  28070. }
  28071. };
  28072. this._syncData = function () {
  28073. if (_this._labelsEnabled || !_this._showUI) {
  28074. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28075. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28076. var engine = _this._scene.getEngine();
  28077. var viewport = _this._camera.viewport;
  28078. var globalViewport = viewport.toGlobal(engine);
  28079. // Meshes
  28080. var meshes = _this._camera.getActiveMeshes();
  28081. for (var index = 0; index < meshes.length; index++) {
  28082. var mesh = meshes.data[index];
  28083. var position = mesh.getBoundingInfo().boundingSphere.center;
  28084. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28085. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28086. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28087. }
  28088. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28089. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  28090. mesh.renderOverlay = !mesh.renderOverlay;
  28091. }, function () {
  28092. return mesh.renderOverlay ? 'red' : 'black';
  28093. });
  28094. }
  28095. }
  28096. // Cameras
  28097. var cameras = _this._scene.cameras;
  28098. for (index = 0; index < cameras.length; index++) {
  28099. var camera = cameras[index];
  28100. if (camera === _this._camera) {
  28101. continue;
  28102. }
  28103. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28104. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28105. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28106. _this._camera.detachControl(engine.getRenderingCanvas());
  28107. _this._camera = camera;
  28108. _this._camera.attachControl(engine.getRenderingCanvas());
  28109. }, function () {
  28110. return "purple";
  28111. });
  28112. }
  28113. }
  28114. // Lights
  28115. var lights = _this._scene.lights;
  28116. for (index = 0; index < lights.length; index++) {
  28117. var light = lights[index];
  28118. if (light.position) {
  28119. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28120. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28121. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28122. light.setEnabled(!light.isEnabled());
  28123. }, function () {
  28124. return light.isEnabled() ? "orange" : "gray";
  28125. });
  28126. }
  28127. }
  28128. }
  28129. }
  28130. _this._clickPosition = undefined;
  28131. };
  28132. }
  28133. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28134. while (this._treeSubsetDiv.hasChildNodes()) {
  28135. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28136. }
  28137. // Add meshes
  28138. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28139. sortedArray.sort(function (a, b) {
  28140. if (a.name === b.name) {
  28141. return 0;
  28142. }
  28143. return (a.name > b.name) ? 1 : -1;
  28144. });
  28145. for (var index = 0; index < sortedArray.length; index++) {
  28146. var mesh = sortedArray[index];
  28147. if (!mesh.isEnabled()) {
  28148. continue;
  28149. }
  28150. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28151. m.isVisible = element.checked;
  28152. }, mesh);
  28153. }
  28154. };
  28155. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28156. this._drawingContext.beginPath();
  28157. this._drawingContext.moveTo(zero.x, zero.y);
  28158. this._drawingContext.lineTo(unit.x, unit.y);
  28159. this._drawingContext.strokeStyle = color;
  28160. this._drawingContext.lineWidth = 4;
  28161. this._drawingContext.stroke();
  28162. this._drawingContext.font = "normal 14px Segoe UI";
  28163. this._drawingContext.fillStyle = color;
  28164. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28165. };
  28166. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28167. var position = mesh.getBoundingInfo().boundingSphere.center;
  28168. var worldMatrix = mesh.getWorldMatrix();
  28169. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28170. var unit = (unprojectedVector.subtract(position)).length();
  28171. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28172. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28173. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28174. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28175. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28176. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28177. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28178. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28179. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28180. };
  28181. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28182. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28183. this._drawingContext.font = "normal 12px Segoe UI";
  28184. var textMetrics = this._drawingContext.measureText(text);
  28185. var centerX = projectedPosition.x - textMetrics.width / 2;
  28186. var centerY = projectedPosition.y;
  28187. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28188. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28189. onClick();
  28190. }
  28191. this._drawingContext.beginPath();
  28192. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28193. this._drawingContext.fillStyle = getFillStyle();
  28194. this._drawingContext.globalAlpha = 0.5;
  28195. this._drawingContext.fill();
  28196. this._drawingContext.globalAlpha = 1.0;
  28197. this._drawingContext.strokeStyle = '#FFFFFF';
  28198. this._drawingContext.lineWidth = 1;
  28199. this._drawingContext.stroke();
  28200. this._drawingContext.fillStyle = "#FFFFFF";
  28201. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28202. this._drawingContext.beginPath();
  28203. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28204. this._drawingContext.fill();
  28205. }
  28206. };
  28207. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28208. if (!this._clickPosition) {
  28209. return false;
  28210. }
  28211. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28212. return false;
  28213. }
  28214. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28215. return false;
  28216. }
  28217. return true;
  28218. };
  28219. DebugLayer.prototype.isVisible = function () {
  28220. return this._enabled;
  28221. };
  28222. DebugLayer.prototype.hide = function () {
  28223. if (!this._enabled) {
  28224. return;
  28225. }
  28226. this._enabled = false;
  28227. var engine = this._scene.getEngine();
  28228. this._scene.unregisterBeforeRender(this._syncData);
  28229. this._scene.unregisterAfterRender(this._syncUI);
  28230. document.body.removeChild(this._globalDiv);
  28231. window.removeEventListener("resize", this._syncPositions);
  28232. this._scene.forceShowBoundingBoxes = false;
  28233. this._scene.forceWireframe = false;
  28234. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28235. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28236. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28237. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28238. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28239. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28240. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28241. this._scene.shadowsEnabled = true;
  28242. this._scene.particlesEnabled = true;
  28243. this._scene.postProcessesEnabled = true;
  28244. this._scene.collisionsEnabled = true;
  28245. this._scene.lightsEnabled = true;
  28246. this._scene.texturesEnabled = true;
  28247. this._scene.lensFlaresEnabled = true;
  28248. this._scene.proceduralTexturesEnabled = true;
  28249. this._scene.renderTargetsEnabled = true;
  28250. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28251. };
  28252. DebugLayer.prototype.show = function (showUI, camera) {
  28253. if (showUI === void 0) { showUI = true; }
  28254. if (camera === void 0) { camera = null; }
  28255. if (this._enabled) {
  28256. return;
  28257. }
  28258. this._enabled = true;
  28259. if (camera) {
  28260. this._camera = camera;
  28261. }
  28262. else {
  28263. this._camera = this._scene.activeCamera;
  28264. }
  28265. this._showUI = showUI;
  28266. var engine = this._scene.getEngine();
  28267. this._globalDiv = document.createElement("div");
  28268. document.body.appendChild(this._globalDiv);
  28269. this._generateDOMelements();
  28270. window.addEventListener("resize", this._syncPositions);
  28271. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28272. this._syncPositions();
  28273. this._scene.registerBeforeRender(this._syncData);
  28274. this._scene.registerAfterRender(this._syncUI);
  28275. };
  28276. DebugLayer.prototype._clearLabels = function () {
  28277. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28278. for (var index = 0; index < this._scene.meshes.length; index++) {
  28279. var mesh = this._scene.meshes[index];
  28280. mesh.renderOverlay = false;
  28281. }
  28282. };
  28283. DebugLayer.prototype._generateheader = function (root, text) {
  28284. var header = document.createElement("div");
  28285. header.innerHTML = text + "&nbsp;";
  28286. header.style.textAlign = "right";
  28287. header.style.width = "100%";
  28288. header.style.color = "white";
  28289. header.style.backgroundColor = "Black";
  28290. header.style.padding = "5px 5px 4px 0px";
  28291. header.style.marginLeft = "-5px";
  28292. header.style.fontWeight = "bold";
  28293. root.appendChild(header);
  28294. };
  28295. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28296. var label = document.createElement("label");
  28297. label.innerHTML = title;
  28298. label.style.color = color;
  28299. root.appendChild(label);
  28300. root.appendChild(document.createElement("br"));
  28301. };
  28302. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28303. if (tag === void 0) { tag = null; }
  28304. var label = document.createElement("label");
  28305. var boundingBoxesCheckbox = document.createElement("input");
  28306. boundingBoxesCheckbox.type = "checkbox";
  28307. boundingBoxesCheckbox.checked = initialState;
  28308. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28309. task(evt.target, tag);
  28310. });
  28311. label.appendChild(boundingBoxesCheckbox);
  28312. var container = document.createElement("span");
  28313. var leftPart = document.createElement("span");
  28314. var rightPart = document.createElement("span");
  28315. rightPart.style.cssFloat = "right";
  28316. leftPart.innerHTML = leftTitle;
  28317. rightPart.innerHTML = rightTitle;
  28318. rightPart.style.fontSize = "12px";
  28319. rightPart.style.maxWidth = "200px";
  28320. container.appendChild(leftPart);
  28321. container.appendChild(rightPart);
  28322. label.appendChild(container);
  28323. root.appendChild(label);
  28324. root.appendChild(document.createElement("br"));
  28325. };
  28326. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28327. if (tag === void 0) { tag = null; }
  28328. var label = document.createElement("label");
  28329. var checkBox = document.createElement("input");
  28330. checkBox.type = "checkbox";
  28331. checkBox.checked = initialState;
  28332. checkBox.addEventListener("change", function (evt) {
  28333. task(evt.target, tag);
  28334. });
  28335. label.appendChild(checkBox);
  28336. label.appendChild(document.createTextNode(title));
  28337. root.appendChild(label);
  28338. root.appendChild(document.createElement("br"));
  28339. };
  28340. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28341. if (tag === void 0) { tag = null; }
  28342. var button = document.createElement("button");
  28343. button.innerHTML = title;
  28344. button.style.height = "24px";
  28345. button.style.color = "#444444";
  28346. button.style.border = "1px solid white";
  28347. button.className = "debugLayerButton";
  28348. button.addEventListener("click", function (evt) {
  28349. task(evt.target, tag);
  28350. });
  28351. root.appendChild(button);
  28352. root.appendChild(document.createElement("br"));
  28353. };
  28354. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28355. if (tag === void 0) { tag = null; }
  28356. var label = document.createElement("label");
  28357. var boundingBoxesRadio = document.createElement("input");
  28358. boundingBoxesRadio.type = "radio";
  28359. boundingBoxesRadio.name = name;
  28360. boundingBoxesRadio.checked = initialState;
  28361. boundingBoxesRadio.addEventListener("change", function (evt) {
  28362. task(evt.target, tag);
  28363. });
  28364. label.appendChild(boundingBoxesRadio);
  28365. label.appendChild(document.createTextNode(title));
  28366. root.appendChild(label);
  28367. root.appendChild(document.createElement("br"));
  28368. };
  28369. DebugLayer.prototype._generateDOMelements = function () {
  28370. var _this = this;
  28371. this._globalDiv.id = "DebugLayer";
  28372. this._globalDiv.style.position = "absolute";
  28373. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28374. this._globalDiv.style.fontSize = "14px";
  28375. this._globalDiv.style.color = "white";
  28376. // Drawing canvas
  28377. this._drawingCanvas = document.createElement("canvas");
  28378. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28379. this._drawingCanvas.style.position = "absolute";
  28380. this._drawingCanvas.style.pointerEvents = "none";
  28381. this._drawingContext = this._drawingCanvas.getContext("2d");
  28382. this._globalDiv.appendChild(this._drawingCanvas);
  28383. if (this._showUI) {
  28384. var background = "rgba(128, 128, 128, 0.4)";
  28385. var border = "rgb(180, 180, 180) solid 1px";
  28386. // Stats
  28387. this._statsDiv = document.createElement("div");
  28388. this._statsDiv.id = "DebugLayerStats";
  28389. this._statsDiv.style.border = border;
  28390. this._statsDiv.style.position = "absolute";
  28391. this._statsDiv.style.background = background;
  28392. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28393. this._generateheader(this._statsDiv, "STATISTICS");
  28394. this._statsSubsetDiv = document.createElement("div");
  28395. this._statsSubsetDiv.style.paddingTop = "5px";
  28396. this._statsSubsetDiv.style.paddingBottom = "5px";
  28397. this._statsSubsetDiv.style.overflowY = "auto";
  28398. this._statsDiv.appendChild(this._statsSubsetDiv);
  28399. // Tree
  28400. this._treeDiv = document.createElement("div");
  28401. this._treeDiv.id = "DebugLayerTree";
  28402. this._treeDiv.style.border = border;
  28403. this._treeDiv.style.position = "absolute";
  28404. this._treeDiv.style.background = background;
  28405. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28406. this._treeDiv.style.display = "none";
  28407. this._generateheader(this._treeDiv, "MESHES TREE");
  28408. this._treeSubsetDiv = document.createElement("div");
  28409. this._treeSubsetDiv.style.paddingTop = "5px";
  28410. this._treeSubsetDiv.style.paddingRight = "5px";
  28411. this._treeSubsetDiv.style.overflowY = "auto";
  28412. this._treeSubsetDiv.style.maxHeight = "300px";
  28413. this._treeDiv.appendChild(this._treeSubsetDiv);
  28414. this._needToRefreshMeshesTree = true;
  28415. // Logs
  28416. this._logDiv = document.createElement("div");
  28417. this._logDiv.style.border = border;
  28418. this._logDiv.id = "DebugLayerLogs";
  28419. this._logDiv.style.position = "absolute";
  28420. this._logDiv.style.background = background;
  28421. this._logDiv.style.padding = "0px 0px 0px 5px";
  28422. this._logDiv.style.display = "none";
  28423. this._generateheader(this._logDiv, "LOGS");
  28424. this._logSubsetDiv = document.createElement("div");
  28425. this._logSubsetDiv.style.height = "127px";
  28426. this._logSubsetDiv.style.paddingTop = "5px";
  28427. this._logSubsetDiv.style.overflowY = "auto";
  28428. this._logSubsetDiv.style.fontSize = "12px";
  28429. this._logSubsetDiv.style.fontFamily = "consolas";
  28430. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28431. this._logDiv.appendChild(this._logSubsetDiv);
  28432. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28433. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28434. };
  28435. // Options
  28436. this._optionsDiv = document.createElement("div");
  28437. this._optionsDiv.id = "DebugLayerOptions";
  28438. this._optionsDiv.style.border = border;
  28439. this._optionsDiv.style.position = "absolute";
  28440. this._optionsDiv.style.background = background;
  28441. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28442. this._optionsDiv.style.overflowY = "auto";
  28443. this._generateheader(this._optionsDiv, "OPTIONS");
  28444. this._optionsSubsetDiv = document.createElement("div");
  28445. this._optionsSubsetDiv.style.paddingTop = "5px";
  28446. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28447. this._optionsSubsetDiv.style.overflowY = "auto";
  28448. this._optionsSubsetDiv.style.maxHeight = "200px";
  28449. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28450. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28451. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28452. _this._displayStatistics = element.checked;
  28453. });
  28454. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28455. _this._displayLogs = element.checked;
  28456. });
  28457. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28458. _this._displayTree = element.checked;
  28459. _this._needToRefreshMeshesTree = true;
  28460. });
  28461. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28462. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28463. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28464. _this._scene.forceShowBoundingBoxes = element.checked;
  28465. });
  28466. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28467. _this._labelsEnabled = element.checked;
  28468. if (!_this._labelsEnabled) {
  28469. _this._clearLabels();
  28470. }
  28471. });
  28472. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28473. if (element.checked) {
  28474. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28475. }
  28476. else {
  28477. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28478. }
  28479. });
  28480. ;
  28481. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28482. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28483. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28484. if (element.checked) {
  28485. _this._scene.forceWireframe = false;
  28486. _this._scene.forcePointsCloud = false;
  28487. }
  28488. });
  28489. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28490. if (element.checked) {
  28491. _this._scene.forceWireframe = true;
  28492. _this._scene.forcePointsCloud = false;
  28493. }
  28494. });
  28495. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28496. if (element.checked) {
  28497. _this._scene.forceWireframe = false;
  28498. _this._scene.forcePointsCloud = true;
  28499. }
  28500. });
  28501. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28502. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28503. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28504. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28505. });
  28506. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28507. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28508. });
  28509. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28510. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28511. });
  28512. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28513. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28514. });
  28515. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28516. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28517. });
  28518. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28519. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28520. });
  28521. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28522. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28523. });
  28524. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28525. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28526. });
  28527. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28528. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28529. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28530. _this._scene.animationsEnabled = element.checked;
  28531. });
  28532. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28533. _this._scene.collisionsEnabled = element.checked;
  28534. });
  28535. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28536. _this._scene.fogEnabled = element.checked;
  28537. });
  28538. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28539. _this._scene.lensFlaresEnabled = element.checked;
  28540. });
  28541. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28542. _this._scene.lightsEnabled = element.checked;
  28543. });
  28544. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28545. _this._scene.particlesEnabled = element.checked;
  28546. });
  28547. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28548. _this._scene.postProcessesEnabled = element.checked;
  28549. });
  28550. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28551. _this._scene.proceduralTexturesEnabled = element.checked;
  28552. });
  28553. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28554. _this._scene.renderTargetsEnabled = element.checked;
  28555. });
  28556. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28557. _this._scene.shadowsEnabled = element.checked;
  28558. });
  28559. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28560. _this._scene.skeletonsEnabled = element.checked;
  28561. });
  28562. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28563. _this._scene.spritesEnabled = element.checked;
  28564. });
  28565. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28566. _this._scene.texturesEnabled = element.checked;
  28567. });
  28568. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28569. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28570. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28571. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28572. if (element.checked) {
  28573. _this._scene.headphone = true;
  28574. }
  28575. });
  28576. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28577. if (element.checked) {
  28578. _this._scene.headphone = false;
  28579. }
  28580. });
  28581. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28582. _this._scene.audioEnabled = !element.checked;
  28583. });
  28584. }
  28585. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28586. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28587. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28588. _this._scene.dumpNextRenderTargets = true;
  28589. });
  28590. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28591. this._globalDiv.appendChild(this._statsDiv);
  28592. this._globalDiv.appendChild(this._logDiv);
  28593. this._globalDiv.appendChild(this._optionsDiv);
  28594. this._globalDiv.appendChild(this._treeDiv);
  28595. }
  28596. };
  28597. DebugLayer.prototype._displayStats = function () {
  28598. var scene = this._scene;
  28599. var engine = scene.getEngine();
  28600. var glInfo = engine.getGlInfo();
  28601. 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>";
  28602. if (this.customStatsFunction) {
  28603. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28604. }
  28605. };
  28606. return DebugLayer;
  28607. })();
  28608. BABYLON.DebugLayer = DebugLayer;
  28609. })(BABYLON || (BABYLON = {}));
  28610. //# sourceMappingURL=babylon.debugLayer.js.map
  28611. var BABYLON;
  28612. (function (BABYLON) {
  28613. var RawTexture = (function (_super) {
  28614. __extends(RawTexture, _super);
  28615. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28616. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28617. if (invertY === void 0) { invertY = false; }
  28618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28619. _super.call(this, null, scene, !generateMipMaps, invertY);
  28620. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28621. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28622. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28623. }
  28624. // Statics
  28625. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28626. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28627. if (invertY === void 0) { invertY = false; }
  28628. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28629. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28630. };
  28631. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28632. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28633. if (invertY === void 0) { invertY = false; }
  28634. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28635. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28636. };
  28637. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28638. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28639. if (invertY === void 0) { invertY = false; }
  28640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28641. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28642. };
  28643. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28644. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28645. if (invertY === void 0) { invertY = false; }
  28646. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28647. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28648. };
  28649. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28650. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28651. if (invertY === void 0) { invertY = false; }
  28652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28653. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28654. };
  28655. return RawTexture;
  28656. })(BABYLON.Texture);
  28657. BABYLON.RawTexture = RawTexture;
  28658. })(BABYLON || (BABYLON = {}));
  28659. //# sourceMappingURL=babylon.rawTexture.js.map
  28660. var BABYLON;
  28661. (function (BABYLON) {
  28662. var IndexedVector2 = (function (_super) {
  28663. __extends(IndexedVector2, _super);
  28664. function IndexedVector2(original, index) {
  28665. _super.call(this, original.x, original.y);
  28666. this.index = index;
  28667. }
  28668. return IndexedVector2;
  28669. })(BABYLON.Vector2);
  28670. var PolygonPoints = (function () {
  28671. function PolygonPoints() {
  28672. this.elements = new Array();
  28673. }
  28674. PolygonPoints.prototype.add = function (originalPoints) {
  28675. var _this = this;
  28676. var result = new Array();
  28677. originalPoints.forEach(function (point) {
  28678. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28679. var newPoint = new IndexedVector2(point, _this.elements.length);
  28680. result.push(newPoint);
  28681. _this.elements.push(newPoint);
  28682. }
  28683. });
  28684. return result;
  28685. };
  28686. PolygonPoints.prototype.computeBounds = function () {
  28687. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28688. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28689. this.elements.forEach(function (point) {
  28690. // x
  28691. if (point.x < lmin.x) {
  28692. lmin.x = point.x;
  28693. }
  28694. else if (point.x > lmax.x) {
  28695. lmax.x = point.x;
  28696. }
  28697. // y
  28698. if (point.y < lmin.y) {
  28699. lmin.y = point.y;
  28700. }
  28701. else if (point.y > lmax.y) {
  28702. lmax.y = point.y;
  28703. }
  28704. });
  28705. return {
  28706. min: lmin,
  28707. max: lmax,
  28708. width: lmax.x - lmin.x,
  28709. height: lmax.y - lmin.y
  28710. };
  28711. };
  28712. return PolygonPoints;
  28713. })();
  28714. var Polygon = (function () {
  28715. function Polygon() {
  28716. }
  28717. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28718. return [
  28719. new BABYLON.Vector2(xmin, ymin),
  28720. new BABYLON.Vector2(xmax, ymin),
  28721. new BABYLON.Vector2(xmax, ymax),
  28722. new BABYLON.Vector2(xmin, ymax)
  28723. ];
  28724. };
  28725. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28726. if (cx === void 0) { cx = 0; }
  28727. if (cy === void 0) { cy = 0; }
  28728. if (numberOfSides === void 0) { numberOfSides = 32; }
  28729. var result = new Array();
  28730. var angle = 0;
  28731. var increment = (Math.PI * 2) / numberOfSides;
  28732. for (var i = 0; i < numberOfSides; i++) {
  28733. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28734. angle -= increment;
  28735. }
  28736. return result;
  28737. };
  28738. Polygon.Parse = function (input) {
  28739. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28740. var i, result = [];
  28741. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28742. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28743. }
  28744. return result;
  28745. };
  28746. Polygon.StartingAt = function (x, y) {
  28747. return BABYLON.Path2.StartingAt(x, y);
  28748. };
  28749. return Polygon;
  28750. })();
  28751. BABYLON.Polygon = Polygon;
  28752. var PolygonMeshBuilder = (function () {
  28753. function PolygonMeshBuilder(name, contours, scene) {
  28754. this._points = new PolygonPoints();
  28755. if (!("poly2tri" in window)) {
  28756. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28757. }
  28758. this._name = name;
  28759. this._scene = scene;
  28760. var points;
  28761. if (contours instanceof BABYLON.Path2) {
  28762. points = contours.getPoints();
  28763. }
  28764. else {
  28765. points = contours;
  28766. }
  28767. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28768. }
  28769. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28770. this._swctx.addHole(this._points.add(hole));
  28771. return this;
  28772. };
  28773. PolygonMeshBuilder.prototype.build = function (updatable) {
  28774. if (updatable === void 0) { updatable = false; }
  28775. var result = new BABYLON.Mesh(this._name, this._scene);
  28776. var normals = [];
  28777. var positions = [];
  28778. var uvs = [];
  28779. var bounds = this._points.computeBounds();
  28780. this._points.elements.forEach(function (p) {
  28781. normals.push(0, 1.0, 0);
  28782. positions.push(p.x, 0, p.y);
  28783. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28784. });
  28785. var indices = [];
  28786. this._swctx.triangulate();
  28787. this._swctx.getTriangles().forEach(function (triangle) {
  28788. triangle.getPoints().forEach(function (point) {
  28789. indices.push(point.index);
  28790. });
  28791. });
  28792. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  28793. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  28794. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  28795. result.setIndices(indices);
  28796. return result;
  28797. };
  28798. return PolygonMeshBuilder;
  28799. })();
  28800. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28801. })(BABYLON || (BABYLON = {}));
  28802. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28803. (function (BABYLON) {
  28804. var SimplificationSettings = (function () {
  28805. function SimplificationSettings(quality, distance, optimizeMesh) {
  28806. this.quality = quality;
  28807. this.distance = distance;
  28808. this.optimizeMesh = optimizeMesh;
  28809. }
  28810. return SimplificationSettings;
  28811. })();
  28812. BABYLON.SimplificationSettings = SimplificationSettings;
  28813. var SimplificationQueue = (function () {
  28814. function SimplificationQueue() {
  28815. this.running = false;
  28816. this._simplificationArray = [];
  28817. }
  28818. SimplificationQueue.prototype.addTask = function (task) {
  28819. this._simplificationArray.push(task);
  28820. };
  28821. SimplificationQueue.prototype.executeNext = function () {
  28822. var task = this._simplificationArray.pop();
  28823. if (task) {
  28824. this.running = true;
  28825. this.runSimplification(task);
  28826. }
  28827. else {
  28828. this.running = false;
  28829. }
  28830. };
  28831. SimplificationQueue.prototype.runSimplification = function (task) {
  28832. var _this = this;
  28833. if (task.parallelProcessing) {
  28834. //parallel simplifier
  28835. task.settings.forEach(function (setting) {
  28836. var simplifier = _this.getSimplifier(task);
  28837. simplifier.simplify(setting, function (newMesh) {
  28838. task.mesh.addLODLevel(setting.distance, newMesh);
  28839. newMesh.isVisible = true;
  28840. //check if it is the last
  28841. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28842. //all done, run the success callback.
  28843. task.successCallback();
  28844. }
  28845. _this.executeNext();
  28846. });
  28847. });
  28848. }
  28849. else {
  28850. //single simplifier.
  28851. var simplifier = this.getSimplifier(task);
  28852. var runDecimation = function (setting, callback) {
  28853. simplifier.simplify(setting, function (newMesh) {
  28854. task.mesh.addLODLevel(setting.distance, newMesh);
  28855. newMesh.isVisible = true;
  28856. //run the next quality level
  28857. callback();
  28858. });
  28859. };
  28860. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28861. runDecimation(task.settings[loop.index], function () {
  28862. loop.executeNext();
  28863. });
  28864. }, function () {
  28865. //execution ended, run the success callback.
  28866. if (task.successCallback) {
  28867. task.successCallback();
  28868. }
  28869. _this.executeNext();
  28870. });
  28871. }
  28872. };
  28873. SimplificationQueue.prototype.getSimplifier = function (task) {
  28874. switch (task.simplificationType) {
  28875. case 0 /* QUADRATIC */:
  28876. default:
  28877. return new QuadraticErrorSimplification(task.mesh);
  28878. }
  28879. };
  28880. return SimplificationQueue;
  28881. })();
  28882. BABYLON.SimplificationQueue = SimplificationQueue;
  28883. /**
  28884. * The implemented types of simplification.
  28885. * At the moment only Quadratic Error Decimation is implemented.
  28886. */
  28887. (function (SimplificationType) {
  28888. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28889. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28890. var SimplificationType = BABYLON.SimplificationType;
  28891. var DecimationTriangle = (function () {
  28892. function DecimationTriangle(vertices) {
  28893. this.vertices = vertices;
  28894. this.error = new Array(4);
  28895. this.deleted = false;
  28896. this.isDirty = false;
  28897. this.deletePending = false;
  28898. this.borderFactor = 0;
  28899. }
  28900. return DecimationTriangle;
  28901. })();
  28902. BABYLON.DecimationTriangle = DecimationTriangle;
  28903. var DecimationVertex = (function () {
  28904. function DecimationVertex(position, id) {
  28905. this.position = position;
  28906. this.id = id;
  28907. this.isBorder = true;
  28908. this.q = new QuadraticMatrix();
  28909. this.triangleCount = 0;
  28910. this.triangleStart = 0;
  28911. this.originalOffsets = [];
  28912. }
  28913. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28914. this.position.copyFrom(newPosition);
  28915. };
  28916. return DecimationVertex;
  28917. })();
  28918. BABYLON.DecimationVertex = DecimationVertex;
  28919. var QuadraticMatrix = (function () {
  28920. function QuadraticMatrix(data) {
  28921. this.data = new Array(10);
  28922. for (var i = 0; i < 10; ++i) {
  28923. if (data && data[i]) {
  28924. this.data[i] = data[i];
  28925. }
  28926. else {
  28927. this.data[i] = 0;
  28928. }
  28929. }
  28930. }
  28931. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28932. 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];
  28933. return det;
  28934. };
  28935. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28936. for (var i = 0; i < 10; ++i) {
  28937. this.data[i] += matrix.data[i];
  28938. }
  28939. };
  28940. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28941. for (var i = 0; i < 10; ++i) {
  28942. this.data[i] += data[i];
  28943. }
  28944. };
  28945. QuadraticMatrix.prototype.add = function (matrix) {
  28946. var m = new QuadraticMatrix();
  28947. for (var i = 0; i < 10; ++i) {
  28948. m.data[i] = this.data[i] + matrix.data[i];
  28949. }
  28950. return m;
  28951. };
  28952. QuadraticMatrix.FromData = function (a, b, c, d) {
  28953. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28954. };
  28955. //returning an array to avoid garbage collection
  28956. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28957. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28958. };
  28959. return QuadraticMatrix;
  28960. })();
  28961. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28962. var Reference = (function () {
  28963. function Reference(vertexId, triangleId) {
  28964. this.vertexId = vertexId;
  28965. this.triangleId = triangleId;
  28966. }
  28967. return Reference;
  28968. })();
  28969. BABYLON.Reference = Reference;
  28970. /**
  28971. * An implementation of the Quadratic Error simplification algorithm.
  28972. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28973. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28974. * @author RaananW
  28975. */
  28976. var QuadraticErrorSimplification = (function () {
  28977. function QuadraticErrorSimplification(_mesh) {
  28978. this._mesh = _mesh;
  28979. this.initialized = false;
  28980. this.syncIterations = 5000;
  28981. this.aggressiveness = 7;
  28982. this.decimationIterations = 100;
  28983. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28984. }
  28985. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28986. var _this = this;
  28987. this.initDecimatedMesh();
  28988. //iterating through the submeshes array, one after the other.
  28989. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28990. _this.initWithMesh(loop.index, function () {
  28991. _this.runDecimation(settings, loop.index, function () {
  28992. loop.executeNext();
  28993. });
  28994. }, settings.optimizeMesh);
  28995. }, function () {
  28996. setTimeout(function () {
  28997. successCallback(_this._reconstructedMesh);
  28998. }, 0);
  28999. });
  29000. };
  29001. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29002. var _this = this;
  29003. var gCount = 0;
  29004. triangle.vertices.forEach(function (vertex) {
  29005. var count = 0;
  29006. var vPos = vertex.position;
  29007. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29008. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29009. ++count;
  29010. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  29011. ++count;
  29012. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  29013. ++count;
  29014. if (count > 1) {
  29015. ++gCount;
  29016. }
  29017. ;
  29018. });
  29019. if (gCount > 1) {
  29020. console.log(triangle, gCount);
  29021. }
  29022. return gCount > 1;
  29023. };
  29024. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29025. var _this = this;
  29026. var targetCount = ~~(this.triangles.length * settings.quality);
  29027. var deletedTriangles = 0;
  29028. var triangleCount = this.triangles.length;
  29029. var iterationFunction = function (iteration, callback) {
  29030. setTimeout(function () {
  29031. if (iteration % 5 === 0) {
  29032. _this.updateMesh(iteration === 0);
  29033. }
  29034. for (var i = 0; i < _this.triangles.length; ++i) {
  29035. _this.triangles[i].isDirty = false;
  29036. }
  29037. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29038. var trianglesIterator = function (i) {
  29039. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29040. var t = _this.triangles[tIdx];
  29041. if (!t)
  29042. return;
  29043. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29044. return;
  29045. }
  29046. for (var j = 0; j < 3; ++j) {
  29047. if (t.error[j] < threshold) {
  29048. var deleted0 = [];
  29049. var deleted1 = [];
  29050. var v0 = t.vertices[j];
  29051. var v1 = t.vertices[(j + 1) % 3];
  29052. if (v0.isBorder !== v1.isBorder)
  29053. continue;
  29054. var p = BABYLON.Vector3.Zero();
  29055. var n = BABYLON.Vector3.Zero();
  29056. var uv = BABYLON.Vector2.Zero();
  29057. var color = new BABYLON.Color4(0, 0, 0, 1);
  29058. _this.calculateError(v0, v1, p, n, uv, color);
  29059. var delTr = [];
  29060. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29061. continue;
  29062. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29063. continue;
  29064. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29065. continue;
  29066. var uniqueArray = [];
  29067. delTr.forEach(function (deletedT) {
  29068. if (uniqueArray.indexOf(deletedT) === -1) {
  29069. deletedT.deletePending = true;
  29070. uniqueArray.push(deletedT);
  29071. }
  29072. });
  29073. if (uniqueArray.length % 2 != 0) {
  29074. continue;
  29075. }
  29076. v0.q = v1.q.add(v0.q);
  29077. v0.updatePosition(p);
  29078. var tStart = _this.references.length;
  29079. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29080. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29081. var tCount = _this.references.length - tStart;
  29082. if (tCount <= v0.triangleCount) {
  29083. if (tCount) {
  29084. for (var c = 0; c < tCount; c++) {
  29085. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29086. }
  29087. }
  29088. }
  29089. else {
  29090. v0.triangleStart = tStart;
  29091. }
  29092. v0.triangleCount = tCount;
  29093. break;
  29094. }
  29095. }
  29096. };
  29097. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  29098. return (triangleCount - deletedTriangles <= targetCount);
  29099. });
  29100. }, 0);
  29101. };
  29102. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29103. if (triangleCount - deletedTriangles <= targetCount)
  29104. loop.breakLoop();
  29105. else {
  29106. iterationFunction(loop.index, function () {
  29107. loop.executeNext();
  29108. });
  29109. }
  29110. }, function () {
  29111. setTimeout(function () {
  29112. //reconstruct this part of the mesh
  29113. _this.reconstructMesh(submeshIndex);
  29114. successCallback();
  29115. }, 0);
  29116. });
  29117. };
  29118. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29119. var _this = this;
  29120. this.vertices = [];
  29121. this.triangles = [];
  29122. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29123. var indices = this._mesh.getIndices();
  29124. var submesh = this._mesh.subMeshes[submeshIndex];
  29125. var findInVertices = function (positionToSearch) {
  29126. if (optimizeMesh) {
  29127. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29128. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29129. return _this.vertices[ii];
  29130. }
  29131. }
  29132. }
  29133. return null;
  29134. };
  29135. var vertexReferences = [];
  29136. var vertexInit = function (i) {
  29137. var offset = i + submesh.verticesStart;
  29138. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29139. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29140. vertex.originalOffsets.push(offset);
  29141. if (vertex.id == _this.vertices.length) {
  29142. _this.vertices.push(vertex);
  29143. }
  29144. vertexReferences.push(vertex.id);
  29145. };
  29146. //var totalVertices = mesh.getTotalVertices();
  29147. var totalVertices = submesh.verticesCount;
  29148. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29149. var indicesInit = function (i) {
  29150. var offset = (submesh.indexStart / 3) + i;
  29151. var pos = (offset * 3);
  29152. var i0 = indices[pos + 0];
  29153. var i1 = indices[pos + 1];
  29154. var i2 = indices[pos + 2];
  29155. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29156. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29157. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29158. var triangle = new DecimationTriangle([v0, v1, v2]);
  29159. triangle.originalOffset = pos;
  29160. _this.triangles.push(triangle);
  29161. };
  29162. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29163. _this.init(callback);
  29164. });
  29165. });
  29166. };
  29167. QuadraticErrorSimplification.prototype.init = function (callback) {
  29168. var _this = this;
  29169. var triangleInit1 = function (i) {
  29170. var t = _this.triangles[i];
  29171. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29172. for (var j = 0; j < 3; j++) {
  29173. 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))));
  29174. }
  29175. };
  29176. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29177. var triangleInit2 = function (i) {
  29178. var t = _this.triangles[i];
  29179. for (var j = 0; j < 3; ++j) {
  29180. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29181. }
  29182. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29183. };
  29184. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29185. _this.initialized = true;
  29186. callback();
  29187. });
  29188. });
  29189. };
  29190. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29191. var newTriangles = [];
  29192. var i;
  29193. for (i = 0; i < this.vertices.length; ++i) {
  29194. this.vertices[i].triangleCount = 0;
  29195. }
  29196. var t;
  29197. var j;
  29198. for (i = 0; i < this.triangles.length; ++i) {
  29199. if (!this.triangles[i].deleted) {
  29200. t = this.triangles[i];
  29201. for (j = 0; j < 3; ++j) {
  29202. t.vertices[j].triangleCount = 1;
  29203. }
  29204. newTriangles.push(t);
  29205. }
  29206. }
  29207. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  29208. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  29209. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  29210. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  29211. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29212. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29213. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29214. var vertexCount = 0;
  29215. for (i = 0; i < this.vertices.length; ++i) {
  29216. var vertex = this.vertices[i];
  29217. vertex.id = vertexCount;
  29218. if (vertex.triangleCount) {
  29219. vertex.originalOffsets.forEach(function (originalOffset) {
  29220. newPositionData.push(vertex.position.x);
  29221. newPositionData.push(vertex.position.y);
  29222. newPositionData.push(vertex.position.z);
  29223. newNormalData.push(normalData[originalOffset * 3]);
  29224. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29225. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29226. if (uvs && uvs.length) {
  29227. newUVsData.push(uvs[(originalOffset * 2)]);
  29228. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29229. }
  29230. else if (colorsData && colorsData.length) {
  29231. newColorsData.push(colorsData[(originalOffset * 4)]);
  29232. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29233. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29234. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29235. }
  29236. ++vertexCount;
  29237. });
  29238. }
  29239. }
  29240. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29241. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29242. var submeshesArray = this._reconstructedMesh.subMeshes;
  29243. this._reconstructedMesh.subMeshes = [];
  29244. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29245. var originalIndices = this._mesh.getIndices();
  29246. for (i = 0; i < newTriangles.length; ++i) {
  29247. var t = newTriangles[i];
  29248. //now get the new referencing point for each vertex
  29249. [0, 1, 2].forEach(function (idx) {
  29250. var id = originalIndices[t.originalOffset + idx];
  29251. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29252. if (offset < 0)
  29253. offset = 0;
  29254. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29255. });
  29256. }
  29257. //overwriting the old vertex buffers and indices.
  29258. this._reconstructedMesh.setIndices(newIndicesArray);
  29259. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29260. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29261. if (newUVsData.length > 0)
  29262. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29263. if (newColorsData.length > 0)
  29264. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29265. //create submesh
  29266. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29267. if (submeshIndex > 0) {
  29268. this._reconstructedMesh.subMeshes = [];
  29269. submeshesArray.forEach(function (submesh) {
  29270. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29271. });
  29272. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29273. }
  29274. };
  29275. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29276. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29277. this._reconstructedMesh.material = this._mesh.material;
  29278. this._reconstructedMesh.parent = this._mesh.parent;
  29279. this._reconstructedMesh.isVisible = false;
  29280. };
  29281. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29282. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29283. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29284. if (t.deleted)
  29285. continue;
  29286. var s = this.references[vertex1.triangleStart + i].vertexId;
  29287. var v1 = t.vertices[(s + 1) % 3];
  29288. var v2 = t.vertices[(s + 2) % 3];
  29289. if ((v1 === vertex2 || v2 === vertex2)) {
  29290. deletedArray[i] = true;
  29291. delTr.push(t);
  29292. continue;
  29293. }
  29294. var d1 = v1.position.subtract(point);
  29295. d1 = d1.normalize();
  29296. var d2 = v2.position.subtract(point);
  29297. d2 = d2.normalize();
  29298. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29299. return true;
  29300. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29301. deletedArray[i] = false;
  29302. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29303. return true;
  29304. }
  29305. return false;
  29306. };
  29307. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29308. var newDeleted = deletedTriangles;
  29309. for (var i = 0; i < vertex.triangleCount; ++i) {
  29310. var ref = this.references[vertex.triangleStart + i];
  29311. var t = this.triangles[ref.triangleId];
  29312. if (t.deleted)
  29313. continue;
  29314. if (deletedArray[i] && t.deletePending) {
  29315. t.deleted = true;
  29316. newDeleted++;
  29317. continue;
  29318. }
  29319. t.vertices[ref.vertexId] = origVertex;
  29320. t.isDirty = true;
  29321. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29322. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29323. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29324. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29325. this.references.push(ref);
  29326. }
  29327. return newDeleted;
  29328. };
  29329. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29330. for (var i = 0; i < this.vertices.length; ++i) {
  29331. var vCount = [];
  29332. var vId = [];
  29333. var v = this.vertices[i];
  29334. var j;
  29335. for (j = 0; j < v.triangleCount; ++j) {
  29336. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29337. for (var ii = 0; ii < 3; ii++) {
  29338. var ofs = 0;
  29339. var vv = triangle.vertices[ii];
  29340. while (ofs < vCount.length) {
  29341. if (vId[ofs] === vv.id)
  29342. break;
  29343. ++ofs;
  29344. }
  29345. if (ofs === vCount.length) {
  29346. vCount.push(1);
  29347. vId.push(vv.id);
  29348. }
  29349. else {
  29350. vCount[ofs]++;
  29351. }
  29352. }
  29353. }
  29354. for (j = 0; j < vCount.length; ++j) {
  29355. if (vCount[j] === 1) {
  29356. this.vertices[vId[j]].isBorder = true;
  29357. }
  29358. else {
  29359. this.vertices[vId[j]].isBorder = false;
  29360. }
  29361. }
  29362. }
  29363. };
  29364. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29365. if (identifyBorders === void 0) { identifyBorders = false; }
  29366. var i;
  29367. if (!identifyBorders) {
  29368. var newTrianglesVector = [];
  29369. for (i = 0; i < this.triangles.length; ++i) {
  29370. if (!this.triangles[i].deleted) {
  29371. newTrianglesVector.push(this.triangles[i]);
  29372. }
  29373. }
  29374. this.triangles = newTrianglesVector;
  29375. }
  29376. for (i = 0; i < this.vertices.length; ++i) {
  29377. this.vertices[i].triangleCount = 0;
  29378. this.vertices[i].triangleStart = 0;
  29379. }
  29380. var t;
  29381. var j;
  29382. var v;
  29383. for (i = 0; i < this.triangles.length; ++i) {
  29384. t = this.triangles[i];
  29385. for (j = 0; j < 3; ++j) {
  29386. v = t.vertices[j];
  29387. v.triangleCount++;
  29388. }
  29389. }
  29390. var tStart = 0;
  29391. for (i = 0; i < this.vertices.length; ++i) {
  29392. this.vertices[i].triangleStart = tStart;
  29393. tStart += this.vertices[i].triangleCount;
  29394. this.vertices[i].triangleCount = 0;
  29395. }
  29396. var newReferences = new Array(this.triangles.length * 3);
  29397. for (i = 0; i < this.triangles.length; ++i) {
  29398. t = this.triangles[i];
  29399. for (j = 0; j < 3; ++j) {
  29400. v = t.vertices[j];
  29401. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29402. v.triangleCount++;
  29403. }
  29404. }
  29405. this.references = newReferences;
  29406. if (identifyBorders) {
  29407. this.identifyBorder();
  29408. }
  29409. };
  29410. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29411. var x = point.x;
  29412. var y = point.y;
  29413. var z = point.z;
  29414. 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];
  29415. };
  29416. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29417. var q = vertex1.q.add(vertex2.q);
  29418. var border = vertex1.isBorder && vertex2.isBorder;
  29419. var error = 0;
  29420. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29421. if (qDet !== 0 && !border) {
  29422. if (!pointResult) {
  29423. pointResult = BABYLON.Vector3.Zero();
  29424. }
  29425. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29426. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29427. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29428. error = this.vertexError(q, pointResult);
  29429. }
  29430. else {
  29431. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29432. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29433. var error1 = this.vertexError(q, vertex1.position);
  29434. var error2 = this.vertexError(q, vertex2.position);
  29435. var error3 = this.vertexError(q, p3);
  29436. error = Math.min(error1, error2, error3);
  29437. if (error === error1) {
  29438. if (pointResult) {
  29439. pointResult.copyFrom(vertex1.position);
  29440. }
  29441. }
  29442. else if (error === error2) {
  29443. if (pointResult) {
  29444. pointResult.copyFrom(vertex2.position);
  29445. }
  29446. }
  29447. else {
  29448. if (pointResult) {
  29449. pointResult.copyFrom(p3);
  29450. }
  29451. }
  29452. }
  29453. return error;
  29454. };
  29455. return QuadraticErrorSimplification;
  29456. })();
  29457. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29458. })(BABYLON || (BABYLON = {}));
  29459. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29460. (function (BABYLON) {
  29461. var Analyser = (function () {
  29462. function Analyser(scene) {
  29463. this.SMOOTHING = 0.75;
  29464. this.FFT_SIZE = 512;
  29465. this.BARGRAPHAMPLITUDE = 256;
  29466. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29467. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29468. this._scene = scene;
  29469. this._audioEngine = BABYLON.Engine.audioEngine;
  29470. if (this._audioEngine.canUseWebAudio) {
  29471. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29472. this._webAudioAnalyser.minDecibels = -140;
  29473. this._webAudioAnalyser.maxDecibels = 0;
  29474. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29475. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29476. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29477. }
  29478. }
  29479. Analyser.prototype.getFrequencyBinCount = function () {
  29480. if (this._audioEngine.canUseWebAudio) {
  29481. return this._webAudioAnalyser.frequencyBinCount;
  29482. }
  29483. else {
  29484. return 0;
  29485. }
  29486. };
  29487. Analyser.prototype.getByteFrequencyData = function () {
  29488. if (this._audioEngine.canUseWebAudio) {
  29489. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29490. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29491. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29492. }
  29493. return this._byteFreqs;
  29494. };
  29495. Analyser.prototype.getByteTimeDomainData = function () {
  29496. if (this._audioEngine.canUseWebAudio) {
  29497. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29498. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29499. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29500. }
  29501. return this._byteTime;
  29502. };
  29503. Analyser.prototype.getFloatFrequencyData = function () {
  29504. if (this._audioEngine.canUseWebAudio) {
  29505. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29506. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29507. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29508. }
  29509. return this._floatFreqs;
  29510. };
  29511. Analyser.prototype.drawDebugCanvas = function () {
  29512. var _this = this;
  29513. if (this._audioEngine.canUseWebAudio) {
  29514. if (!this._debugCanvas) {
  29515. this._debugCanvas = document.createElement("canvas");
  29516. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29517. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29518. this._debugCanvas.style.position = "absolute";
  29519. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29520. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29521. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29522. document.body.appendChild(this._debugCanvas);
  29523. this._registerFunc = function () {
  29524. _this.drawDebugCanvas();
  29525. };
  29526. this._scene.registerBeforeRender(this._registerFunc);
  29527. }
  29528. if (this._registerFunc) {
  29529. var workingArray = this.getByteFrequencyData();
  29530. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29531. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29532. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29533. var value = workingArray[i];
  29534. var percent = value / this.BARGRAPHAMPLITUDE;
  29535. var height = this.DEBUGCANVASSIZE.height * percent;
  29536. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29537. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29538. var hue = i / this.getFrequencyBinCount() * 360;
  29539. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29540. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29541. }
  29542. }
  29543. }
  29544. };
  29545. Analyser.prototype.stopDebugCanvas = function () {
  29546. if (this._debugCanvas) {
  29547. this._scene.unregisterBeforeRender(this._registerFunc);
  29548. this._registerFunc = null;
  29549. document.body.removeChild(this._debugCanvas);
  29550. this._debugCanvas = null;
  29551. this._debugCanvasContext = null;
  29552. }
  29553. };
  29554. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29555. if (this._audioEngine.canUseWebAudio) {
  29556. inputAudioNode.connect(this._webAudioAnalyser);
  29557. this._webAudioAnalyser.connect(outputAudioNode);
  29558. }
  29559. };
  29560. Analyser.prototype.dispose = function () {
  29561. if (this._audioEngine.canUseWebAudio) {
  29562. this._webAudioAnalyser.disconnect();
  29563. }
  29564. };
  29565. return Analyser;
  29566. })();
  29567. BABYLON.Analyser = Analyser;
  29568. })(BABYLON || (BABYLON = {}));
  29569. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29570. (function (BABYLON) {
  29571. var DepthRenderer = (function () {
  29572. function DepthRenderer(scene, type) {
  29573. var _this = this;
  29574. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29575. this._viewMatrix = BABYLON.Matrix.Zero();
  29576. this._projectionMatrix = BABYLON.Matrix.Zero();
  29577. this._transformMatrix = BABYLON.Matrix.Zero();
  29578. this._worldViewProjection = BABYLON.Matrix.Zero();
  29579. this._scene = scene;
  29580. var engine = scene.getEngine();
  29581. // Render target
  29582. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29583. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29584. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29585. this._depthMap.refreshRate = 1;
  29586. this._depthMap.renderParticles = false;
  29587. this._depthMap.renderList = null;
  29588. // Custom render function
  29589. var renderSubMesh = function (subMesh) {
  29590. var mesh = subMesh.getRenderingMesh();
  29591. var scene = _this._scene;
  29592. var engine = scene.getEngine();
  29593. // Culling
  29594. engine.setState(subMesh.getMaterial().backFaceCulling);
  29595. // Managing instances
  29596. var batch = mesh._getInstancesRenderList(subMesh._id);
  29597. if (batch.mustReturn) {
  29598. return;
  29599. }
  29600. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29601. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29602. engine.enableEffect(_this._effect);
  29603. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29604. var material = subMesh.getMaterial();
  29605. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29606. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29607. // Alpha test
  29608. if (material && material.needAlphaTesting()) {
  29609. var alphaTexture = material.getAlphaTestTexture();
  29610. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29611. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29612. }
  29613. // Bones
  29614. if (mesh.useBones) {
  29615. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29616. }
  29617. // Draw
  29618. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29619. }
  29620. };
  29621. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29622. var index;
  29623. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29624. renderSubMesh(opaqueSubMeshes.data[index]);
  29625. }
  29626. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29627. renderSubMesh(alphaTestSubMeshes.data[index]);
  29628. }
  29629. };
  29630. }
  29631. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29632. var defines = [];
  29633. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29634. var mesh = subMesh.getMesh();
  29635. var scene = mesh.getScene();
  29636. var material = subMesh.getMaterial();
  29637. // Alpha test
  29638. if (material && material.needAlphaTesting()) {
  29639. defines.push("#define ALPHATEST");
  29640. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29641. attribs.push(BABYLON.VertexBuffer.UVKind);
  29642. defines.push("#define UV1");
  29643. }
  29644. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29645. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29646. defines.push("#define UV2");
  29647. }
  29648. }
  29649. // Bones
  29650. if (mesh.useBones) {
  29651. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29652. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29653. defines.push("#define BONES");
  29654. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29655. }
  29656. // Instances
  29657. if (useInstances) {
  29658. defines.push("#define INSTANCES");
  29659. attribs.push("world0");
  29660. attribs.push("world1");
  29661. attribs.push("world2");
  29662. attribs.push("world3");
  29663. }
  29664. // Get correct effect
  29665. var join = defines.join("\n");
  29666. if (this._cachedDefines !== join) {
  29667. this._cachedDefines = join;
  29668. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29669. }
  29670. return this._effect.isReady();
  29671. };
  29672. DepthRenderer.prototype.getDepthMap = function () {
  29673. return this._depthMap;
  29674. };
  29675. // Methods
  29676. DepthRenderer.prototype.dispose = function () {
  29677. this._depthMap.dispose();
  29678. };
  29679. return DepthRenderer;
  29680. })();
  29681. BABYLON.DepthRenderer = DepthRenderer;
  29682. })(BABYLON || (BABYLON = {}));
  29683. //# sourceMappingURL=babylon.depthRenderer.js.map
  29684. var BABYLON;
  29685. (function (BABYLON) {
  29686. var SSAORenderingPipeline = (function (_super) {
  29687. __extends(SSAORenderingPipeline, _super);
  29688. /**
  29689. * @constructor
  29690. * @param {string} name - The rendering pipeline name
  29691. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29692. * @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 }
  29693. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29694. */
  29695. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29696. var _this = this;
  29697. _super.call(this, scene.getEngine(), name);
  29698. // Members
  29699. /**
  29700. * The PassPostProcess id in the pipeline that contains the original scene color
  29701. * @type {string}
  29702. */
  29703. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29704. /**
  29705. * The SSAO PostProcess id in the pipeline
  29706. * @type {string}
  29707. */
  29708. this.SSAORenderEffect = "SSAORenderEffect";
  29709. /**
  29710. * The horizontal blur PostProcess id in the pipeline
  29711. * @type {string}
  29712. */
  29713. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29714. /**
  29715. * The vertical blur PostProcess id in the pipeline
  29716. * @type {string}
  29717. */
  29718. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29719. /**
  29720. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29721. * @type {string}
  29722. */
  29723. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29724. /**
  29725. * The output strength of the SSAO post-process. Default value is 1.0.
  29726. * @type {number}
  29727. */
  29728. this.totalStrength = 1.0;
  29729. /**
  29730. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29731. * @type {number}
  29732. */
  29733. this.radius = 0.0002;
  29734. /**
  29735. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29736. * Must not be equal to fallOff and superior to fallOff.
  29737. * Default value is 0.0075
  29738. * @type {number}
  29739. */
  29740. this.area = 0.0075;
  29741. /**
  29742. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29743. * Must not be equal to area and inferior to area.
  29744. * Default value is 0.0002
  29745. * @type {number}
  29746. */
  29747. this.fallOff = 0.0002;
  29748. this._firstUpdate = true;
  29749. this._scene = scene;
  29750. // Set up assets
  29751. this._createRandomTexture();
  29752. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29753. var ssaoRatio = ratio.ssaoRatio || ratio;
  29754. var combineRatio = ratio.combineRatio || ratio;
  29755. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29756. this._createSSAOPostProcess(ssaoRatio);
  29757. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29758. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29759. this._createSSAOCombinePostProcess(combineRatio);
  29760. // Set up pipeline
  29761. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29762. return _this._originalColorPostProcess;
  29763. }, true));
  29764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29765. return _this._ssaoPostProcess;
  29766. }, true));
  29767. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29768. return _this._blurHPostProcess;
  29769. }, true));
  29770. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29771. return _this._blurVPostProcess;
  29772. }, true));
  29773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29774. return _this._ssaoCombinePostProcess;
  29775. }, true));
  29776. // Finish
  29777. scene.postProcessRenderPipelineManager.addPipeline(this);
  29778. if (cameras)
  29779. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29780. }
  29781. // Public Methods
  29782. /**
  29783. * Returns the horizontal blur PostProcess
  29784. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29785. */
  29786. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29787. return this._blurHPostProcess;
  29788. };
  29789. /**
  29790. * Returns the vertical blur PostProcess
  29791. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29792. */
  29793. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29794. return this._blurVPostProcess;
  29795. };
  29796. /**
  29797. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29798. */
  29799. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29800. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29801. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29802. this._originalColorPostProcess = undefined;
  29803. this._ssaoPostProcess = undefined;
  29804. this._blurHPostProcess = undefined;
  29805. this._blurVPostProcess = undefined;
  29806. this._ssaoCombinePostProcess = undefined;
  29807. this._randomTexture.dispose();
  29808. if (disableDepthRender)
  29809. this._scene.disableDepthRenderer();
  29810. };
  29811. // Private Methods
  29812. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29813. var _this = this;
  29814. var sampleSphere = [
  29815. 0.5381,
  29816. 0.1856,
  29817. -0.4319,
  29818. 0.1379,
  29819. 0.2486,
  29820. 0.4430,
  29821. 0.3371,
  29822. 0.5679,
  29823. -0.0057,
  29824. -0.6999,
  29825. -0.0451,
  29826. -0.0019,
  29827. 0.0689,
  29828. -0.1598,
  29829. -0.8547,
  29830. 0.0560,
  29831. 0.0069,
  29832. -0.1843,
  29833. -0.0146,
  29834. 0.1402,
  29835. 0.0762,
  29836. 0.0100,
  29837. -0.1924,
  29838. -0.0344,
  29839. -0.3577,
  29840. -0.5301,
  29841. -0.4358,
  29842. -0.3169,
  29843. 0.1063,
  29844. 0.0158,
  29845. 0.0103,
  29846. -0.5869,
  29847. 0.0046,
  29848. -0.0897,
  29849. -0.4940,
  29850. 0.3287,
  29851. 0.7119,
  29852. -0.0154,
  29853. -0.0918,
  29854. -0.0533,
  29855. 0.0596,
  29856. -0.5411,
  29857. 0.0352,
  29858. -0.0631,
  29859. 0.5460,
  29860. -0.4776,
  29861. 0.2847,
  29862. -0.0271
  29863. ];
  29864. var samplesFactor = 1.0 / 16.0;
  29865. 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);
  29866. this._ssaoPostProcess.onApply = function (effect) {
  29867. if (_this._firstUpdate) {
  29868. effect.setArray3("sampleSphere", sampleSphere);
  29869. effect.setFloat("samplesFactor", samplesFactor);
  29870. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29871. _this._firstUpdate = false;
  29872. }
  29873. effect.setFloat("totalStrength", _this.totalStrength);
  29874. effect.setFloat("radius", _this.radius);
  29875. effect.setFloat("area", _this.area);
  29876. effect.setFloat("fallOff", _this.fallOff);
  29877. effect.setTexture("textureSampler", _this._depthTexture);
  29878. effect.setTexture("randomSampler", _this._randomTexture);
  29879. };
  29880. };
  29881. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29882. var _this = this;
  29883. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29884. this._ssaoCombinePostProcess.onApply = function (effect) {
  29885. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29886. };
  29887. };
  29888. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29889. var size = 512;
  29890. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29891. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29892. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29893. var context = this._randomTexture.getContext();
  29894. var rand = function (min, max) {
  29895. return Math.random() * (max - min) + min;
  29896. };
  29897. for (var x = 0; x < size; x++) {
  29898. for (var y = 0; y < size; y++) {
  29899. var randVector = BABYLON.Vector3.Zero();
  29900. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29901. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29902. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29903. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29904. context.fillRect(x, y, 1, 1);
  29905. }
  29906. }
  29907. this._randomTexture.update(false);
  29908. };
  29909. return SSAORenderingPipeline;
  29910. })(BABYLON.PostProcessRenderPipeline);
  29911. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29912. })(BABYLON || (BABYLON = {}));
  29913. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29914. var BABYLON;
  29915. (function (BABYLON) {
  29916. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29917. var VolumetricLightScatteringPostProcess = (function (_super) {
  29918. __extends(VolumetricLightScatteringPostProcess, _super);
  29919. /**
  29920. * @constructor
  29921. * @param {string} name - The post-process name
  29922. * @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)
  29923. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29924. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29925. * @param {number} samples - The post-process quality, default 100
  29926. * @param {number} samplingMode - The post-process filtering mode
  29927. * @param {BABYLON.Engine} engine - The babylon engine
  29928. * @param {boolean} reusable - If the post-process is reusable
  29929. */
  29930. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29931. var _this = this;
  29932. if (samples === void 0) { samples = 100; }
  29933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29934. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29935. this._screenCoordinates = BABYLON.Vector2.Zero();
  29936. /**
  29937. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29938. * @type {boolean}
  29939. */
  29940. this.useCustomMeshPosition = false;
  29941. /**
  29942. * If the post-process should inverse the light scattering direction
  29943. * @type {boolean}
  29944. */
  29945. this.invert = true;
  29946. /**
  29947. * Array containing the excluded meshes not rendered in the internal pass
  29948. */
  29949. this.excludedMeshes = new Array();
  29950. this.exposure = 0.3;
  29951. this.decay = 0.96815;
  29952. this.weight = 0.58767;
  29953. this.density = 0.926;
  29954. var scene = camera.getScene();
  29955. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29956. // Configure mesh
  29957. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29958. // Configure
  29959. this._createPass(scene, ratio.passRatio || ratio);
  29960. this.onApply = function (effect) {
  29961. _this._updateMeshScreenCoordinates(scene);
  29962. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29963. effect.setFloat("exposure", _this.exposure);
  29964. effect.setFloat("decay", _this.decay);
  29965. effect.setFloat("weight", _this.weight);
  29966. effect.setFloat("density", _this.density);
  29967. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29968. };
  29969. }
  29970. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29971. var mesh = subMesh.getMesh();
  29972. var defines = [];
  29973. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29974. var material = subMesh.getMaterial();
  29975. var needUV = false;
  29976. // Render this.mesh as default
  29977. if (mesh === this.mesh) {
  29978. defines.push("#define BASIC_RENDER");
  29979. defines.push("#define NEED_UV");
  29980. needUV = true;
  29981. }
  29982. // Alpha test
  29983. if (material) {
  29984. if (material.needAlphaTesting() || mesh === this.mesh)
  29985. defines.push("#define ALPHATEST");
  29986. if (material.opacityTexture !== undefined) {
  29987. defines.push("#define OPACITY");
  29988. if (material.opacityTexture.getAlphaFromRGB)
  29989. defines.push("#define OPACITYRGB");
  29990. if (!needUV)
  29991. defines.push("#define NEED_UV");
  29992. }
  29993. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29994. attribs.push(BABYLON.VertexBuffer.UVKind);
  29995. defines.push("#define UV1");
  29996. }
  29997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29998. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29999. defines.push("#define UV2");
  30000. }
  30001. }
  30002. // Bones
  30003. if (mesh.useBones) {
  30004. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30005. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30006. defines.push("#define BONES");
  30007. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30008. }
  30009. // Instances
  30010. if (useInstances) {
  30011. defines.push("#define INSTANCES");
  30012. attribs.push("world0");
  30013. attribs.push("world1");
  30014. attribs.push("world2");
  30015. attribs.push("world3");
  30016. }
  30017. // Get correct effect
  30018. var join = defines.join("\n");
  30019. if (this._cachedDefines !== join) {
  30020. this._cachedDefines = join;
  30021. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  30022. }
  30023. return this._volumetricLightScatteringPass.isReady();
  30024. };
  30025. /**
  30026. * Sets the new light position for light scattering effect
  30027. * @param {BABYLON.Vector3} The new custom light position
  30028. */
  30029. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  30030. this._customMeshPosition = position;
  30031. };
  30032. /**
  30033. * Returns the light position for light scattering effect
  30034. * @return {BABYLON.Vector3} The custom light position
  30035. */
  30036. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  30037. return this._customMeshPosition;
  30038. };
  30039. /**
  30040. * Disposes the internal assets and detaches the post-process from the camera
  30041. */
  30042. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  30043. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  30044. if (rttIndex !== -1) {
  30045. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  30046. }
  30047. this._volumetricLightScatteringRTT.dispose();
  30048. _super.prototype.dispose.call(this, camera);
  30049. };
  30050. /**
  30051. * Returns the render target texture used by the post-process
  30052. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  30053. */
  30054. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  30055. return this._volumetricLightScatteringRTT;
  30056. };
  30057. // Private methods
  30058. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  30059. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  30060. return true;
  30061. }
  30062. return false;
  30063. };
  30064. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  30065. var _this = this;
  30066. var engine = scene.getEngine();
  30067. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  30068. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30069. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30070. this._volumetricLightScatteringRTT.renderList = null;
  30071. this._volumetricLightScatteringRTT.renderParticles = false;
  30072. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  30073. // Custom render function for submeshes
  30074. var renderSubMesh = function (subMesh) {
  30075. var mesh = subMesh.getRenderingMesh();
  30076. if (_this._meshExcluded(mesh)) {
  30077. return;
  30078. }
  30079. var scene = mesh.getScene();
  30080. var engine = scene.getEngine();
  30081. // Culling
  30082. engine.setState(subMesh.getMaterial().backFaceCulling);
  30083. // Managing instances
  30084. var batch = mesh._getInstancesRenderList(subMesh._id);
  30085. if (batch.mustReturn) {
  30086. return;
  30087. }
  30088. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30089. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30090. engine.enableEffect(_this._volumetricLightScatteringPass);
  30091. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  30092. var material = subMesh.getMaterial();
  30093. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  30094. // Alpha test
  30095. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  30096. var alphaTexture = material.getAlphaTestTexture();
  30097. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  30098. if (alphaTexture) {
  30099. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30100. }
  30101. if (material.opacityTexture !== undefined) {
  30102. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  30103. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  30104. }
  30105. }
  30106. // Bones
  30107. if (mesh.useBones) {
  30108. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30109. }
  30110. // Draw
  30111. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  30112. }
  30113. };
  30114. // Render target texture callbacks
  30115. var savedSceneClearColor;
  30116. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  30117. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  30118. savedSceneClearColor = scene.clearColor;
  30119. scene.clearColor = sceneClearColor;
  30120. };
  30121. this._volumetricLightScatteringRTT.onAfterRender = function () {
  30122. scene.clearColor = savedSceneClearColor;
  30123. };
  30124. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  30125. var engine = scene.getEngine();
  30126. var index;
  30127. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30128. renderSubMesh(opaqueSubMeshes.data[index]);
  30129. }
  30130. engine.setAlphaTesting(true);
  30131. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30132. renderSubMesh(alphaTestSubMeshes.data[index]);
  30133. }
  30134. engine.setAlphaTesting(false);
  30135. if (transparentSubMeshes.length) {
  30136. for (index = 0; index < transparentSubMeshes.length; index++) {
  30137. var submesh = transparentSubMeshes.data[index];
  30138. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  30139. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  30140. }
  30141. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  30142. sortedArray.sort(function (a, b) {
  30143. // Alpha index first
  30144. if (a._alphaIndex > b._alphaIndex) {
  30145. return 1;
  30146. }
  30147. if (a._alphaIndex < b._alphaIndex) {
  30148. return -1;
  30149. }
  30150. // Then distance to camera
  30151. if (a._distanceToCamera < b._distanceToCamera) {
  30152. return 1;
  30153. }
  30154. if (a._distanceToCamera > b._distanceToCamera) {
  30155. return -1;
  30156. }
  30157. return 0;
  30158. });
  30159. // Render sub meshes
  30160. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  30161. for (index = 0; index < sortedArray.length; index++) {
  30162. renderSubMesh(sortedArray[index]);
  30163. }
  30164. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30165. }
  30166. };
  30167. };
  30168. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  30169. var transform = scene.getTransformMatrix();
  30170. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  30171. this._screenCoordinates.x = pos.x / this._viewPort.width;
  30172. this._screenCoordinates.y = pos.y / this._viewPort.height;
  30173. if (this.invert)
  30174. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  30175. };
  30176. // Static methods
  30177. /**
  30178. * Creates a default mesh for the Volumeric Light Scattering post-process
  30179. * @param {string} The mesh name
  30180. * @param {BABYLON.Scene} The scene where to create the mesh
  30181. * @return {BABYLON.Mesh} the default mesh
  30182. */
  30183. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  30184. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  30185. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  30186. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  30187. return mesh;
  30188. };
  30189. return VolumetricLightScatteringPostProcess;
  30190. })(BABYLON.PostProcess);
  30191. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  30192. })(BABYLON || (BABYLON = {}));
  30193. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  30194. var BABYLON;
  30195. (function (BABYLON) {
  30196. var LensRenderingPipeline = (function (_super) {
  30197. __extends(LensRenderingPipeline, _super);
  30198. /**
  30199. * @constructor
  30200. *
  30201. * Effect parameters are as follow:
  30202. * {
  30203. * chromatic_aberration: number; // from 0 to x (1 for realism)
  30204. * edge_blur: number; // from 0 to x (1 for realism)
  30205. * distortion: number; // from 0 to x (1 for realism)
  30206. * grain_amount: number; // from 0 to 1
  30207. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  30208. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  30209. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  30210. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  30211. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  30212. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  30213. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  30214. * }
  30215. * Note: if an effect parameter is unset, effect is disabled
  30216. *
  30217. * @param {string} name - The rendering pipeline name
  30218. * @param {object} parameters - An object containing all parameters (see above)
  30219. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30220. * @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)
  30221. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30222. */
  30223. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  30224. var _this = this;
  30225. if (ratio === void 0) { ratio = 1.0; }
  30226. _super.call(this, scene.getEngine(), name);
  30227. // Lens effects can be of the following:
  30228. // - chromatic aberration (slight shift of RGB colors)
  30229. // - blur on the edge of the lens
  30230. // - lens distortion
  30231. // - depth-of-field blur & highlights enhancing
  30232. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  30233. // - grain effect (noise or custom texture)
  30234. // Two additional texture samplers are needed:
  30235. // - depth map (for depth-of-field)
  30236. // - grain texture
  30237. /**
  30238. * The chromatic aberration PostProcess id in the pipeline
  30239. * @type {string}
  30240. */
  30241. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  30242. /**
  30243. * The highlights enhancing PostProcess id in the pipeline
  30244. * @type {string}
  30245. */
  30246. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  30247. /**
  30248. * The depth-of-field PostProcess id in the pipeline
  30249. * @type {string}
  30250. */
  30251. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  30252. this._scene = scene;
  30253. // Fetch texture samplers
  30254. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30255. if (parameters.grain_texture) {
  30256. this._grainTexture = parameters.grain_texture;
  30257. }
  30258. else {
  30259. this._createGrainTexture();
  30260. }
  30261. // save parameters
  30262. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  30263. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  30264. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  30265. this._distortion = parameters.distortion ? parameters.distortion : 0;
  30266. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  30267. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  30268. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  30269. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  30270. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  30271. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  30272. // Create effects
  30273. this._createChromaticAberrationPostProcess(ratio);
  30274. this._createHighlightsPostProcess(ratio);
  30275. this._createDepthOfFieldPostProcess(ratio);
  30276. // Set up pipeline
  30277. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  30278. return _this._chromaticAberrationPostProcess;
  30279. }, true));
  30280. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  30281. return _this._highlightsPostProcess;
  30282. }, true));
  30283. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  30284. return _this._depthOfFieldPostProcess;
  30285. }, true));
  30286. if (this._highlightsGain == -1) {
  30287. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30288. }
  30289. // Finish
  30290. scene.postProcessRenderPipelineManager.addPipeline(this);
  30291. if (cameras) {
  30292. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30293. }
  30294. }
  30295. // public methods (self explanatory)
  30296. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30297. this._edgeBlur = amount;
  30298. };
  30299. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30300. this._edgeBlur = 0;
  30301. };
  30302. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30303. this._grainAmount = amount;
  30304. };
  30305. LensRenderingPipeline.prototype.disableGrain = function () {
  30306. this._grainAmount = 0;
  30307. };
  30308. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30309. this._chromaticAberration = amount;
  30310. };
  30311. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30312. this._chromaticAberration = 0;
  30313. };
  30314. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30315. this._distortion = amount;
  30316. };
  30317. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30318. this._distortion = 0;
  30319. };
  30320. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30321. this._dofDepth = amount;
  30322. };
  30323. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30324. this._dofDepth = -1;
  30325. };
  30326. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30327. this._dofAperture = amount;
  30328. };
  30329. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30330. this._dofPentagon = true;
  30331. };
  30332. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30333. this._dofPentagon = false;
  30334. };
  30335. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30336. this._blurNoise = true;
  30337. };
  30338. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30339. this._blurNoise = false;
  30340. };
  30341. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30342. this._highlightsGain = amount;
  30343. };
  30344. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30345. if (this._highlightsGain == -1) {
  30346. this._highlightsGain = 1.0;
  30347. }
  30348. this._highlightsThreshold = amount;
  30349. };
  30350. LensRenderingPipeline.prototype.disableHighlights = function () {
  30351. this._highlightsGain = -1;
  30352. };
  30353. /**
  30354. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30355. */
  30356. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30357. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30358. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30359. this._chromaticAberrationPostProcess = undefined;
  30360. this._highlightsPostProcess = undefined;
  30361. this._depthOfFieldPostProcess = undefined;
  30362. this._grainTexture.dispose();
  30363. if (disableDepthRender)
  30364. this._scene.disableDepthRenderer();
  30365. };
  30366. // colors shifting and distortion
  30367. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30368. var _this = this;
  30369. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30370. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30371. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30372. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30373. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30374. };
  30375. };
  30376. // highlights enhancing
  30377. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30378. var _this = this;
  30379. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30380. this._highlightsPostProcess.onApply = function (effect) {
  30381. effect.setFloat('gain', _this._highlightsGain);
  30382. effect.setFloat('threshold', _this._highlightsThreshold);
  30383. effect.setBool('pentagon', _this._dofPentagon);
  30384. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30385. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30386. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30387. };
  30388. };
  30389. // colors shifting and distortion
  30390. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30391. var _this = this;
  30392. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30393. "focus_depth",
  30394. "aperture",
  30395. "pentagon",
  30396. "maxZ",
  30397. "edge_blur",
  30398. "chromatic_aberration",
  30399. "distortion",
  30400. "blur_noise",
  30401. "grain_amount",
  30402. "screen_width",
  30403. "screen_height",
  30404. "highlights"
  30405. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30406. this._depthOfFieldPostProcess.onApply = function (effect) {
  30407. effect.setBool('blur_noise', _this._blurNoise);
  30408. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30409. effect.setFloat('grain_amount', _this._grainAmount);
  30410. effect.setTexture("depthSampler", _this._depthTexture);
  30411. effect.setTexture("grainSampler", _this._grainTexture);
  30412. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30413. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30414. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30415. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30416. effect.setFloat('distortion', _this._distortion);
  30417. effect.setFloat('focus_depth', _this._dofDepth);
  30418. effect.setFloat('aperture', _this._dofAperture);
  30419. effect.setFloat('edge_blur', _this._edgeBlur);
  30420. effect.setBool('highlights', (_this._highlightsGain != -1));
  30421. };
  30422. };
  30423. // creates a black and white random noise texture, 512x512
  30424. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30425. var size = 512;
  30426. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30427. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30428. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30429. var context = this._grainTexture.getContext();
  30430. var rand = function (min, max) {
  30431. return Math.random() * (max - min) + min;
  30432. };
  30433. var value;
  30434. for (var x = 0; x < size; x++) {
  30435. for (var y = 0; y < size; y++) {
  30436. value = Math.floor(rand(0.42, 0.58) * 255);
  30437. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30438. context.fillRect(x, y, 1, 1);
  30439. }
  30440. }
  30441. this._grainTexture.update(false);
  30442. };
  30443. return LensRenderingPipeline;
  30444. })(BABYLON.PostProcessRenderPipeline);
  30445. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30446. })(BABYLON || (BABYLON = {}));
  30447. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30448. // This post-process allows the modification of rendered colors by using
  30449. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30450. //
  30451. // The object needs to be provided an url to a texture containing the color
  30452. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30453. // Use an image editing software to tweak the LUT to match your needs.
  30454. //
  30455. // For an example of a color LUT, see here:
  30456. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30457. // For explanations on color grading, see here:
  30458. // http://udn.epicgames.com/Three/ColorGrading.html
  30459. //
  30460. var BABYLON;
  30461. (function (BABYLON) {
  30462. var ColorCorrectionPostProcess = (function (_super) {
  30463. __extends(ColorCorrectionPostProcess, _super);
  30464. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30465. var _this = this;
  30466. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30467. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30468. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30469. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30470. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30471. this.onApply = function (effect) {
  30472. effect.setTexture("colorTable", _this._colorTableTexture);
  30473. };
  30474. }
  30475. return ColorCorrectionPostProcess;
  30476. })(BABYLON.PostProcess);
  30477. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30478. })(BABYLON || (BABYLON = {}));
  30479. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30480. (function (BABYLON) {
  30481. var SmartCollection = (function () {
  30482. function SmartCollection(capacity) {
  30483. if (capacity === void 0) { capacity = 10; }
  30484. this.count = 0;
  30485. this._initialCapacity = capacity;
  30486. this.items = {};
  30487. this._keys = new Array(this._initialCapacity);
  30488. }
  30489. SmartCollection.prototype.add = function (key, item) {
  30490. if (this.items[key] != undefined) {
  30491. return -1;
  30492. }
  30493. this.items[key] = item;
  30494. //literal keys are always strings, but we keep source type of key in _keys array
  30495. this._keys[this.count++] = key;
  30496. if (this.count > this._keys.length) {
  30497. this._keys.length *= 2;
  30498. }
  30499. return this.count;
  30500. };
  30501. SmartCollection.prototype.remove = function (key) {
  30502. if (this.items[key] == undefined) {
  30503. return -1;
  30504. }
  30505. return this.removeItemOfIndex(this.indexOf(key));
  30506. };
  30507. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30508. if (index < this.count && index > -1) {
  30509. delete this.items[this._keys[index]];
  30510. while (index < this.count) {
  30511. this._keys[index] = this._keys[index + 1];
  30512. index++;
  30513. }
  30514. }
  30515. else {
  30516. return -1;
  30517. }
  30518. return --this.count;
  30519. };
  30520. SmartCollection.prototype.indexOf = function (key) {
  30521. for (var i = 0; i !== this.count; i++) {
  30522. if (this._keys[i] === key) {
  30523. return i;
  30524. }
  30525. }
  30526. return -1;
  30527. };
  30528. SmartCollection.prototype.item = function (key) {
  30529. return this.items[key];
  30530. };
  30531. SmartCollection.prototype.getAllKeys = function () {
  30532. if (this.count > 0) {
  30533. var keys = new Array(this.count);
  30534. for (var i = 0; i < this.count; i++) {
  30535. keys[i] = this._keys[i];
  30536. }
  30537. return keys;
  30538. }
  30539. else {
  30540. return undefined;
  30541. }
  30542. };
  30543. SmartCollection.prototype.getKeyByIndex = function (index) {
  30544. if (index < this.count && index > -1) {
  30545. return this._keys[index];
  30546. }
  30547. else {
  30548. return undefined;
  30549. }
  30550. };
  30551. SmartCollection.prototype.getItemByIndex = function (index) {
  30552. if (index < this.count && index > -1) {
  30553. return this.items[this._keys[index]];
  30554. }
  30555. else {
  30556. return undefined;
  30557. }
  30558. };
  30559. SmartCollection.prototype.empty = function () {
  30560. if (this.count > 0) {
  30561. this.count = 0;
  30562. this.items = {};
  30563. this._keys = new Array(this._initialCapacity);
  30564. }
  30565. };
  30566. SmartCollection.prototype.forEach = function (block) {
  30567. var key;
  30568. for (key in this.items) {
  30569. if (this.items.hasOwnProperty(key)) {
  30570. block(this.items[key]);
  30571. }
  30572. }
  30573. };
  30574. return SmartCollection;
  30575. })();
  30576. BABYLON.SmartCollection = SmartCollection;
  30577. })(BABYLON || (BABYLON = {}));
  30578. //# sourceMappingURL=babylon.smartCollection.js.map