babylon.2.0-beta.debug.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181
  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 (typeof r === "undefined") { r = 0; }
  11. if (typeof g === "undefined") { g = 0; }
  12. if (typeof b === "undefined") { 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. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (typeof alpha === "undefined") { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array, offset) {
  91. if (typeof offset === "undefined") { offset = 0; }
  92. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  93. };
  94. Color3.FromInts = function (r, g, b) {
  95. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  96. };
  97. Color3.Lerp = function (start, end, amount) {
  98. var r = start.r + ((end.r - start.r) * amount);
  99. var g = start.g + ((end.g - start.g) * amount);
  100. var b = start.b + ((end.b - start.b) * amount);
  101. return new Color3(r, g, b);
  102. };
  103. Color3.Red = function () {
  104. return new Color3(1, 0, 0);
  105. };
  106. Color3.Green = function () {
  107. return new Color3(0, 1, 0);
  108. };
  109. Color3.Blue = function () {
  110. return new Color3(0, 0, 1);
  111. };
  112. Color3.Black = function () {
  113. return new Color3(0, 0, 0);
  114. };
  115. Color3.White = function () {
  116. return new Color3(1, 1, 1);
  117. };
  118. Color3.Purple = function () {
  119. return new Color3(0.5, 0, 0.5);
  120. };
  121. Color3.Magenta = function () {
  122. return new Color3(1, 0, 1);
  123. };
  124. Color3.Yellow = function () {
  125. return new Color3(1, 1, 0);
  126. };
  127. Color3.Gray = function () {
  128. return new Color3(0.5, 0.5, 0.5);
  129. };
  130. return Color3;
  131. })();
  132. BABYLON.Color3 = Color3;
  133. var Color4 = (function () {
  134. function Color4(r, g, b, a) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. this.a = a;
  139. }
  140. // Operators
  141. Color4.prototype.addInPlace = function (right) {
  142. this.r += right.r;
  143. this.g += right.g;
  144. this.b += right.b;
  145. this.a += right.a;
  146. };
  147. Color4.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. Color4.prototype.toArray = function (array, index) {
  153. if (index === undefined) {
  154. index = 0;
  155. }
  156. array[index] = this.r;
  157. array[index + 1] = this.g;
  158. array[index + 2] = this.b;
  159. array[index + 3] = this.a;
  160. };
  161. Color4.prototype.add = function (right) {
  162. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  163. };
  164. Color4.prototype.subtract = function (right) {
  165. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  166. };
  167. Color4.prototype.subtractToRef = function (right, result) {
  168. result.r = this.r - right.r;
  169. result.g = this.g - right.g;
  170. result.b = this.b - right.b;
  171. result.a = this.a - right.a;
  172. };
  173. Color4.prototype.scale = function (scale) {
  174. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  175. };
  176. Color4.prototype.scaleToRef = function (scale, result) {
  177. result.r = this.r * scale;
  178. result.g = this.g * scale;
  179. result.b = this.b * scale;
  180. result.a = this.a * scale;
  181. };
  182. Color4.prototype.toString = function () {
  183. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  184. };
  185. Color4.prototype.clone = function () {
  186. return new Color4(this.r, this.g, this.b, this.a);
  187. };
  188. Color4.prototype.copyFrom = function (source) {
  189. this.r = source.r;
  190. this.g = source.g;
  191. this.b = source.b;
  192. this.a = source.a;
  193. };
  194. // Statics
  195. Color4.Lerp = function (left, right, amount) {
  196. var result = new Color4(0, 0, 0, 0);
  197. Color4.LerpToRef(left, right, amount, result);
  198. return result;
  199. };
  200. Color4.LerpToRef = function (left, right, amount, result) {
  201. result.r = left.r + (right.r - left.r) * amount;
  202. result.g = left.g + (right.g - left.g) * amount;
  203. result.b = left.b + (right.b - left.b) * amount;
  204. result.a = left.a + (right.a - left.a) * amount;
  205. };
  206. Color4.FromArray = function (array, offset) {
  207. if (typeof offset === "undefined") { offset = 0; }
  208. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  209. };
  210. Color4.FromInts = function (r, g, b, a) {
  211. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  212. };
  213. return Color4;
  214. })();
  215. BABYLON.Color4 = Color4;
  216. var Vector2 = (function () {
  217. function Vector2(x, y) {
  218. this.x = x;
  219. this.y = y;
  220. }
  221. Vector2.prototype.toString = function () {
  222. return "{X: " + this.x + " Y:" + this.y + "}";
  223. };
  224. // Operators
  225. Vector2.prototype.toArray = function (array, index) {
  226. if (index === undefined) {
  227. index = 0;
  228. }
  229. array[index] = this.x;
  230. array[index + 1] = this.y;
  231. };
  232. Vector2.prototype.asArray = function () {
  233. var result = [];
  234. this.toArray(result, 0);
  235. return result;
  236. };
  237. Vector2.prototype.copyFrom = function (source) {
  238. this.x = source.x;
  239. this.y = source.y;
  240. };
  241. Vector2.prototype.copyFromFloats = function (x, y) {
  242. this.x = x;
  243. this.y = y;
  244. };
  245. Vector2.prototype.add = function (otherVector) {
  246. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  247. };
  248. Vector2.prototype.addVector3 = function (otherVector) {
  249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  250. };
  251. Vector2.prototype.subtract = function (otherVector) {
  252. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  253. };
  254. Vector2.prototype.subtractInPlace = function (otherVector) {
  255. this.x -= otherVector.x;
  256. this.y -= otherVector.y;
  257. };
  258. Vector2.prototype.multiplyInPlace = function (otherVector) {
  259. this.x *= otherVector.x;
  260. this.y *= otherVector.y;
  261. };
  262. Vector2.prototype.multiply = function (otherVector) {
  263. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  264. };
  265. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  266. result.x = this.x * otherVector.x;
  267. result.y = this.y * otherVector.y;
  268. };
  269. Vector2.prototype.multiplyByFloats = function (x, y) {
  270. return new Vector2(this.x * x, this.y * y);
  271. };
  272. Vector2.prototype.divide = function (otherVector) {
  273. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  274. };
  275. Vector2.prototype.divideToRef = function (otherVector, result) {
  276. result.x = this.x / otherVector.x;
  277. result.y = this.y / otherVector.y;
  278. };
  279. Vector2.prototype.negate = function () {
  280. return new Vector2(-this.x, -this.y);
  281. };
  282. Vector2.prototype.scaleInPlace = function (scale) {
  283. this.x *= scale;
  284. this.y *= scale;
  285. return this;
  286. };
  287. Vector2.prototype.scale = function (scale) {
  288. return new Vector2(this.x * scale, this.y * scale);
  289. };
  290. Vector2.prototype.equals = function (otherVector) {
  291. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  292. };
  293. // Properties
  294. Vector2.prototype.length = function () {
  295. return Math.sqrt(this.x * this.x + this.y * this.y);
  296. };
  297. Vector2.prototype.lengthSquared = function () {
  298. return (this.x * this.x + this.y * this.y);
  299. };
  300. // Methods
  301. Vector2.prototype.normalize = function () {
  302. var len = this.length();
  303. if (len === 0)
  304. return this;
  305. var num = 1.0 / len;
  306. this.x *= num;
  307. this.y *= num;
  308. return this;
  309. };
  310. Vector2.prototype.clone = function () {
  311. return new Vector2(this.x, this.y);
  312. };
  313. // Statics
  314. Vector2.Zero = function () {
  315. return new Vector2(0, 0);
  316. };
  317. Vector2.FromArray = function (array, offset) {
  318. if (typeof offset === "undefined") { offset = 0; }
  319. return new Vector2(array[offset], array[offset + 1]);
  320. };
  321. Vector2.FromArrayToRef = function (array, offset, result) {
  322. result.x = array[offset];
  323. result.y = array[offset + 1];
  324. };
  325. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  326. var squared = amount * amount;
  327. var cubed = amount * squared;
  328. 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));
  329. 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));
  330. return new Vector2(x, y);
  331. };
  332. Vector2.Clamp = function (value, min, max) {
  333. var x = value.x;
  334. x = (x > max.x) ? max.x : x;
  335. x = (x < min.x) ? min.x : x;
  336. var y = value.y;
  337. y = (y > max.y) ? max.y : y;
  338. y = (y < min.y) ? min.y : y;
  339. return new Vector2(x, y);
  340. };
  341. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  342. var squared = amount * amount;
  343. var cubed = amount * squared;
  344. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  345. var part2 = (-2.0 * cubed) + (3.0 * squared);
  346. var part3 = (cubed - (2.0 * squared)) + amount;
  347. var part4 = cubed - squared;
  348. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  349. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Lerp = function (start, end, amount) {
  353. var x = start.x + ((end.x - start.x) * amount);
  354. var y = start.y + ((end.y - start.y) * amount);
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Dot = function (left, right) {
  358. return left.x * right.x + left.y * right.y;
  359. };
  360. Vector2.Normalize = function (vector) {
  361. var newVector = vector.clone();
  362. newVector.normalize();
  363. return newVector;
  364. };
  365. Vector2.Minimize = function (left, right) {
  366. var x = (left.x < right.x) ? left.x : right.x;
  367. var y = (left.y < right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Maximize = function (left, right) {
  371. var x = (left.x > right.x) ? left.x : right.x;
  372. var y = (left.y > right.y) ? left.y : right.y;
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Transform = function (vector, transformation) {
  376. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  377. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  378. return new Vector2(x, y);
  379. };
  380. Vector2.Distance = function (value1, value2) {
  381. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  382. };
  383. Vector2.DistanceSquared = function (value1, value2) {
  384. var x = value1.x - value2.x;
  385. var y = value1.y - value2.y;
  386. return (x * x) + (y * y);
  387. };
  388. return Vector2;
  389. })();
  390. BABYLON.Vector2 = Vector2;
  391. var Vector3 = (function () {
  392. function Vector3(x, y, z) {
  393. this.x = x;
  394. this.y = y;
  395. this.z = z;
  396. }
  397. Vector3.prototype.toString = function () {
  398. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  399. };
  400. // Operators
  401. Vector3.prototype.asArray = function () {
  402. var result = [];
  403. this.toArray(result, 0);
  404. return result;
  405. };
  406. Vector3.prototype.toArray = function (array, index) {
  407. if (index === undefined) {
  408. index = 0;
  409. }
  410. array[index] = this.x;
  411. array[index + 1] = this.y;
  412. array[index + 2] = this.z;
  413. };
  414. Vector3.prototype.addInPlace = function (otherVector) {
  415. this.x += otherVector.x;
  416. this.y += otherVector.y;
  417. this.z += otherVector.z;
  418. };
  419. Vector3.prototype.add = function (otherVector) {
  420. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  421. };
  422. Vector3.prototype.addToRef = function (otherVector, result) {
  423. result.x = this.x + otherVector.x;
  424. result.y = this.y + otherVector.y;
  425. result.z = this.z + otherVector.z;
  426. };
  427. Vector3.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. this.z -= otherVector.z;
  431. };
  432. Vector3.prototype.subtract = function (otherVector) {
  433. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  434. };
  435. Vector3.prototype.subtractToRef = function (otherVector, result) {
  436. result.x = this.x - otherVector.x;
  437. result.y = this.y - otherVector.y;
  438. result.z = this.z - otherVector.z;
  439. };
  440. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  441. return new Vector3(this.x - x, this.y - y, this.z - z);
  442. };
  443. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  444. result.x = this.x - x;
  445. result.y = this.y - y;
  446. result.z = this.z - z;
  447. };
  448. Vector3.prototype.negate = function () {
  449. return new Vector3(-this.x, -this.y, -this.z);
  450. };
  451. Vector3.prototype.scaleInPlace = function (scale) {
  452. this.x *= scale;
  453. this.y *= scale;
  454. this.z *= scale;
  455. return this;
  456. };
  457. Vector3.prototype.scale = function (scale) {
  458. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  459. };
  460. Vector3.prototype.scaleToRef = function (scale, result) {
  461. result.x = this.x * scale;
  462. result.y = this.y * scale;
  463. result.z = this.z * scale;
  464. };
  465. Vector3.prototype.equals = function (otherVector) {
  466. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  467. };
  468. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  469. 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;
  470. };
  471. Vector3.prototype.equalsToFloats = function (x, y, z) {
  472. return this.x === x && this.y === y && this.z === z;
  473. };
  474. Vector3.prototype.multiplyInPlace = function (otherVector) {
  475. this.x *= otherVector.x;
  476. this.y *= otherVector.y;
  477. this.z *= otherVector.z;
  478. };
  479. Vector3.prototype.multiply = function (otherVector) {
  480. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  481. };
  482. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  483. result.x = this.x * otherVector.x;
  484. result.y = this.y * otherVector.y;
  485. result.z = this.z * otherVector.z;
  486. };
  487. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  488. return new Vector3(this.x * x, this.y * y, this.z * z);
  489. };
  490. Vector3.prototype.divide = function (otherVector) {
  491. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  492. };
  493. Vector3.prototype.divideToRef = function (otherVector, result) {
  494. result.x = this.x / otherVector.x;
  495. result.y = this.y / otherVector.y;
  496. result.z = this.z / otherVector.z;
  497. };
  498. Vector3.prototype.MinimizeInPlace = function (other) {
  499. if (other.x < this.x)
  500. this.x = other.x;
  501. if (other.y < this.y)
  502. this.y = other.y;
  503. if (other.z < this.z)
  504. this.z = other.z;
  505. };
  506. Vector3.prototype.MaximizeInPlace = function (other) {
  507. if (other.x > this.x)
  508. this.x = other.x;
  509. if (other.y > this.y)
  510. this.y = other.y;
  511. if (other.z > this.z)
  512. this.z = other.z;
  513. };
  514. // Properties
  515. Vector3.prototype.length = function () {
  516. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  517. };
  518. Vector3.prototype.lengthSquared = function () {
  519. return (this.x * this.x + this.y * this.y + this.z * this.z);
  520. };
  521. // Methods
  522. Vector3.prototype.normalize = function () {
  523. var len = this.length();
  524. if (len === 0)
  525. return this;
  526. var num = 1.0 / len;
  527. this.x *= num;
  528. this.y *= num;
  529. this.z *= num;
  530. return this;
  531. };
  532. Vector3.prototype.clone = function () {
  533. return new Vector3(this.x, this.y, this.z);
  534. };
  535. Vector3.prototype.copyFrom = function (source) {
  536. this.x = source.x;
  537. this.y = source.y;
  538. this.z = source.z;
  539. };
  540. Vector3.prototype.copyFromFloats = function (x, y, z) {
  541. this.x = x;
  542. this.y = y;
  543. this.z = z;
  544. };
  545. // Statics
  546. Vector3.FromArray = function (array, offset) {
  547. if (!offset) {
  548. offset = 0;
  549. }
  550. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  551. };
  552. Vector3.FromArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  558. result.x = array[offset];
  559. result.y = array[offset + 1];
  560. result.z = array[offset + 2];
  561. };
  562. Vector3.FromFloatsToRef = function (x, y, z, result) {
  563. result.x = x;
  564. result.y = y;
  565. result.z = z;
  566. };
  567. Vector3.Zero = function () {
  568. return new Vector3(0, 0, 0);
  569. };
  570. Vector3.Up = function () {
  571. return new Vector3(0, 1.0, 0);
  572. };
  573. Vector3.TransformCoordinates = function (vector, transformation) {
  574. var result = Vector3.Zero();
  575. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  576. return result;
  577. };
  578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  583. result.x = x / w;
  584. result.y = y / w;
  585. result.z = z / w;
  586. };
  587. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  588. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  589. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  590. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  591. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  592. result.x = rx / rw;
  593. result.y = ry / rw;
  594. result.z = rz / rw;
  595. };
  596. Vector3.TransformNormal = function (vector, transformation) {
  597. var result = Vector3.Zero();
  598. Vector3.TransformNormalToRef(vector, transformation, result);
  599. return result;
  600. };
  601. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  602. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  603. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  604. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  605. };
  606. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  607. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  608. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  609. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  610. };
  611. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  612. var squared = amount * amount;
  613. var cubed = amount * squared;
  614. 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));
  615. 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));
  616. 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));
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Clamp = function (value, min, max) {
  620. var x = value.x;
  621. x = (x > max.x) ? max.x : x;
  622. x = (x < min.x) ? min.x : x;
  623. var y = value.y;
  624. y = (y > max.y) ? max.y : y;
  625. y = (y < min.y) ? min.y : y;
  626. var z = value.z;
  627. z = (z > max.z) ? max.z : z;
  628. z = (z < min.z) ? min.z : z;
  629. return new Vector3(x, y, z);
  630. };
  631. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  632. var squared = amount * amount;
  633. var cubed = amount * squared;
  634. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  635. var part2 = (-2.0 * cubed) + (3.0 * squared);
  636. var part3 = (cubed - (2.0 * squared)) + amount;
  637. var part4 = cubed - squared;
  638. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  639. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  640. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  641. return new Vector3(x, y, z);
  642. };
  643. Vector3.Lerp = function (start, end, amount) {
  644. var x = start.x + ((end.x - start.x) * amount);
  645. var y = start.y + ((end.y - start.y) * amount);
  646. var z = start.z + ((end.z - start.z) * amount);
  647. return new Vector3(x, y, z);
  648. };
  649. Vector3.Dot = function (left, right) {
  650. return (left.x * right.x + left.y * right.y + left.z * right.z);
  651. };
  652. Vector3.Cross = function (left, right) {
  653. var result = Vector3.Zero();
  654. Vector3.CrossToRef(left, right, result);
  655. return result;
  656. };
  657. Vector3.CrossToRef = function (left, right, result) {
  658. result.x = left.y * right.z - left.z * right.y;
  659. result.y = left.z * right.x - left.x * right.z;
  660. result.z = left.x * right.y - left.y * right.x;
  661. };
  662. Vector3.Normalize = function (vector) {
  663. var result = Vector3.Zero();
  664. Vector3.NormalizeToRef(vector, result);
  665. return result;
  666. };
  667. Vector3.NormalizeToRef = function (vector, result) {
  668. result.copyFrom(vector);
  669. result.normalize();
  670. };
  671. Vector3.Project = function (vector, world, transform, viewport) {
  672. var cw = viewport.width;
  673. var ch = viewport.height;
  674. var cx = viewport.x;
  675. var cy = viewport.y;
  676. 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);
  677. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  678. return Vector3.TransformCoordinates(vector, finalMatrix);
  679. };
  680. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  681. var matrix = world.multiply(transform);
  682. matrix.invert();
  683. source.x = source.x / viewportWidth * 2 - 1;
  684. source.y = -(source.y / viewportHeight * 2 - 1);
  685. var vector = Vector3.TransformCoordinates(source, matrix);
  686. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  687. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  688. vector = vector.scale(1.0 / num);
  689. }
  690. return vector;
  691. };
  692. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  693. var matrix = world.multiply(view).multiply(projection);
  694. matrix.invert();
  695. source.x = source.x / viewportWidth * 2 - 1;
  696. source.y = -(source.y / viewportHeight * 2 - 1);
  697. var vector = Vector3.TransformCoordinates(source, matrix);
  698. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  699. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  700. vector = vector.scale(1.0 / num);
  701. }
  702. return vector;
  703. };
  704. Vector3.Minimize = function (left, right) {
  705. var min = left.clone();
  706. min.MinimizeInPlace(right);
  707. return min;
  708. };
  709. Vector3.Maximize = function (left, right) {
  710. var max = left.clone();
  711. max.MaximizeInPlace(right);
  712. return max;
  713. };
  714. Vector3.Distance = function (value1, value2) {
  715. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  716. };
  717. Vector3.DistanceSquared = function (value1, value2) {
  718. var x = value1.x - value2.x;
  719. var y = value1.y - value2.y;
  720. var z = value1.z - value2.z;
  721. return (x * x) + (y * y) + (z * z);
  722. };
  723. Vector3.Center = function (value1, value2) {
  724. var center = value1.add(value2);
  725. center.scaleInPlace(0.5);
  726. return center;
  727. };
  728. return Vector3;
  729. })();
  730. BABYLON.Vector3 = Vector3;
  731. //Vector4 class created for EulerAngle class conversion to Quaternion
  732. var Vector4 = (function () {
  733. function Vector4(x, y, z, w) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. }
  739. Vector4.prototype.toString = function () {
  740. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  741. };
  742. // Operators
  743. Vector4.prototype.asArray = function () {
  744. var result = [];
  745. this.toArray(result, 0);
  746. return result;
  747. };
  748. Vector4.prototype.toArray = function (array, index) {
  749. if (index === undefined) {
  750. index = 0;
  751. }
  752. array[index] = this.x;
  753. array[index + 1] = this.y;
  754. array[index + 2] = this.z;
  755. array[index + 3] = this.w;
  756. };
  757. Vector4.prototype.addInPlace = function (otherVector) {
  758. this.x += otherVector.x;
  759. this.y += otherVector.y;
  760. this.z += otherVector.z;
  761. this.w += otherVector.w;
  762. };
  763. Vector4.prototype.add = function (otherVector) {
  764. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  765. };
  766. Vector4.prototype.addToRef = function (otherVector, result) {
  767. result.x = this.x + otherVector.x;
  768. result.y = this.y + otherVector.y;
  769. result.z = this.z + otherVector.z;
  770. result.w = this.w + otherVector.w;
  771. };
  772. Vector4.prototype.subtractInPlace = function (otherVector) {
  773. this.x -= otherVector.x;
  774. this.y -= otherVector.y;
  775. this.z -= otherVector.z;
  776. this.w -= otherVector.w;
  777. };
  778. Vector4.prototype.subtract = function (otherVector) {
  779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  780. };
  781. Vector4.prototype.subtractToRef = function (otherVector, result) {
  782. result.x = this.x - otherVector.x;
  783. result.y = this.y - otherVector.y;
  784. result.z = this.z - otherVector.z;
  785. result.w = this.w - otherVector.w;
  786. };
  787. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  788. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  789. };
  790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  791. result.x = this.x - x;
  792. result.y = this.y - y;
  793. result.z = this.z - z;
  794. result.w = this.w - w;
  795. };
  796. Vector4.prototype.negate = function () {
  797. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  798. };
  799. Vector4.prototype.scaleInPlace = function (scale) {
  800. this.x *= scale;
  801. this.y *= scale;
  802. this.z *= scale;
  803. this.w *= scale;
  804. return this;
  805. };
  806. Vector4.prototype.scale = function (scale) {
  807. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  808. };
  809. Vector4.prototype.scaleToRef = function (scale, result) {
  810. result.x = this.x * scale;
  811. result.y = this.y * scale;
  812. result.z = this.z * scale;
  813. result.w = this.w * scale;
  814. };
  815. Vector4.prototype.equals = function (otherVector) {
  816. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  817. };
  818. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  819. 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;
  820. };
  821. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  822. return this.x === x && this.y === y && this.z === z && this.w === w;
  823. };
  824. Vector4.prototype.multiplyInPlace = function (otherVector) {
  825. this.x *= otherVector.x;
  826. this.y *= otherVector.y;
  827. this.z *= otherVector.z;
  828. this.w *= otherVector.w;
  829. };
  830. Vector4.prototype.multiply = function (otherVector) {
  831. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  832. };
  833. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  834. result.x = this.x * otherVector.x;
  835. result.y = this.y * otherVector.y;
  836. result.z = this.z * otherVector.z;
  837. result.w = this.w * otherVector.w;
  838. };
  839. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  840. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  841. };
  842. Vector4.prototype.divide = function (otherVector) {
  843. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  844. };
  845. Vector4.prototype.divideToRef = function (otherVector, result) {
  846. result.x = this.x / otherVector.x;
  847. result.y = this.y / otherVector.y;
  848. result.z = this.z / otherVector.z;
  849. result.w = this.w / otherVector.w;
  850. };
  851. Vector4.prototype.MinimizeInPlace = function (other) {
  852. if (other.x < this.x)
  853. this.x = other.x;
  854. if (other.y < this.y)
  855. this.y = other.y;
  856. if (other.z < this.z)
  857. this.z = other.z;
  858. if (other.w < this.w)
  859. this.w = other.w;
  860. };
  861. Vector4.prototype.MaximizeInPlace = function (other) {
  862. if (other.x > this.x)
  863. this.x = other.x;
  864. if (other.y > this.y)
  865. this.y = other.y;
  866. if (other.z > this.z)
  867. this.z = other.z;
  868. if (other.w > this.w)
  869. this.w = other.w;
  870. };
  871. // Properties
  872. Vector4.prototype.length = function () {
  873. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  874. };
  875. Vector4.prototype.lengthSquared = function () {
  876. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  877. };
  878. // Methods
  879. Vector4.prototype.normalize = function () {
  880. var len = this.length();
  881. if (len === 0)
  882. return this;
  883. var num = 1.0 / len;
  884. this.x *= num;
  885. this.y *= num;
  886. this.z *= num;
  887. this.w *= num;
  888. return this;
  889. };
  890. Vector4.prototype.clone = function () {
  891. return new Vector4(this.x, this.y, this.z, this.w);
  892. };
  893. Vector4.prototype.copyFrom = function (source) {
  894. this.x = source.x;
  895. this.y = source.y;
  896. this.z = source.z;
  897. this.w = source.w;
  898. };
  899. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  900. this.x = x;
  901. this.y = y;
  902. this.z = z;
  903. this.w = w;
  904. };
  905. // Statics
  906. Vector4.FromArray = function (array, offset) {
  907. if (!offset) {
  908. offset = 0;
  909. }
  910. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  911. };
  912. Vector4.FromArrayToRef = function (array, offset, result) {
  913. result.x = array[offset];
  914. result.y = array[offset + 1];
  915. result.z = array[offset + 2];
  916. result.w = array[offset + 3];
  917. };
  918. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  919. result.x = array[offset];
  920. result.y = array[offset + 1];
  921. result.z = array[offset + 2];
  922. result.w = array[offset + 3];
  923. };
  924. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  925. result.x = x;
  926. result.y = y;
  927. result.z = z;
  928. result.w = w;
  929. };
  930. Vector4.Zero = function () {
  931. return new Vector4(0, 0, 0, 0);
  932. };
  933. Vector4.Normalize = function (vector) {
  934. var result = Vector4.Zero();
  935. Vector4.NormalizeToRef(vector, result);
  936. return result;
  937. };
  938. Vector4.NormalizeToRef = function (vector, result) {
  939. result.copyFrom(vector);
  940. result.normalize();
  941. };
  942. Vector4.Minimize = function (left, right) {
  943. var min = left.clone();
  944. min.MinimizeInPlace(right);
  945. return min;
  946. };
  947. Vector4.Maximize = function (left, right) {
  948. var max = left.clone();
  949. max.MaximizeInPlace(right);
  950. return max;
  951. };
  952. Vector4.Distance = function (value1, value2) {
  953. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  954. };
  955. Vector4.DistanceSquared = function (value1, value2) {
  956. var x = value1.x - value2.x;
  957. var y = value1.y - value2.y;
  958. var z = value1.z - value2.z;
  959. var w = value1.w - value2.w;
  960. return (x * x) + (y * y) + (z * z) + (w * w);
  961. };
  962. Vector4.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. return Vector4;
  968. })();
  969. BABYLON.Vector4 = Vector4;
  970. var Quaternion = (function () {
  971. function Quaternion(x, y, z, w) {
  972. if (typeof x === "undefined") { x = 0; }
  973. if (typeof y === "undefined") { y = 0; }
  974. if (typeof z === "undefined") { z = 0; }
  975. if (typeof w === "undefined") { w = 1; }
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. }
  981. Quaternion.prototype.toString = function () {
  982. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  983. };
  984. Quaternion.prototype.asArray = function () {
  985. return [this.x, this.y, this.z, this.w];
  986. };
  987. Quaternion.prototype.equals = function (otherQuaternion) {
  988. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  989. };
  990. Quaternion.prototype.clone = function () {
  991. return new Quaternion(this.x, this.y, this.z, this.w);
  992. };
  993. Quaternion.prototype.copyFrom = function (other) {
  994. this.x = other.x;
  995. this.y = other.y;
  996. this.z = other.z;
  997. this.w = other.w;
  998. };
  999. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1000. this.x = x;
  1001. this.y = y;
  1002. this.z = z;
  1003. this.w = w;
  1004. };
  1005. Quaternion.prototype.add = function (other) {
  1006. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1007. };
  1008. Quaternion.prototype.subtract = function (other) {
  1009. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1010. };
  1011. Quaternion.prototype.scale = function (value) {
  1012. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1013. };
  1014. Quaternion.prototype.multiply = function (q1) {
  1015. var result = new Quaternion(0, 0, 0, 1.0);
  1016. this.multiplyToRef(q1, result);
  1017. return result;
  1018. };
  1019. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1020. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1021. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1022. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1023. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1024. };
  1025. Quaternion.prototype.length = function () {
  1026. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1027. };
  1028. Quaternion.prototype.normalize = function () {
  1029. var length = 1.0 / this.length();
  1030. this.x *= length;
  1031. this.y *= length;
  1032. this.z *= length;
  1033. this.w *= length;
  1034. };
  1035. Quaternion.prototype.toEulerAngles = function () {
  1036. var result = Vector3.Zero();
  1037. this.toEulerAnglesToRef(result);
  1038. return result;
  1039. };
  1040. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1041. //result is an EulerAngles in the in the z-x-z convention
  1042. var qx = this.x;
  1043. var qy = this.y;
  1044. var qz = this.z;
  1045. var qw = this.w;
  1046. var qxy = qx * qy;
  1047. var qxz = qx * qz;
  1048. var qwy = qw * qy;
  1049. var qwz = qw * qz;
  1050. var qwx = qw * qx;
  1051. var qyz = qy * qz;
  1052. var sqx = qx * qx;
  1053. var sqy = qy * qy;
  1054. var determinant = sqx + sqy;
  1055. if (determinant !== 0.000 && determinant !== 1.000) {
  1056. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1057. result.y = Math.acos(1 - 2 * determinant);
  1058. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1059. } else {
  1060. if (determinant === 0.0) {
  1061. result.x = 0.0;
  1062. result.y = 0.0;
  1063. 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)
  1064. } else {
  1065. 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)
  1066. result.y = Math.PI;
  1067. result.z = 0.0;
  1068. }
  1069. }
  1070. };
  1071. Quaternion.prototype.toRotationMatrix = function (result) {
  1072. var xx = this.x * this.x;
  1073. var yy = this.y * this.y;
  1074. var zz = this.z * this.z;
  1075. var xy = this.x * this.y;
  1076. var zw = this.z * this.w;
  1077. var zx = this.z * this.x;
  1078. var yw = this.y * this.w;
  1079. var yz = this.y * this.z;
  1080. var xw = this.x * this.w;
  1081. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1082. result.m[1] = 2.0 * (xy + zw);
  1083. result.m[2] = 2.0 * (zx - yw);
  1084. result.m[3] = 0;
  1085. result.m[4] = 2.0 * (xy - zw);
  1086. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1087. result.m[6] = 2.0 * (yz + xw);
  1088. result.m[7] = 0;
  1089. result.m[8] = 2.0 * (zx + yw);
  1090. result.m[9] = 2.0 * (yz - xw);
  1091. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1092. result.m[11] = 0;
  1093. result.m[12] = 0;
  1094. result.m[13] = 0;
  1095. result.m[14] = 0;
  1096. result.m[15] = 1.0;
  1097. };
  1098. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1099. var data = matrix.m;
  1100. var m11 = data[0], m12 = data[4], m13 = data[8];
  1101. var m21 = data[1], m22 = data[5], m23 = data[9];
  1102. var m31 = data[2], m32 = data[6], m33 = data[10];
  1103. var trace = m11 + m22 + m33;
  1104. var s;
  1105. if (trace > 0) {
  1106. s = 0.5 / Math.sqrt(trace + 1.0);
  1107. this.w = 0.25 / s;
  1108. this.x = (m32 - m23) * s;
  1109. this.y = (m13 - m31) * s;
  1110. this.z = (m21 - m12) * s;
  1111. return;
  1112. }
  1113. if (m11 > m22 && m11 > m33) {
  1114. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1115. this.w = (m32 - m23) / s;
  1116. this.x = 0.25 * s;
  1117. this.y = (m12 + m21) / s;
  1118. this.z = (m13 + m31) / s;
  1119. return;
  1120. }
  1121. if (m22 > m33) {
  1122. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1123. this.w = (m13 - m31) / s;
  1124. this.x = (m12 + m21) / s;
  1125. this.y = 0.25 * s;
  1126. this.z = (m23 + m32) / s;
  1127. return;
  1128. }
  1129. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1130. this.w = (m21 - m12) / s;
  1131. this.x = (m13 + m31) / s;
  1132. this.y = (m23 + m32) / s;
  1133. this.z = 0.25 * s;
  1134. };
  1135. // Statics
  1136. Quaternion.Inverse = function (q) {
  1137. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1138. };
  1139. Quaternion.Identity = function () {
  1140. return new Quaternion(0, 0, 0, 1);
  1141. };
  1142. Quaternion.RotationAxis = function (axis, angle) {
  1143. var result = new Quaternion();
  1144. var sin = Math.sin(angle / 2);
  1145. result.w = Math.cos(angle / 2);
  1146. result.x = axis.x * sin;
  1147. result.y = axis.y * sin;
  1148. result.z = axis.z * sin;
  1149. return result;
  1150. };
  1151. Quaternion.FromArray = function (array, offset) {
  1152. if (!offset) {
  1153. offset = 0;
  1154. }
  1155. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1156. };
  1157. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1158. var result = new Quaternion();
  1159. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1160. return result;
  1161. };
  1162. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1163. var halfRoll = roll * 0.5;
  1164. var halfPitch = pitch * 0.5;
  1165. var halfYaw = yaw * 0.5;
  1166. var sinRoll = Math.sin(halfRoll);
  1167. var cosRoll = Math.cos(halfRoll);
  1168. var sinPitch = Math.sin(halfPitch);
  1169. var cosPitch = Math.cos(halfPitch);
  1170. var sinYaw = Math.sin(halfYaw);
  1171. var cosYaw = Math.cos(halfYaw);
  1172. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1173. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1174. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1175. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1176. };
  1177. Quaternion.Slerp = function (left, right, amount) {
  1178. var num2;
  1179. var num3;
  1180. var num = amount;
  1181. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1182. var flag = false;
  1183. if (num4 < 0) {
  1184. flag = true;
  1185. num4 = -num4;
  1186. }
  1187. if (num4 > 0.999999) {
  1188. num3 = 1 - num;
  1189. num2 = flag ? -num : num;
  1190. } else {
  1191. var num5 = Math.acos(num4);
  1192. var num6 = (1.0 / Math.sin(num5));
  1193. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1194. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1195. }
  1196. 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));
  1197. };
  1198. return Quaternion;
  1199. })();
  1200. BABYLON.Quaternion = Quaternion;
  1201. var Matrix = (function () {
  1202. function Matrix() {
  1203. this.m = new Float32Array(16);
  1204. }
  1205. // Properties
  1206. Matrix.prototype.isIdentity = function () {
  1207. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1208. return false;
  1209. 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)
  1210. return false;
  1211. return true;
  1212. };
  1213. Matrix.prototype.determinant = function () {
  1214. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1215. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1216. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1217. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1218. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1219. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1220. 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))));
  1221. };
  1222. // Methods
  1223. Matrix.prototype.toArray = function () {
  1224. return this.m;
  1225. };
  1226. Matrix.prototype.asArray = function () {
  1227. return this.toArray();
  1228. };
  1229. Matrix.prototype.invert = function () {
  1230. this.invertToRef(this);
  1231. };
  1232. Matrix.prototype.invertToRef = function (other) {
  1233. var l1 = this.m[0];
  1234. var l2 = this.m[1];
  1235. var l3 = this.m[2];
  1236. var l4 = this.m[3];
  1237. var l5 = this.m[4];
  1238. var l6 = this.m[5];
  1239. var l7 = this.m[6];
  1240. var l8 = this.m[7];
  1241. var l9 = this.m[8];
  1242. var l10 = this.m[9];
  1243. var l11 = this.m[10];
  1244. var l12 = this.m[11];
  1245. var l13 = this.m[12];
  1246. var l14 = this.m[13];
  1247. var l15 = this.m[14];
  1248. var l16 = this.m[15];
  1249. var l17 = (l11 * l16) - (l12 * l15);
  1250. var l18 = (l10 * l16) - (l12 * l14);
  1251. var l19 = (l10 * l15) - (l11 * l14);
  1252. var l20 = (l9 * l16) - (l12 * l13);
  1253. var l21 = (l9 * l15) - (l11 * l13);
  1254. var l22 = (l9 * l14) - (l10 * l13);
  1255. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1256. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1257. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1258. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1259. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1260. var l28 = (l7 * l16) - (l8 * l15);
  1261. var l29 = (l6 * l16) - (l8 * l14);
  1262. var l30 = (l6 * l15) - (l7 * l14);
  1263. var l31 = (l5 * l16) - (l8 * l13);
  1264. var l32 = (l5 * l15) - (l7 * l13);
  1265. var l33 = (l5 * l14) - (l6 * l13);
  1266. var l34 = (l7 * l12) - (l8 * l11);
  1267. var l35 = (l6 * l12) - (l8 * l10);
  1268. var l36 = (l6 * l11) - (l7 * l10);
  1269. var l37 = (l5 * l12) - (l8 * l9);
  1270. var l38 = (l5 * l11) - (l7 * l9);
  1271. var l39 = (l5 * l10) - (l6 * l9);
  1272. other.m[0] = l23 * l27;
  1273. other.m[4] = l24 * l27;
  1274. other.m[8] = l25 * l27;
  1275. other.m[12] = l26 * l27;
  1276. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1277. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1278. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1279. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1280. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1281. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1282. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1283. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1284. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1285. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1286. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1287. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1288. };
  1289. Matrix.prototype.setTranslation = function (vector3) {
  1290. this.m[12] = vector3.x;
  1291. this.m[13] = vector3.y;
  1292. this.m[14] = vector3.z;
  1293. };
  1294. Matrix.prototype.multiply = function (other) {
  1295. var result = new Matrix();
  1296. this.multiplyToRef(other, result);
  1297. return result;
  1298. };
  1299. Matrix.prototype.copyFrom = function (other) {
  1300. for (var index = 0; index < 16; index++) {
  1301. this.m[index] = other.m[index];
  1302. }
  1303. };
  1304. Matrix.prototype.copyToArray = function (array, offset) {
  1305. if (typeof offset === "undefined") { offset = 0; }
  1306. for (var index = 0; index < 16; index++) {
  1307. array[offset + index] = this.m[index];
  1308. }
  1309. };
  1310. Matrix.prototype.multiplyToRef = function (other, result) {
  1311. this.multiplyToArray(other, result.m, 0);
  1312. };
  1313. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1314. var tm0 = this.m[0];
  1315. var tm1 = this.m[1];
  1316. var tm2 = this.m[2];
  1317. var tm3 = this.m[3];
  1318. var tm4 = this.m[4];
  1319. var tm5 = this.m[5];
  1320. var tm6 = this.m[6];
  1321. var tm7 = this.m[7];
  1322. var tm8 = this.m[8];
  1323. var tm9 = this.m[9];
  1324. var tm10 = this.m[10];
  1325. var tm11 = this.m[11];
  1326. var tm12 = this.m[12];
  1327. var tm13 = this.m[13];
  1328. var tm14 = this.m[14];
  1329. var tm15 = this.m[15];
  1330. var om0 = other.m[0];
  1331. var om1 = other.m[1];
  1332. var om2 = other.m[2];
  1333. var om3 = other.m[3];
  1334. var om4 = other.m[4];
  1335. var om5 = other.m[5];
  1336. var om6 = other.m[6];
  1337. var om7 = other.m[7];
  1338. var om8 = other.m[8];
  1339. var om9 = other.m[9];
  1340. var om10 = other.m[10];
  1341. var om11 = other.m[11];
  1342. var om12 = other.m[12];
  1343. var om13 = other.m[13];
  1344. var om14 = other.m[14];
  1345. var om15 = other.m[15];
  1346. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1347. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1348. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1349. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1350. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1351. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1352. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1353. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1354. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1355. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1356. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1357. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1358. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1359. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1360. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1361. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1362. };
  1363. Matrix.prototype.equals = function (value) {
  1364. 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]);
  1365. };
  1366. Matrix.prototype.clone = function () {
  1367. 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]);
  1368. };
  1369. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1370. translation.x = this.m[12];
  1371. translation.y = this.m[13];
  1372. translation.z = this.m[14];
  1373. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1374. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1375. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1376. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1377. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1378. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1379. if (scale.x == 0 || scale.y == 0 || scale.z == 0) {
  1380. rotation.x = 0;
  1381. rotation.y = 0;
  1382. rotation.z = 0;
  1383. rotation.w = 1;
  1384. return false;
  1385. }
  1386. var rotationMatrix = BABYLON.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);
  1387. rotation.fromRotationMatrix(rotationMatrix);
  1388. return true;
  1389. };
  1390. // Statics
  1391. Matrix.FromArray = function (array, offset) {
  1392. var result = new Matrix();
  1393. if (!offset) {
  1394. offset = 0;
  1395. }
  1396. Matrix.FromArrayToRef(array, offset, result);
  1397. return result;
  1398. };
  1399. Matrix.FromArrayToRef = function (array, offset, result) {
  1400. for (var index = 0; index < 16; index++) {
  1401. result.m[index] = array[index + offset];
  1402. }
  1403. };
  1404. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1405. result.m[0] = initialM11;
  1406. result.m[1] = initialM12;
  1407. result.m[2] = initialM13;
  1408. result.m[3] = initialM14;
  1409. result.m[4] = initialM21;
  1410. result.m[5] = initialM22;
  1411. result.m[6] = initialM23;
  1412. result.m[7] = initialM24;
  1413. result.m[8] = initialM31;
  1414. result.m[9] = initialM32;
  1415. result.m[10] = initialM33;
  1416. result.m[11] = initialM34;
  1417. result.m[12] = initialM41;
  1418. result.m[13] = initialM42;
  1419. result.m[14] = initialM43;
  1420. result.m[15] = initialM44;
  1421. };
  1422. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1423. var result = new Matrix();
  1424. result.m[0] = initialM11;
  1425. result.m[1] = initialM12;
  1426. result.m[2] = initialM13;
  1427. result.m[3] = initialM14;
  1428. result.m[4] = initialM21;
  1429. result.m[5] = initialM22;
  1430. result.m[6] = initialM23;
  1431. result.m[7] = initialM24;
  1432. result.m[8] = initialM31;
  1433. result.m[9] = initialM32;
  1434. result.m[10] = initialM33;
  1435. result.m[11] = initialM34;
  1436. result.m[12] = initialM41;
  1437. result.m[13] = initialM42;
  1438. result.m[14] = initialM43;
  1439. result.m[15] = initialM44;
  1440. return result;
  1441. };
  1442. Matrix.Compose = function (scale, rotation, translation) {
  1443. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1444. var rotationMatrix = Matrix.Identity();
  1445. rotation.toRotationMatrix(rotationMatrix);
  1446. result = result.multiply(rotationMatrix);
  1447. result.setTranslation(translation);
  1448. return result;
  1449. };
  1450. Matrix.Identity = function () {
  1451. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1452. };
  1453. Matrix.IdentityToRef = function (result) {
  1454. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1455. };
  1456. Matrix.Zero = function () {
  1457. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1458. };
  1459. Matrix.RotationX = function (angle) {
  1460. var result = new Matrix();
  1461. Matrix.RotationXToRef(angle, result);
  1462. return result;
  1463. };
  1464. Matrix.Invert = function (source) {
  1465. var result = new Matrix();
  1466. source.invertToRef(result);
  1467. return result;
  1468. };
  1469. Matrix.RotationXToRef = function (angle, result) {
  1470. var s = Math.sin(angle);
  1471. var c = Math.cos(angle);
  1472. result.m[0] = 1.0;
  1473. result.m[15] = 1.0;
  1474. result.m[5] = c;
  1475. result.m[10] = c;
  1476. result.m[9] = -s;
  1477. result.m[6] = s;
  1478. result.m[1] = 0;
  1479. result.m[2] = 0;
  1480. result.m[3] = 0;
  1481. result.m[4] = 0;
  1482. result.m[7] = 0;
  1483. result.m[8] = 0;
  1484. result.m[11] = 0;
  1485. result.m[12] = 0;
  1486. result.m[13] = 0;
  1487. result.m[14] = 0;
  1488. };
  1489. Matrix.RotationY = function (angle) {
  1490. var result = new Matrix();
  1491. Matrix.RotationYToRef(angle, result);
  1492. return result;
  1493. };
  1494. Matrix.RotationYToRef = function (angle, result) {
  1495. var s = Math.sin(angle);
  1496. var c = Math.cos(angle);
  1497. result.m[5] = 1.0;
  1498. result.m[15] = 1.0;
  1499. result.m[0] = c;
  1500. result.m[2] = -s;
  1501. result.m[8] = s;
  1502. result.m[10] = c;
  1503. result.m[1] = 0;
  1504. result.m[3] = 0;
  1505. result.m[4] = 0;
  1506. result.m[6] = 0;
  1507. result.m[7] = 0;
  1508. result.m[9] = 0;
  1509. result.m[11] = 0;
  1510. result.m[12] = 0;
  1511. result.m[13] = 0;
  1512. result.m[14] = 0;
  1513. };
  1514. Matrix.RotationZ = function (angle) {
  1515. var result = new Matrix();
  1516. Matrix.RotationZToRef(angle, result);
  1517. return result;
  1518. };
  1519. Matrix.RotationZToRef = function (angle, result) {
  1520. var s = Math.sin(angle);
  1521. var c = Math.cos(angle);
  1522. result.m[10] = 1.0;
  1523. result.m[15] = 1.0;
  1524. result.m[0] = c;
  1525. result.m[1] = s;
  1526. result.m[4] = -s;
  1527. result.m[5] = c;
  1528. result.m[2] = 0;
  1529. result.m[3] = 0;
  1530. result.m[6] = 0;
  1531. result.m[7] = 0;
  1532. result.m[8] = 0;
  1533. result.m[9] = 0;
  1534. result.m[11] = 0;
  1535. result.m[12] = 0;
  1536. result.m[13] = 0;
  1537. result.m[14] = 0;
  1538. };
  1539. Matrix.RotationAxis = function (axis, angle) {
  1540. var s = Math.sin(-angle);
  1541. var c = Math.cos(-angle);
  1542. var c1 = 1 - c;
  1543. axis.normalize();
  1544. var result = Matrix.Zero();
  1545. result.m[0] = (axis.x * axis.x) * c1 + c;
  1546. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1547. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1548. result.m[3] = 0.0;
  1549. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1550. result.m[5] = (axis.y * axis.y) * c1 + c;
  1551. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1552. result.m[7] = 0.0;
  1553. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1554. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1555. result.m[10] = (axis.z * axis.z) * c1 + c;
  1556. result.m[11] = 0.0;
  1557. result.m[15] = 1.0;
  1558. return result;
  1559. };
  1560. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1561. var result = new Matrix();
  1562. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1563. return result;
  1564. };
  1565. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1566. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1567. this._tempQuaternion.toRotationMatrix(result);
  1568. };
  1569. Matrix.Scaling = function (x, y, z) {
  1570. var result = Matrix.Zero();
  1571. Matrix.ScalingToRef(x, y, z, result);
  1572. return result;
  1573. };
  1574. Matrix.ScalingToRef = function (x, y, z, result) {
  1575. result.m[0] = x;
  1576. result.m[1] = 0;
  1577. result.m[2] = 0;
  1578. result.m[3] = 0;
  1579. result.m[4] = 0;
  1580. result.m[5] = y;
  1581. result.m[6] = 0;
  1582. result.m[7] = 0;
  1583. result.m[8] = 0;
  1584. result.m[9] = 0;
  1585. result.m[10] = z;
  1586. result.m[11] = 0;
  1587. result.m[12] = 0;
  1588. result.m[13] = 0;
  1589. result.m[14] = 0;
  1590. result.m[15] = 1.0;
  1591. };
  1592. Matrix.Translation = function (x, y, z) {
  1593. var result = Matrix.Identity();
  1594. Matrix.TranslationToRef(x, y, z, result);
  1595. return result;
  1596. };
  1597. Matrix.TranslationToRef = function (x, y, z, result) {
  1598. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1599. };
  1600. Matrix.LookAtLH = function (eye, target, up) {
  1601. var result = Matrix.Zero();
  1602. Matrix.LookAtLHToRef(eye, target, up, result);
  1603. return result;
  1604. };
  1605. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1606. // Z axis
  1607. target.subtractToRef(eye, this._zAxis);
  1608. this._zAxis.normalize();
  1609. // X axis
  1610. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1611. this._xAxis.normalize();
  1612. // Y axis
  1613. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1614. this._yAxis.normalize();
  1615. // Eye angles
  1616. var ex = -Vector3.Dot(this._xAxis, eye);
  1617. var ey = -Vector3.Dot(this._yAxis, eye);
  1618. var ez = -Vector3.Dot(this._zAxis, eye);
  1619. 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);
  1620. };
  1621. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1622. var hw = 2.0 / width;
  1623. var hh = 2.0 / height;
  1624. var id = 1.0 / (zfar - znear);
  1625. var nid = znear / (znear - zfar);
  1626. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1627. };
  1628. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1629. var matrix = Matrix.Zero();
  1630. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1631. return matrix;
  1632. };
  1633. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1634. result.m[0] = 2.0 / (right - left);
  1635. result.m[1] = result.m[2] = result.m[3] = 0;
  1636. result.m[5] = 2.0 / (top - bottom);
  1637. result.m[4] = result.m[6] = result.m[7] = 0;
  1638. result.m[10] = -1.0 / (znear - zfar);
  1639. result.m[8] = result.m[9] = result.m[11] = 0;
  1640. result.m[12] = (left + right) / (left - right);
  1641. result.m[13] = (top + bottom) / (bottom - top);
  1642. result.m[14] = znear / (znear - zfar);
  1643. result.m[15] = 1.0;
  1644. };
  1645. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1646. var matrix = Matrix.Zero();
  1647. matrix.m[0] = (2.0 * znear) / width;
  1648. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1649. matrix.m[5] = (2.0 * znear) / height;
  1650. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1651. matrix.m[10] = -zfar / (znear - zfar);
  1652. matrix.m[8] = matrix.m[9] = 0.0;
  1653. matrix.m[11] = 1.0;
  1654. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1655. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1656. return matrix;
  1657. };
  1658. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1659. var matrix = Matrix.Zero();
  1660. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1661. return matrix;
  1662. };
  1663. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1664. var tan = 1.0 / (Math.tan(fov * 0.5));
  1665. result.m[0] = tan / aspect;
  1666. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1667. result.m[5] = tan;
  1668. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1669. result.m[8] = result.m[9] = 0.0;
  1670. result.m[10] = -zfar / (znear - zfar);
  1671. result.m[11] = 1.0;
  1672. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1673. result.m[14] = (znear * zfar) / (znear - zfar);
  1674. };
  1675. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1676. var cw = viewport.width;
  1677. var ch = viewport.height;
  1678. var cx = viewport.x;
  1679. var cy = viewport.y;
  1680. 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);
  1681. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1682. };
  1683. Matrix.Transpose = function (matrix) {
  1684. var result = new Matrix();
  1685. result.m[0] = matrix.m[0];
  1686. result.m[1] = matrix.m[4];
  1687. result.m[2] = matrix.m[8];
  1688. result.m[3] = matrix.m[12];
  1689. result.m[4] = matrix.m[1];
  1690. result.m[5] = matrix.m[5];
  1691. result.m[6] = matrix.m[9];
  1692. result.m[7] = matrix.m[13];
  1693. result.m[8] = matrix.m[2];
  1694. result.m[9] = matrix.m[6];
  1695. result.m[10] = matrix.m[10];
  1696. result.m[11] = matrix.m[14];
  1697. result.m[12] = matrix.m[3];
  1698. result.m[13] = matrix.m[7];
  1699. result.m[14] = matrix.m[11];
  1700. result.m[15] = matrix.m[15];
  1701. return result;
  1702. };
  1703. Matrix.Reflection = function (plane) {
  1704. var matrix = new Matrix();
  1705. Matrix.ReflectionToRef(plane, matrix);
  1706. return matrix;
  1707. };
  1708. Matrix.ReflectionToRef = function (plane, result) {
  1709. plane.normalize();
  1710. var x = plane.normal.x;
  1711. var y = plane.normal.y;
  1712. var z = plane.normal.z;
  1713. var temp = -2 * x;
  1714. var temp2 = -2 * y;
  1715. var temp3 = -2 * z;
  1716. result.m[0] = (temp * x) + 1;
  1717. result.m[1] = temp2 * x;
  1718. result.m[2] = temp3 * x;
  1719. result.m[3] = 0.0;
  1720. result.m[4] = temp * y;
  1721. result.m[5] = (temp2 * y) + 1;
  1722. result.m[6] = temp3 * y;
  1723. result.m[7] = 0.0;
  1724. result.m[8] = temp * z;
  1725. result.m[9] = temp2 * z;
  1726. result.m[10] = (temp3 * z) + 1;
  1727. result.m[11] = 0.0;
  1728. result.m[12] = temp * plane.d;
  1729. result.m[13] = temp2 * plane.d;
  1730. result.m[14] = temp3 * plane.d;
  1731. result.m[15] = 1.0;
  1732. };
  1733. Matrix._tempQuaternion = new Quaternion();
  1734. Matrix._xAxis = Vector3.Zero();
  1735. Matrix._yAxis = Vector3.Zero();
  1736. Matrix._zAxis = Vector3.Zero();
  1737. return Matrix;
  1738. })();
  1739. BABYLON.Matrix = Matrix;
  1740. var Plane = (function () {
  1741. function Plane(a, b, c, d) {
  1742. this.normal = new Vector3(a, b, c);
  1743. this.d = d;
  1744. }
  1745. Plane.prototype.asArray = function () {
  1746. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1747. };
  1748. // Methods
  1749. Plane.prototype.clone = function () {
  1750. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1751. };
  1752. Plane.prototype.normalize = function () {
  1753. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1754. var magnitude = 0;
  1755. if (norm !== 0) {
  1756. magnitude = 1.0 / norm;
  1757. }
  1758. this.normal.x *= magnitude;
  1759. this.normal.y *= magnitude;
  1760. this.normal.z *= magnitude;
  1761. this.d *= magnitude;
  1762. };
  1763. Plane.prototype.transform = function (transformation) {
  1764. var transposedMatrix = Matrix.Transpose(transformation);
  1765. var x = this.normal.x;
  1766. var y = this.normal.y;
  1767. var z = this.normal.z;
  1768. var d = this.d;
  1769. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1770. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1771. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1772. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1773. return new Plane(normalX, normalY, normalZ, finalD);
  1774. };
  1775. Plane.prototype.dotCoordinate = function (point) {
  1776. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1777. };
  1778. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1779. var x1 = point2.x - point1.x;
  1780. var y1 = point2.y - point1.y;
  1781. var z1 = point2.z - point1.z;
  1782. var x2 = point3.x - point1.x;
  1783. var y2 = point3.y - point1.y;
  1784. var z2 = point3.z - point1.z;
  1785. var yz = (y1 * z2) - (z1 * y2);
  1786. var xz = (z1 * x2) - (x1 * z2);
  1787. var xy = (x1 * y2) - (y1 * x2);
  1788. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1789. var invPyth;
  1790. if (pyth !== 0) {
  1791. invPyth = 1.0 / pyth;
  1792. } else {
  1793. invPyth = 0;
  1794. }
  1795. this.normal.x = yz * invPyth;
  1796. this.normal.y = xz * invPyth;
  1797. this.normal.z = xy * invPyth;
  1798. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1799. };
  1800. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1801. var dot = Vector3.Dot(this.normal, direction);
  1802. return (dot <= epsilon);
  1803. };
  1804. Plane.prototype.signedDistanceTo = function (point) {
  1805. return Vector3.Dot(point, this.normal) + this.d;
  1806. };
  1807. // Statics
  1808. Plane.FromArray = function (array) {
  1809. return new Plane(array[0], array[1], array[2], array[3]);
  1810. };
  1811. Plane.FromPoints = function (point1, point2, point3) {
  1812. var result = new Plane(0, 0, 0, 0);
  1813. result.copyFromPoints(point1, point2, point3);
  1814. return result;
  1815. };
  1816. Plane.FromPositionAndNormal = function (origin, normal) {
  1817. var result = new Plane(0, 0, 0, 0);
  1818. normal.normalize();
  1819. result.normal = normal;
  1820. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1821. return result;
  1822. };
  1823. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1824. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1825. return Vector3.Dot(point, normal) + d;
  1826. };
  1827. return Plane;
  1828. })();
  1829. BABYLON.Plane = Plane;
  1830. var Viewport = (function () {
  1831. function Viewport(x, y, width, height) {
  1832. this.x = x;
  1833. this.y = y;
  1834. this.width = width;
  1835. this.height = height;
  1836. }
  1837. Viewport.prototype.toGlobal = function (engine) {
  1838. var width = engine.getRenderWidth();
  1839. var height = engine.getRenderHeight();
  1840. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1841. };
  1842. return Viewport;
  1843. })();
  1844. BABYLON.Viewport = Viewport;
  1845. var Frustum = (function () {
  1846. function Frustum() {
  1847. }
  1848. Frustum.GetPlanes = function (transform) {
  1849. var frustumPlanes = [];
  1850. for (var index = 0; index < 6; index++) {
  1851. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1852. }
  1853. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1854. return frustumPlanes;
  1855. };
  1856. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1857. // Near
  1858. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1859. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1860. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1861. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1862. frustumPlanes[0].normalize();
  1863. // Far
  1864. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1865. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1866. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1867. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1868. frustumPlanes[1].normalize();
  1869. // Left
  1870. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1871. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1872. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1873. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1874. frustumPlanes[2].normalize();
  1875. // Right
  1876. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1877. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1878. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1879. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1880. frustumPlanes[3].normalize();
  1881. // Top
  1882. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1883. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1884. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1885. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1886. frustumPlanes[4].normalize();
  1887. // Bottom
  1888. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1889. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1890. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1891. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1892. frustumPlanes[5].normalize();
  1893. };
  1894. return Frustum;
  1895. })();
  1896. BABYLON.Frustum = Frustum;
  1897. var Ray = (function () {
  1898. function Ray(origin, direction, length) {
  1899. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1900. this.origin = origin;
  1901. this.direction = direction;
  1902. this.length = length;
  1903. }
  1904. // Methods
  1905. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1906. var d = 0.0;
  1907. var maxValue = Number.MAX_VALUE;
  1908. if (Math.abs(this.direction.x) < 0.0000001) {
  1909. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1910. return false;
  1911. }
  1912. } else {
  1913. var inv = 1.0 / this.direction.x;
  1914. var min = (minimum.x - this.origin.x) * inv;
  1915. var max = (maximum.x - this.origin.x) * inv;
  1916. if (max === -Infinity) {
  1917. max = Infinity;
  1918. }
  1919. if (min > max) {
  1920. var temp = min;
  1921. min = max;
  1922. max = temp;
  1923. }
  1924. d = Math.max(min, d);
  1925. maxValue = Math.min(max, maxValue);
  1926. if (d > maxValue) {
  1927. return false;
  1928. }
  1929. }
  1930. if (Math.abs(this.direction.y) < 0.0000001) {
  1931. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1932. return false;
  1933. }
  1934. } else {
  1935. inv = 1.0 / this.direction.y;
  1936. min = (minimum.y - this.origin.y) * inv;
  1937. max = (maximum.y - this.origin.y) * inv;
  1938. if (max === -Infinity) {
  1939. max = Infinity;
  1940. }
  1941. if (min > max) {
  1942. temp = min;
  1943. min = max;
  1944. max = temp;
  1945. }
  1946. d = Math.max(min, d);
  1947. maxValue = Math.min(max, maxValue);
  1948. if (d > maxValue) {
  1949. return false;
  1950. }
  1951. }
  1952. if (Math.abs(this.direction.z) < 0.0000001) {
  1953. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1954. return false;
  1955. }
  1956. } else {
  1957. inv = 1.0 / this.direction.z;
  1958. min = (minimum.z - this.origin.z) * inv;
  1959. max = (maximum.z - this.origin.z) * inv;
  1960. if (max === -Infinity) {
  1961. max = Infinity;
  1962. }
  1963. if (min > max) {
  1964. temp = min;
  1965. min = max;
  1966. max = temp;
  1967. }
  1968. d = Math.max(min, d);
  1969. maxValue = Math.min(max, maxValue);
  1970. if (d > maxValue) {
  1971. return false;
  1972. }
  1973. }
  1974. return true;
  1975. };
  1976. Ray.prototype.intersectsBox = function (box) {
  1977. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1978. };
  1979. Ray.prototype.intersectsSphere = function (sphere) {
  1980. var x = sphere.center.x - this.origin.x;
  1981. var y = sphere.center.y - this.origin.y;
  1982. var z = sphere.center.z - this.origin.z;
  1983. var pyth = (x * x) + (y * y) + (z * z);
  1984. var rr = sphere.radius * sphere.radius;
  1985. if (pyth <= rr) {
  1986. return true;
  1987. }
  1988. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1989. if (dot < 0.0) {
  1990. return false;
  1991. }
  1992. var temp = pyth - (dot * dot);
  1993. return temp <= rr;
  1994. };
  1995. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1996. if (!this._edge1) {
  1997. this._edge1 = Vector3.Zero();
  1998. this._edge2 = Vector3.Zero();
  1999. this._pvec = Vector3.Zero();
  2000. this._tvec = Vector3.Zero();
  2001. this._qvec = Vector3.Zero();
  2002. }
  2003. vertex1.subtractToRef(vertex0, this._edge1);
  2004. vertex2.subtractToRef(vertex0, this._edge2);
  2005. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2006. var det = Vector3.Dot(this._edge1, this._pvec);
  2007. if (det === 0) {
  2008. return null;
  2009. }
  2010. var invdet = 1 / det;
  2011. this.origin.subtractToRef(vertex0, this._tvec);
  2012. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2013. if (bu < 0 || bu > 1.0) {
  2014. return null;
  2015. }
  2016. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2017. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2018. if (bv < 0 || bu + bv > 1.0) {
  2019. return null;
  2020. }
  2021. //check if the distance is longer than the predefined length.
  2022. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2023. if (distance > this.length) {
  2024. return null;
  2025. }
  2026. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2027. };
  2028. // Statics
  2029. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2030. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2031. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2032. var direction = end.subtract(start);
  2033. direction.normalize();
  2034. return new Ray(start, direction);
  2035. };
  2036. /**
  2037. * 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
  2038. * transformed to the given world matrix.
  2039. * @param origin The origin point
  2040. * @param end The end point
  2041. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2042. */
  2043. Ray.CreateNewFromTo = function (origin, end, world) {
  2044. if (typeof world === "undefined") { world = Matrix.Identity(); }
  2045. var direction = end.subtract(origin);
  2046. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2047. direction.normalize();
  2048. return Ray.Transform(new Ray(origin, direction, length), world);
  2049. };
  2050. Ray.Transform = function (ray, matrix) {
  2051. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2052. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2053. return new Ray(newOrigin, newDirection, ray.length);
  2054. };
  2055. return Ray;
  2056. })();
  2057. BABYLON.Ray = Ray;
  2058. (function (Space) {
  2059. Space[Space["LOCAL"] = 0] = "LOCAL";
  2060. Space[Space["WORLD"] = 1] = "WORLD";
  2061. })(BABYLON.Space || (BABYLON.Space = {}));
  2062. var Space = BABYLON.Space;
  2063. var Axis = (function () {
  2064. function Axis() {
  2065. }
  2066. Axis.X = new Vector3(1, 0, 0);
  2067. Axis.Y = new Vector3(0, 1, 0);
  2068. Axis.Z = new Vector3(0, 0, 1);
  2069. return Axis;
  2070. })();
  2071. BABYLON.Axis = Axis;
  2072. ;
  2073. var BezierCurve = (function () {
  2074. function BezierCurve() {
  2075. }
  2076. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2077. // Extract X (which is equal to time here)
  2078. var f0 = 1 - 3 * x2 + 3 * x1;
  2079. var f1 = 3 * x2 - 6 * x1;
  2080. var f2 = 3 * x1;
  2081. var refinedT = t;
  2082. for (var i = 0; i < 5; i++) {
  2083. var refinedT2 = refinedT * refinedT;
  2084. var refinedT3 = refinedT2 * refinedT;
  2085. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2086. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2087. refinedT -= (x - t) * slope;
  2088. refinedT = Math.min(1, Math.max(0, refinedT));
  2089. }
  2090. // Resolve cubic bezier for the given x
  2091. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2092. };
  2093. return BezierCurve;
  2094. })();
  2095. BABYLON.BezierCurve = BezierCurve;
  2096. (function (Orientation) {
  2097. Orientation[Orientation["CW"] = 0] = "CW";
  2098. Orientation[Orientation["CCW"] = 1] = "CCW";
  2099. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2100. var Orientation = BABYLON.Orientation;
  2101. var Angle = (function () {
  2102. function Angle(radians) {
  2103. var _this = this;
  2104. this.degrees = function () {
  2105. return _this._radians * 180 / Math.PI;
  2106. };
  2107. this.radians = function () {
  2108. return _this._radians;
  2109. };
  2110. this._radians = radians;
  2111. if (this._radians < 0)
  2112. this._radians += (2 * Math.PI);
  2113. }
  2114. Angle.BetweenTwoPoints = function (a, b) {
  2115. var delta = b.subtract(a);
  2116. var theta = Math.atan2(delta.y, delta.x);
  2117. return new Angle(theta);
  2118. };
  2119. Angle.FromRadians = function (radians) {
  2120. return new Angle(radians);
  2121. };
  2122. Angle.FromDegrees = function (degrees) {
  2123. return new Angle(degrees * Math.PI / 180);
  2124. };
  2125. return Angle;
  2126. })();
  2127. BABYLON.Angle = Angle;
  2128. var Arc2 = (function () {
  2129. function Arc2(startPoint, midPoint, endPoint) {
  2130. this.startPoint = startPoint;
  2131. this.midPoint = midPoint;
  2132. this.endPoint = endPoint;
  2133. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2134. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2135. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2136. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2137. 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);
  2138. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2139. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2140. var a1 = this.startAngle.degrees();
  2141. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2142. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2143. // angles correction
  2144. if (a2 - a1 > +180.0)
  2145. a2 -= 360.0;
  2146. if (a2 - a1 < -180.0)
  2147. a2 += 360.0;
  2148. if (a3 - a2 > +180.0)
  2149. a3 -= 360.0;
  2150. if (a3 - a2 < -180.0)
  2151. a3 += 360.0;
  2152. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2153. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2154. }
  2155. return Arc2;
  2156. })();
  2157. BABYLON.Arc2 = Arc2;
  2158. var PathCursor = (function () {
  2159. function PathCursor(path) {
  2160. this.path = path;
  2161. this._onchange = new Array();
  2162. this.value = 0;
  2163. this.animations = new Array();
  2164. }
  2165. PathCursor.prototype.getPoint = function () {
  2166. var point = this.path.getPointAtLengthPosition(this.value);
  2167. return new Vector3(point.x, 0, point.y);
  2168. };
  2169. PathCursor.prototype.moveAhead = function (step) {
  2170. if (typeof step === "undefined") { step = 0.002; }
  2171. this.move(step);
  2172. };
  2173. PathCursor.prototype.moveBack = function (step) {
  2174. if (typeof step === "undefined") { step = 0.002; }
  2175. this.move(-step);
  2176. };
  2177. PathCursor.prototype.move = function (step) {
  2178. if (Math.abs(step) > 1) {
  2179. throw "step size should be less than 1.";
  2180. }
  2181. this.value += step;
  2182. this.ensureLimits();
  2183. this.raiseOnChange();
  2184. };
  2185. PathCursor.prototype.ensureLimits = function () {
  2186. while (this.value > 1) {
  2187. this.value -= 1;
  2188. }
  2189. while (this.value < 0) {
  2190. this.value += 1;
  2191. }
  2192. };
  2193. // used by animation engine
  2194. PathCursor.prototype.markAsDirty = function (propertyName) {
  2195. this.ensureLimits();
  2196. this.raiseOnChange();
  2197. };
  2198. PathCursor.prototype.raiseOnChange = function () {
  2199. var _this = this;
  2200. this._onchange.forEach(function (f) {
  2201. return f(_this);
  2202. });
  2203. };
  2204. PathCursor.prototype.onchange = function (f) {
  2205. this._onchange.push(f);
  2206. };
  2207. return PathCursor;
  2208. })();
  2209. BABYLON.PathCursor = PathCursor;
  2210. var Path2 = (function () {
  2211. function Path2(x, y) {
  2212. this._points = [];
  2213. this._length = 0;
  2214. this.closed = false;
  2215. this._points.push(new Vector2(x, y));
  2216. }
  2217. Path2.prototype.addLineTo = function (x, y) {
  2218. if (closed) {
  2219. BABYLON.Tools.Error("cannot add lines to closed paths");
  2220. return this;
  2221. }
  2222. var newPoint = new Vector2(x, y);
  2223. var previousPoint = this._points[this._points.length - 1];
  2224. this._points.push(newPoint);
  2225. this._length += newPoint.subtract(previousPoint).length();
  2226. return this;
  2227. };
  2228. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2229. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2230. if (closed) {
  2231. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2232. return this;
  2233. }
  2234. var startPoint = this._points[this._points.length - 1];
  2235. var midPoint = new Vector2(midX, midY);
  2236. var endPoint = new Vector2(endX, endY);
  2237. var arc = new Arc2(startPoint, midPoint, endPoint);
  2238. var increment = arc.angle.radians() / numberOfSegments;
  2239. if (arc.orientation === 0 /* CW */)
  2240. increment *= -1;
  2241. var currentAngle = arc.startAngle.radians() + increment;
  2242. for (var i = 0; i < numberOfSegments; i++) {
  2243. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2244. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2245. this.addLineTo(x, y);
  2246. currentAngle += increment;
  2247. }
  2248. return this;
  2249. };
  2250. Path2.prototype.close = function () {
  2251. this.closed = true;
  2252. return this;
  2253. };
  2254. Path2.prototype.length = function () {
  2255. var result = this._length;
  2256. if (!this.closed) {
  2257. var lastPoint = this._points[this._points.length - 1];
  2258. var firstPoint = this._points[0];
  2259. result += (firstPoint.subtract(lastPoint).length());
  2260. }
  2261. return result;
  2262. };
  2263. Path2.prototype.getPoints = function () {
  2264. return this._points;
  2265. };
  2266. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2267. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2268. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2269. return;
  2270. }
  2271. var lengthPosition = normalizedLengthPosition * this.length();
  2272. var previousOffset = 0;
  2273. for (var i = 0; i < this._points.length; i++) {
  2274. var j = (i + 1) % this._points.length;
  2275. var a = this._points[i];
  2276. var b = this._points[j];
  2277. var bToA = b.subtract(a);
  2278. var nextOffset = (bToA.length() + previousOffset);
  2279. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2280. var dir = bToA.normalize();
  2281. var localOffset = lengthPosition - previousOffset;
  2282. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2283. }
  2284. previousOffset = nextOffset;
  2285. }
  2286. BABYLON.Tools.Error("internal error");
  2287. };
  2288. Path2.StartingAt = function (x, y) {
  2289. return new Path2(x, y);
  2290. };
  2291. return Path2;
  2292. })();
  2293. BABYLON.Path2 = Path2;
  2294. })(BABYLON || (BABYLON = {}));
  2295. //# sourceMappingURL=babylon.math.js.map
  2296. var BABYLON;
  2297. (function (BABYLON) {
  2298. // Screenshots
  2299. var screenshotCanvas;
  2300. var cloneValue = function (source, destinationObject) {
  2301. if (!source)
  2302. return null;
  2303. if (source instanceof BABYLON.Mesh) {
  2304. return null;
  2305. }
  2306. if (source instanceof BABYLON.SubMesh) {
  2307. return source.clone(destinationObject);
  2308. } else if (source.clone) {
  2309. return source.clone();
  2310. }
  2311. return null;
  2312. };
  2313. var Tools = (function () {
  2314. function Tools() {
  2315. }
  2316. Tools.GetFilename = function (path) {
  2317. var index = path.lastIndexOf("/");
  2318. if (index < 0)
  2319. return path;
  2320. return path.substring(index + 1);
  2321. };
  2322. Tools.GetDOMTextContent = function (element) {
  2323. var result = "";
  2324. var child = element.firstChild;
  2325. while (child) {
  2326. if (child.nodeType == 3) {
  2327. result += child.textContent;
  2328. }
  2329. child = child.nextSibling;
  2330. }
  2331. return result;
  2332. };
  2333. Tools.ToDegrees = function (angle) {
  2334. return angle * 180 / Math.PI;
  2335. };
  2336. Tools.ToRadians = function (angle) {
  2337. return angle * Math.PI / 180;
  2338. };
  2339. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2340. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2341. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2342. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2343. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2344. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2345. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2346. }
  2347. return {
  2348. minimum: minimum,
  2349. maximum: maximum
  2350. };
  2351. };
  2352. Tools.ExtractMinAndMax = function (positions, start, count) {
  2353. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2354. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2355. for (var index = start; index < start + count; index++) {
  2356. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2357. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2358. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2359. }
  2360. return {
  2361. minimum: minimum,
  2362. maximum: maximum
  2363. };
  2364. };
  2365. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2366. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2367. return undefined;
  2368. return Array.isArray(obj) ? obj : [obj];
  2369. };
  2370. // Misc.
  2371. Tools.GetPointerPrefix = function () {
  2372. var eventPrefix = "pointer";
  2373. // Check if hand.js is referenced or if the browser natively supports pointer events
  2374. if (!navigator.pointerEnabled) {
  2375. eventPrefix = "mouse";
  2376. }
  2377. return eventPrefix;
  2378. };
  2379. Tools.QueueNewFrame = function (func) {
  2380. if (window.requestAnimationFrame)
  2381. window.requestAnimationFrame(func);
  2382. else if (window.msRequestAnimationFrame)
  2383. window.msRequestAnimationFrame(func);
  2384. else if (window.webkitRequestAnimationFrame)
  2385. window.webkitRequestAnimationFrame(func);
  2386. else if (window.mozRequestAnimationFrame)
  2387. window.mozRequestAnimationFrame(func);
  2388. else if (window.oRequestAnimationFrame)
  2389. window.oRequestAnimationFrame(func);
  2390. else {
  2391. window.setTimeout(func, 16);
  2392. }
  2393. };
  2394. Tools.RequestFullscreen = function (element) {
  2395. if (element.requestFullscreen)
  2396. element.requestFullscreen();
  2397. else if (element.msRequestFullscreen)
  2398. element.msRequestFullscreen();
  2399. else if (element.webkitRequestFullscreen)
  2400. element.webkitRequestFullscreen();
  2401. else if (element.mozRequestFullScreen)
  2402. element.mozRequestFullScreen();
  2403. };
  2404. Tools.ExitFullscreen = function () {
  2405. if (document.exitFullscreen) {
  2406. document.exitFullscreen();
  2407. } else if (document.mozCancelFullScreen) {
  2408. document.mozCancelFullScreen();
  2409. } else if (document.webkitCancelFullScreen) {
  2410. document.webkitCancelFullScreen();
  2411. } else if (document.msCancelFullScreen) {
  2412. document.msCancelFullScreen();
  2413. }
  2414. };
  2415. // External files
  2416. Tools.CleanUrl = function (url) {
  2417. url = url.replace(/#/mg, "%23");
  2418. return url;
  2419. };
  2420. Tools.LoadImage = function (url, onload, onerror, database) {
  2421. url = Tools.CleanUrl(url);
  2422. var img = new Image();
  2423. if (url.substr(0, 5) != "data:")
  2424. img.crossOrigin = 'anonymous';
  2425. img.onload = function () {
  2426. onload(img);
  2427. };
  2428. img.onerror = function (err) {
  2429. onerror(img, err);
  2430. };
  2431. var noIndexedDB = function () {
  2432. img.src = url;
  2433. };
  2434. var loadFromIndexedDB = function () {
  2435. database.loadImageFromDB(url, img);
  2436. };
  2437. //ANY database to do!
  2438. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2439. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2440. } else {
  2441. if (url.indexOf("file:") === -1) {
  2442. noIndexedDB();
  2443. } else {
  2444. try {
  2445. var textureName = url.substring(5);
  2446. var blobURL;
  2447. try {
  2448. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2449. } catch (ex) {
  2450. // Chrome doesn't support oneTimeOnly parameter
  2451. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2452. }
  2453. img.src = blobURL;
  2454. } catch (e) {
  2455. Tools.Log("Error while trying to load texture: " + textureName);
  2456. img.src = null;
  2457. }
  2458. }
  2459. }
  2460. return img;
  2461. };
  2462. //ANY
  2463. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2464. url = Tools.CleanUrl(url);
  2465. var noIndexedDB = function () {
  2466. var request = new XMLHttpRequest();
  2467. var loadUrl = Tools.BaseUrl + url;
  2468. request.open('GET', loadUrl, true);
  2469. if (useArrayBuffer) {
  2470. request.responseType = "arraybuffer";
  2471. }
  2472. request.onprogress = progressCallBack;
  2473. request.onreadystatechange = function () {
  2474. if (request.readyState == 4) {
  2475. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2476. callback(!useArrayBuffer ? request.responseText : request.response);
  2477. } else {
  2478. if (onError) {
  2479. onError();
  2480. } else {
  2481. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2482. }
  2483. }
  2484. }
  2485. };
  2486. request.send(null);
  2487. };
  2488. var loadFromIndexedDB = function () {
  2489. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2490. };
  2491. if (url.indexOf("file:") !== -1) {
  2492. var fileName = url.substring(5);
  2493. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2494. } else {
  2495. // Caching all files
  2496. if (database && database.enableSceneOffline) {
  2497. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2498. } else {
  2499. noIndexedDB();
  2500. }
  2501. }
  2502. };
  2503. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2504. var reader = new FileReader();
  2505. reader.onload = function (e) {
  2506. callback(e.target.result);
  2507. };
  2508. reader.onprogress = progressCallback;
  2509. reader.readAsDataURL(fileToLoad);
  2510. };
  2511. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2512. var reader = new FileReader();
  2513. reader.onload = function (e) {
  2514. callback(e.target.result);
  2515. };
  2516. reader.onprogress = progressCallBack;
  2517. if (!useArrayBuffer) {
  2518. // Asynchronous read
  2519. reader.readAsText(fileToLoad);
  2520. } else {
  2521. reader.readAsArrayBuffer(fileToLoad);
  2522. }
  2523. };
  2524. // Misc.
  2525. Tools.Clamp = function (value, min, max) {
  2526. if (typeof min === "undefined") { min = 0; }
  2527. if (typeof max === "undefined") { max = 1; }
  2528. return Math.min(max, Math.max(min, value));
  2529. };
  2530. // Returns -1 when value is a negative number and
  2531. // +1 when value is a positive number.
  2532. Tools.Sign = function (value) {
  2533. value = +value; // convert to a number
  2534. if (value === 0 || isNaN(value))
  2535. return value;
  2536. return value > 0 ? 1 : -1;
  2537. };
  2538. Tools.Format = function (value, decimals) {
  2539. if (typeof decimals === "undefined") { decimals = 2; }
  2540. return value.toFixed(decimals);
  2541. };
  2542. Tools.CheckExtends = function (v, min, max) {
  2543. if (v.x < min.x)
  2544. min.x = v.x;
  2545. if (v.y < min.y)
  2546. min.y = v.y;
  2547. if (v.z < min.z)
  2548. min.z = v.z;
  2549. if (v.x > max.x)
  2550. max.x = v.x;
  2551. if (v.y > max.y)
  2552. max.y = v.y;
  2553. if (v.z > max.z)
  2554. max.z = v.z;
  2555. };
  2556. Tools.WithinEpsilon = function (a, b, epsilon) {
  2557. if (typeof epsilon === "undefined") { epsilon = 1.401298E-45; }
  2558. var num = a - b;
  2559. return -epsilon <= num && num <= epsilon;
  2560. };
  2561. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2562. for (var prop in source) {
  2563. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2564. continue;
  2565. }
  2566. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2567. continue;
  2568. }
  2569. var sourceValue = source[prop];
  2570. var typeOfSourceValue = typeof sourceValue;
  2571. if (typeOfSourceValue == "function") {
  2572. continue;
  2573. }
  2574. if (typeOfSourceValue == "object") {
  2575. if (sourceValue instanceof Array) {
  2576. destination[prop] = [];
  2577. if (sourceValue.length > 0) {
  2578. if (typeof sourceValue[0] == "object") {
  2579. for (var index = 0; index < sourceValue.length; index++) {
  2580. var clonedValue = cloneValue(sourceValue[index], destination);
  2581. if (destination[prop].indexOf(clonedValue) === -1) {
  2582. destination[prop].push(clonedValue);
  2583. }
  2584. }
  2585. } else {
  2586. destination[prop] = sourceValue.slice(0);
  2587. }
  2588. }
  2589. } else {
  2590. destination[prop] = cloneValue(sourceValue, destination);
  2591. }
  2592. } else {
  2593. destination[prop] = sourceValue;
  2594. }
  2595. }
  2596. };
  2597. Tools.IsEmpty = function (obj) {
  2598. for (var i in obj) {
  2599. return false;
  2600. }
  2601. return true;
  2602. };
  2603. Tools.RegisterTopRootEvents = function (events) {
  2604. for (var index = 0; index < events.length; index++) {
  2605. var event = events[index];
  2606. window.addEventListener(event.name, event.handler, false);
  2607. try {
  2608. if (window.parent) {
  2609. window.parent.addEventListener(event.name, event.handler, false);
  2610. }
  2611. } catch (e) {
  2612. // Silently fails...
  2613. }
  2614. }
  2615. };
  2616. Tools.UnregisterTopRootEvents = function (events) {
  2617. for (var index = 0; index < events.length; index++) {
  2618. var event = events[index];
  2619. window.removeEventListener(event.name, event.handler);
  2620. try {
  2621. if (window.parent) {
  2622. window.parent.removeEventListener(event.name, event.handler);
  2623. }
  2624. } catch (e) {
  2625. // Silently fails...
  2626. }
  2627. }
  2628. };
  2629. Tools.CreateScreenshot = function (engine, camera, size) {
  2630. var width;
  2631. var height;
  2632. var scene = camera.getScene();
  2633. var previousCamera = null;
  2634. if (scene.activeCamera !== camera) {
  2635. previousCamera = scene.activeCamera;
  2636. scene.activeCamera = camera;
  2637. }
  2638. //If a precision value is specified
  2639. if (size.precision) {
  2640. width = Math.round(engine.getRenderWidth() * size.precision);
  2641. height = Math.round(width / engine.getAspectRatio(camera));
  2642. size = { width: width, height: height };
  2643. } else if (size.width && size.height) {
  2644. width = size.width;
  2645. height = size.height;
  2646. } else if (size.width && !size.height) {
  2647. width = size.width;
  2648. height = Math.round(width / engine.getAspectRatio(camera));
  2649. size = { width: width, height: height };
  2650. } else if (size.height && !size.width) {
  2651. height = size.height;
  2652. width = Math.round(height * engine.getAspectRatio(camera));
  2653. size = { width: width, height: height };
  2654. } else if (!isNaN(size)) {
  2655. height = size;
  2656. width = size;
  2657. } else {
  2658. Tools.Error("Invalid 'size' parameter !");
  2659. return;
  2660. }
  2661. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2662. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2663. texture.renderList = scene.meshes;
  2664. texture.onAfterRender = function () {
  2665. // Read the contents of the framebuffer
  2666. var numberOfChannelsByLine = width * 4;
  2667. var halfHeight = height / 2;
  2668. //Reading datas from WebGL
  2669. var data = engine.readPixels(0, 0, width, height);
  2670. for (var i = 0; i < halfHeight; i++) {
  2671. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2672. var currentCell = j + i * numberOfChannelsByLine;
  2673. var targetLine = height - i - 1;
  2674. var targetCell = j + targetLine * numberOfChannelsByLine;
  2675. var temp = data[currentCell];
  2676. data[currentCell] = data[targetCell];
  2677. data[targetCell] = temp;
  2678. }
  2679. }
  2680. // Create a 2D canvas to store the result
  2681. if (!screenshotCanvas) {
  2682. screenshotCanvas = document.createElement('canvas');
  2683. }
  2684. screenshotCanvas.width = width;
  2685. screenshotCanvas.height = height;
  2686. var context = screenshotCanvas.getContext('2d');
  2687. // Copy the pixels to a 2D canvas
  2688. var imageData = context.createImageData(width, height);
  2689. imageData.data.set(data);
  2690. context.putImageData(imageData, 0, 0);
  2691. var base64Image = screenshotCanvas.toDataURL();
  2692. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2693. if (("download" in document.createElement("a"))) {
  2694. var a = window.document.createElement("a");
  2695. a.href = base64Image;
  2696. var date = new Date();
  2697. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2698. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2699. window.document.body.appendChild(a);
  2700. a.addEventListener("click", function () {
  2701. a.parentElement.removeChild(a);
  2702. });
  2703. a.click();
  2704. //Or opening a new tab with the image if it is not possible to automatically start download.
  2705. } else {
  2706. var newWindow = window.open("");
  2707. var img = newWindow.document.createElement("img");
  2708. img.src = base64Image;
  2709. newWindow.document.body.appendChild(img);
  2710. }
  2711. };
  2712. texture.render(true);
  2713. texture.dispose();
  2714. if (previousCamera) {
  2715. scene.activeCamera = previousCamera;
  2716. }
  2717. };
  2718. // XHR response validator for local file scenario
  2719. Tools.ValidateXHRData = function (xhr, dataType) {
  2720. if (typeof dataType === "undefined") { dataType = 7; }
  2721. try {
  2722. if (dataType & 1) {
  2723. if (xhr.responseText && xhr.responseText.length > 0) {
  2724. return true;
  2725. } else if (dataType === 1) {
  2726. return false;
  2727. }
  2728. }
  2729. if (dataType & 2) {
  2730. // Check header width and height since there is no "TGA" magic number
  2731. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2732. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2733. return true;
  2734. } else if (dataType === 2) {
  2735. return false;
  2736. }
  2737. }
  2738. if (dataType & 4) {
  2739. // Check for the "DDS" magic number
  2740. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2741. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2742. return true;
  2743. } else {
  2744. return false;
  2745. }
  2746. }
  2747. } catch (e) {
  2748. // Global protection
  2749. }
  2750. return false;
  2751. };
  2752. Object.defineProperty(Tools, "NoneLogLevel", {
  2753. get: function () {
  2754. return Tools._NoneLogLevel;
  2755. },
  2756. enumerable: true,
  2757. configurable: true
  2758. });
  2759. Object.defineProperty(Tools, "MessageLogLevel", {
  2760. get: function () {
  2761. return Tools._MessageLogLevel;
  2762. },
  2763. enumerable: true,
  2764. configurable: true
  2765. });
  2766. Object.defineProperty(Tools, "WarningLogLevel", {
  2767. get: function () {
  2768. return Tools._WarningLogLevel;
  2769. },
  2770. enumerable: true,
  2771. configurable: true
  2772. });
  2773. Object.defineProperty(Tools, "ErrorLogLevel", {
  2774. get: function () {
  2775. return Tools._ErrorLogLevel;
  2776. },
  2777. enumerable: true,
  2778. configurable: true
  2779. });
  2780. Object.defineProperty(Tools, "AllLogLevel", {
  2781. get: function () {
  2782. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2783. },
  2784. enumerable: true,
  2785. configurable: true
  2786. });
  2787. Tools._AddLogEntry = function (entry) {
  2788. Tools._LogCache = entry + Tools._LogCache;
  2789. if (Tools.OnNewCacheEntry) {
  2790. Tools.OnNewCacheEntry(entry);
  2791. }
  2792. };
  2793. Tools._FormatMessage = function (message) {
  2794. var padStr = function (i) {
  2795. return (i < 10) ? "0" + i : "" + i;
  2796. };
  2797. var date = new Date();
  2798. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2799. };
  2800. Tools._LogDisabled = function (message) {
  2801. // nothing to do
  2802. };
  2803. Tools._LogEnabled = function (message) {
  2804. var formattedMessage = Tools._FormatMessage(message);
  2805. console.log("BJS - " + formattedMessage);
  2806. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2807. Tools._AddLogEntry(entry);
  2808. };
  2809. Tools._WarnDisabled = function (message) {
  2810. // nothing to do
  2811. };
  2812. Tools._WarnEnabled = function (message) {
  2813. var formattedMessage = Tools._FormatMessage(message);
  2814. console.warn("BJS - " + formattedMessage);
  2815. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2816. Tools._AddLogEntry(entry);
  2817. };
  2818. Tools._ErrorDisabled = function (message) {
  2819. // nothing to do
  2820. };
  2821. Tools._ErrorEnabled = function (message) {
  2822. var formattedMessage = Tools._FormatMessage(message);
  2823. console.error("BJS - " + formattedMessage);
  2824. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2825. Tools._AddLogEntry(entry);
  2826. };
  2827. Object.defineProperty(Tools, "LogCache", {
  2828. get: function () {
  2829. return Tools._LogCache;
  2830. },
  2831. enumerable: true,
  2832. configurable: true
  2833. });
  2834. Object.defineProperty(Tools, "LogLevels", {
  2835. set: function (level) {
  2836. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2837. Tools.Log = Tools._LogEnabled;
  2838. } else {
  2839. Tools.Log = Tools._LogDisabled;
  2840. }
  2841. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2842. Tools.Warn = Tools._WarnEnabled;
  2843. } else {
  2844. Tools.Warn = Tools._WarnDisabled;
  2845. }
  2846. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2847. Tools.Error = Tools._ErrorEnabled;
  2848. } else {
  2849. Tools.Error = Tools._ErrorDisabled;
  2850. }
  2851. },
  2852. enumerable: true,
  2853. configurable: true
  2854. });
  2855. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2856. get: function () {
  2857. return Tools._PerformanceNoneLogLevel;
  2858. },
  2859. enumerable: true,
  2860. configurable: true
  2861. });
  2862. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2863. get: function () {
  2864. return Tools._PerformanceUserMarkLogLevel;
  2865. },
  2866. enumerable: true,
  2867. configurable: true
  2868. });
  2869. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2870. get: function () {
  2871. return Tools._PerformanceConsoleLogLevel;
  2872. },
  2873. enumerable: true,
  2874. configurable: true
  2875. });
  2876. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2877. set: function (level) {
  2878. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2879. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2880. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2881. return;
  2882. }
  2883. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2884. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2885. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2886. return;
  2887. }
  2888. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2889. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2890. },
  2891. enumerable: true,
  2892. configurable: true
  2893. });
  2894. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2895. };
  2896. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2897. };
  2898. Tools._StartUserMark = function (counterName, condition) {
  2899. if (typeof condition === "undefined") { condition = true; }
  2900. if (!condition || !Tools._performance.mark) {
  2901. return;
  2902. }
  2903. Tools._performance.mark(counterName + "-Begin");
  2904. };
  2905. Tools._EndUserMark = function (counterName, condition) {
  2906. if (typeof condition === "undefined") { condition = true; }
  2907. if (!condition || !Tools._performance.mark) {
  2908. return;
  2909. }
  2910. Tools._performance.mark(counterName + "-End");
  2911. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2912. };
  2913. Tools._StartPerformanceConsole = function (counterName, condition) {
  2914. if (typeof condition === "undefined") { condition = true; }
  2915. if (!condition) {
  2916. return;
  2917. }
  2918. Tools._StartUserMark(counterName, condition);
  2919. if (console.time) {
  2920. console.time(counterName);
  2921. }
  2922. };
  2923. Tools._EndPerformanceConsole = function (counterName, condition) {
  2924. if (typeof condition === "undefined") { condition = true; }
  2925. if (!condition) {
  2926. return;
  2927. }
  2928. Tools._EndUserMark(counterName, condition);
  2929. if (console.time) {
  2930. console.timeEnd(counterName);
  2931. }
  2932. };
  2933. Object.defineProperty(Tools, "Now", {
  2934. get: function () {
  2935. if (window.performance && window.performance.now) {
  2936. return window.performance.now();
  2937. }
  2938. return new Date().getTime();
  2939. },
  2940. enumerable: true,
  2941. configurable: true
  2942. });
  2943. // Deprecated
  2944. Tools.GetFps = function () {
  2945. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2946. return 0;
  2947. };
  2948. Tools.BaseUrl = "";
  2949. Tools.GetExponantOfTwo = function (value, max) {
  2950. var count = 1;
  2951. do {
  2952. count *= 2;
  2953. } while(count < value);
  2954. if (count > max)
  2955. count = max;
  2956. return count;
  2957. };
  2958. Tools._NoneLogLevel = 0;
  2959. Tools._MessageLogLevel = 1;
  2960. Tools._WarningLogLevel = 2;
  2961. Tools._ErrorLogLevel = 4;
  2962. Tools._LogCache = "";
  2963. Tools.Log = Tools._LogEnabled;
  2964. Tools.Warn = Tools._WarnEnabled;
  2965. Tools.Error = Tools._ErrorEnabled;
  2966. Tools._PerformanceNoneLogLevel = 0;
  2967. Tools._PerformanceUserMarkLogLevel = 1;
  2968. Tools._PerformanceConsoleLogLevel = 2;
  2969. Tools._performance = window.performance;
  2970. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2971. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2972. return Tools;
  2973. })();
  2974. BABYLON.Tools = Tools;
  2975. /**
  2976. * An implementation of a loop for asynchronous functions.
  2977. */
  2978. var AsyncLoop = (function () {
  2979. /**
  2980. * Constroctor.
  2981. * @param iterations the number of iterations.
  2982. * @param _fn the function to run each iteration
  2983. * @param _successCallback the callback that will be called upon succesful execution
  2984. * @param offset starting offset.
  2985. */
  2986. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  2987. if (typeof offset === "undefined") { offset = 0; }
  2988. this.iterations = iterations;
  2989. this._fn = _fn;
  2990. this._successCallback = _successCallback;
  2991. this.index = offset - 1;
  2992. this._done = false;
  2993. }
  2994. /**
  2995. * Execute the next iteration. Must be called after the last iteration was finished.
  2996. */
  2997. AsyncLoop.prototype.executeNext = function () {
  2998. if (!this._done) {
  2999. if (this.index + 1 < this.iterations) {
  3000. ++this.index;
  3001. this._fn(this);
  3002. } else {
  3003. this.breakLoop();
  3004. }
  3005. }
  3006. };
  3007. /**
  3008. * Break the loop and run the success callback.
  3009. */
  3010. AsyncLoop.prototype.breakLoop = function () {
  3011. this._done = true;
  3012. this._successCallback();
  3013. };
  3014. /**
  3015. * Helper function
  3016. */
  3017. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3018. if (typeof offset === "undefined") { offset = 0; }
  3019. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3020. loop.executeNext();
  3021. return loop;
  3022. };
  3023. /**
  3024. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3025. * @param iterations total number of iterations
  3026. * @param syncedIterations number of synchronous iterations in each async iteration.
  3027. * @param fn the function to call each iteration.
  3028. * @param callback a success call back that will be called when iterating stops.
  3029. * @param breakFunction a break condition (optional)
  3030. * @param timeout timeout settings for the setTimeout function. default - 0.
  3031. * @constructor
  3032. */
  3033. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3034. if (typeof timeout === "undefined") { timeout = 0; }
  3035. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3036. if (breakFunction && breakFunction())
  3037. loop.breakLoop();
  3038. else {
  3039. setTimeout(function () {
  3040. for (var i = 0; i < syncedIterations; ++i) {
  3041. var iteration = (loop.index * syncedIterations) + i;
  3042. if (iteration >= iterations)
  3043. break;
  3044. fn(iteration);
  3045. if (breakFunction && breakFunction()) {
  3046. loop.breakLoop();
  3047. break;
  3048. }
  3049. }
  3050. loop.executeNext();
  3051. }, timeout);
  3052. }
  3053. }, callback);
  3054. };
  3055. return AsyncLoop;
  3056. })();
  3057. BABYLON.AsyncLoop = AsyncLoop;
  3058. })(BABYLON || (BABYLON = {}));
  3059. //# sourceMappingURL=babylon.tools.js.map
  3060. var BABYLON;
  3061. (function (BABYLON) {
  3062. var _DepthCullingState = (function () {
  3063. function _DepthCullingState() {
  3064. this._isDepthTestDirty = false;
  3065. this._isDepthMaskDirty = false;
  3066. this._isDepthFuncDirty = false;
  3067. this._isCullFaceDirty = false;
  3068. this._isCullDirty = false;
  3069. }
  3070. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3071. get: function () {
  3072. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3073. },
  3074. enumerable: true,
  3075. configurable: true
  3076. });
  3077. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3078. get: function () {
  3079. return this._cullFace;
  3080. },
  3081. set: function (value) {
  3082. if (this._cullFace === value) {
  3083. return;
  3084. }
  3085. this._cullFace = value;
  3086. this._isCullFaceDirty = true;
  3087. },
  3088. enumerable: true,
  3089. configurable: true
  3090. });
  3091. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3092. get: function () {
  3093. return this._cull;
  3094. },
  3095. set: function (value) {
  3096. if (this._cull === value) {
  3097. return;
  3098. }
  3099. this._cull = value;
  3100. this._isCullDirty = true;
  3101. },
  3102. enumerable: true,
  3103. configurable: true
  3104. });
  3105. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3106. get: function () {
  3107. return this._depthFunc;
  3108. },
  3109. set: function (value) {
  3110. if (this._depthFunc === value) {
  3111. return;
  3112. }
  3113. this._depthFunc = value;
  3114. this._isDepthFuncDirty = true;
  3115. },
  3116. enumerable: true,
  3117. configurable: true
  3118. });
  3119. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3120. get: function () {
  3121. return this._depthMask;
  3122. },
  3123. set: function (value) {
  3124. if (this._depthMask === value) {
  3125. return;
  3126. }
  3127. this._depthMask = value;
  3128. this._isDepthMaskDirty = true;
  3129. },
  3130. enumerable: true,
  3131. configurable: true
  3132. });
  3133. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3134. get: function () {
  3135. return this._depthTest;
  3136. },
  3137. set: function (value) {
  3138. if (this._depthTest === value) {
  3139. return;
  3140. }
  3141. this._depthTest = value;
  3142. this._isDepthTestDirty = true;
  3143. },
  3144. enumerable: true,
  3145. configurable: true
  3146. });
  3147. _DepthCullingState.prototype.reset = function () {
  3148. this._depthMask = true;
  3149. this._depthTest = true;
  3150. this._depthFunc = null;
  3151. this._cull = null;
  3152. this._cullFace = null;
  3153. this._isDepthTestDirty = true;
  3154. this._isDepthMaskDirty = true;
  3155. this._isDepthFuncDirty = false;
  3156. this._isCullFaceDirty = false;
  3157. this._isCullDirty = false;
  3158. };
  3159. _DepthCullingState.prototype.apply = function (gl) {
  3160. if (!this.isDirty) {
  3161. return;
  3162. }
  3163. // Cull
  3164. if (this._isCullDirty) {
  3165. if (this.cull) {
  3166. gl.enable(gl.CULL_FACE);
  3167. } else {
  3168. gl.disable(gl.CULL_FACE);
  3169. }
  3170. this._isCullDirty = false;
  3171. }
  3172. // Cull face
  3173. if (this._isCullFaceDirty) {
  3174. gl.cullFace(this.cullFace);
  3175. this._isCullFaceDirty = false;
  3176. }
  3177. // Depth mask
  3178. if (this._isDepthMaskDirty) {
  3179. gl.depthMask(this.depthMask);
  3180. this._isDepthMaskDirty = false;
  3181. }
  3182. // Depth test
  3183. if (this._isDepthTestDirty) {
  3184. if (this.depthTest) {
  3185. gl.enable(gl.DEPTH_TEST);
  3186. } else {
  3187. gl.disable(gl.DEPTH_TEST);
  3188. }
  3189. this._isDepthTestDirty = false;
  3190. }
  3191. // Depth func
  3192. if (this._isDepthFuncDirty) {
  3193. gl.depthFunc(this.depthFunc);
  3194. this._isDepthFuncDirty = false;
  3195. }
  3196. };
  3197. return _DepthCullingState;
  3198. })();
  3199. BABYLON._DepthCullingState = _DepthCullingState;
  3200. var _AlphaState = (function () {
  3201. function _AlphaState() {
  3202. this._isAlphaBlendDirty = false;
  3203. this._isBlendFunctionParametersDirty = false;
  3204. this._alphaBlend = false;
  3205. this._blendFunctionParameters = new Array(4);
  3206. }
  3207. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3208. get: function () {
  3209. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3210. },
  3211. enumerable: true,
  3212. configurable: true
  3213. });
  3214. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3215. get: function () {
  3216. return this._alphaBlend;
  3217. },
  3218. set: function (value) {
  3219. if (this._alphaBlend === value) {
  3220. return;
  3221. }
  3222. this._alphaBlend = value;
  3223. this._isAlphaBlendDirty = true;
  3224. },
  3225. enumerable: true,
  3226. configurable: true
  3227. });
  3228. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3229. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3230. return;
  3231. }
  3232. this._blendFunctionParameters[0] = value0;
  3233. this._blendFunctionParameters[1] = value1;
  3234. this._blendFunctionParameters[2] = value2;
  3235. this._blendFunctionParameters[3] = value3;
  3236. this._isBlendFunctionParametersDirty = true;
  3237. };
  3238. _AlphaState.prototype.reset = function () {
  3239. this._alphaBlend = false;
  3240. this._blendFunctionParameters[0] = null;
  3241. this._blendFunctionParameters[1] = null;
  3242. this._blendFunctionParameters[2] = null;
  3243. this._blendFunctionParameters[3] = null;
  3244. this._isAlphaBlendDirty = true;
  3245. this._isBlendFunctionParametersDirty = false;
  3246. };
  3247. _AlphaState.prototype.apply = function (gl) {
  3248. if (!this.isDirty) {
  3249. return;
  3250. }
  3251. // Alpha blend
  3252. if (this._isAlphaBlendDirty) {
  3253. if (this._alphaBlend) {
  3254. gl.enable(gl.BLEND);
  3255. } else {
  3256. gl.disable(gl.BLEND);
  3257. }
  3258. this._isAlphaBlendDirty = false;
  3259. }
  3260. // Alpha function
  3261. if (this._isBlendFunctionParametersDirty) {
  3262. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3263. this._isBlendFunctionParametersDirty = false;
  3264. }
  3265. };
  3266. return _AlphaState;
  3267. })();
  3268. BABYLON._AlphaState = _AlphaState;
  3269. var compileShader = function (gl, source, type, defines) {
  3270. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3271. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3272. gl.compileShader(shader);
  3273. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3274. throw new Error(gl.getShaderInfoLog(shader));
  3275. }
  3276. return shader;
  3277. };
  3278. var getWebGLTextureType = function (gl, type) {
  3279. var textureType = gl.UNSIGNED_BYTE;
  3280. if (type === Engine.TEXTURETYPE_FLOAT)
  3281. textureType = gl.FLOAT;
  3282. return textureType;
  3283. };
  3284. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3285. var magFilter = gl.NEAREST;
  3286. var minFilter = gl.NEAREST;
  3287. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3288. magFilter = gl.LINEAR;
  3289. if (generateMipMaps) {
  3290. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3291. } else {
  3292. minFilter = gl.LINEAR;
  3293. }
  3294. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3295. magFilter = gl.LINEAR;
  3296. if (generateMipMaps) {
  3297. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3298. } else {
  3299. minFilter = gl.LINEAR;
  3300. }
  3301. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3302. magFilter = gl.NEAREST;
  3303. if (generateMipMaps) {
  3304. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3305. } else {
  3306. minFilter = gl.NEAREST;
  3307. }
  3308. }
  3309. return {
  3310. min: minFilter,
  3311. mag: magFilter
  3312. };
  3313. };
  3314. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3315. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3316. var engine = scene.getEngine();
  3317. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3318. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3319. gl.bindTexture(gl.TEXTURE_2D, texture);
  3320. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3321. processFunction(potWidth, potHeight);
  3322. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3323. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3324. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3325. if (!noMipmap && !isCompressed) {
  3326. gl.generateMipmap(gl.TEXTURE_2D);
  3327. }
  3328. gl.bindTexture(gl.TEXTURE_2D, null);
  3329. engine._activeTexturesCache = [];
  3330. texture._baseWidth = width;
  3331. texture._baseHeight = height;
  3332. texture._width = potWidth;
  3333. texture._height = potHeight;
  3334. texture.isReady = true;
  3335. texture.samplingMode = samplingMode;
  3336. scene._removePendingData(texture);
  3337. };
  3338. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3339. var onload = function () {
  3340. loadedImages[index] = img;
  3341. loadedImages._internalCount++;
  3342. scene._removePendingData(img);
  3343. if (loadedImages._internalCount === 6) {
  3344. onfinish(loadedImages);
  3345. }
  3346. };
  3347. var onerror = function () {
  3348. scene._removePendingData(img);
  3349. };
  3350. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3351. scene._addPendingData(img);
  3352. };
  3353. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3354. var loadedImages = [];
  3355. loadedImages._internalCount = 0;
  3356. for (var index = 0; index < 6; index++) {
  3357. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3358. }
  3359. };
  3360. var EngineCapabilities = (function () {
  3361. function EngineCapabilities() {
  3362. }
  3363. return EngineCapabilities;
  3364. })();
  3365. BABYLON.EngineCapabilities = EngineCapabilities;
  3366. var Engine = (function () {
  3367. function Engine(canvas, antialias, options) {
  3368. var _this = this;
  3369. // Public members
  3370. this.isFullscreen = false;
  3371. this.isPointerLock = false;
  3372. this.cullBackFaces = true;
  3373. this.renderEvenInBackground = true;
  3374. this.scenes = new Array();
  3375. this._windowIsBackground = false;
  3376. this._loadingDivBackgroundColor = "black";
  3377. this._drawCalls = 0;
  3378. this._renderingQueueLaunched = false;
  3379. this._activeRenderLoops = [];
  3380. // FPS
  3381. this.fpsRange = 60;
  3382. this.previousFramesDuration = [];
  3383. this.fps = 60;
  3384. this.deltaTime = 0;
  3385. // States
  3386. this._depthCullingState = new _DepthCullingState();
  3387. this._alphaState = new _AlphaState();
  3388. this._alphaMode = Engine.ALPHA_DISABLE;
  3389. // Cache
  3390. this._loadedTexturesCache = new Array();
  3391. this._activeTexturesCache = new Array();
  3392. this._compiledEffects = {};
  3393. this._uintIndicesCurrentlySet = false;
  3394. this._renderingCanvas = canvas;
  3395. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3396. options = options || {};
  3397. options.antialias = antialias;
  3398. try {
  3399. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3400. } catch (e) {
  3401. throw new Error("WebGL not supported");
  3402. }
  3403. if (!this._gl) {
  3404. throw new Error("WebGL not supported");
  3405. }
  3406. this._onBlur = function () {
  3407. _this._windowIsBackground = true;
  3408. };
  3409. this._onFocus = function () {
  3410. _this._windowIsBackground = false;
  3411. };
  3412. window.addEventListener("blur", this._onBlur);
  3413. window.addEventListener("focus", this._onFocus);
  3414. // Textures
  3415. this._workingCanvas = document.createElement("canvas");
  3416. this._workingContext = this._workingCanvas.getContext("2d");
  3417. // Viewport
  3418. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3419. this.resize();
  3420. // Caps
  3421. this._caps = new EngineCapabilities();
  3422. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3423. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3424. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3425. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3426. // Infos
  3427. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3428. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3429. if (rendererInfo != null) {
  3430. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3431. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3432. }
  3433. if (!this._glVendor) {
  3434. this._glVendor = "Unknown vendor";
  3435. }
  3436. if (!this._glRenderer) {
  3437. this._glRenderer = "Unknown renderer";
  3438. }
  3439. // Extensions
  3440. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3441. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3442. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3443. 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');
  3444. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3445. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3446. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3447. // Depth buffer
  3448. this.setDepthBuffer(true);
  3449. this.setDepthFunctionToLessOrEqual();
  3450. this.setDepthWrite(true);
  3451. // Fullscreen
  3452. this._onFullscreenChange = function () {
  3453. if (document.fullscreen !== undefined) {
  3454. _this.isFullscreen = document.fullscreen;
  3455. } else if (document.mozFullScreen !== undefined) {
  3456. _this.isFullscreen = document.mozFullScreen;
  3457. } else if (document.webkitIsFullScreen !== undefined) {
  3458. _this.isFullscreen = document.webkitIsFullScreen;
  3459. } else if (document.msIsFullScreen !== undefined) {
  3460. _this.isFullscreen = document.msIsFullScreen;
  3461. }
  3462. // Pointer lock
  3463. if (_this.isFullscreen && _this._pointerLockRequested) {
  3464. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3465. if (canvas.requestPointerLock) {
  3466. canvas.requestPointerLock();
  3467. }
  3468. }
  3469. };
  3470. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3471. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3472. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3473. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3474. // Pointer lock
  3475. this._onPointerLockChange = function () {
  3476. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3477. };
  3478. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3479. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3480. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3481. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3482. this._audioEngine = new BABYLON.AudioEngine();
  3483. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3484. }
  3485. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3486. get: function () {
  3487. return Engine._ALPHA_DISABLE;
  3488. },
  3489. enumerable: true,
  3490. configurable: true
  3491. });
  3492. Object.defineProperty(Engine, "ALPHA_ADD", {
  3493. get: function () {
  3494. return Engine._ALPHA_ADD;
  3495. },
  3496. enumerable: true,
  3497. configurable: true
  3498. });
  3499. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3500. get: function () {
  3501. return Engine._ALPHA_COMBINE;
  3502. },
  3503. enumerable: true,
  3504. configurable: true
  3505. });
  3506. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3507. get: function () {
  3508. return Engine._DELAYLOADSTATE_NONE;
  3509. },
  3510. enumerable: true,
  3511. configurable: true
  3512. });
  3513. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3514. get: function () {
  3515. return Engine._DELAYLOADSTATE_LOADED;
  3516. },
  3517. enumerable: true,
  3518. configurable: true
  3519. });
  3520. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3521. get: function () {
  3522. return Engine._DELAYLOADSTATE_LOADING;
  3523. },
  3524. enumerable: true,
  3525. configurable: true
  3526. });
  3527. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3528. get: function () {
  3529. return Engine._DELAYLOADSTATE_NOTLOADED;
  3530. },
  3531. enumerable: true,
  3532. configurable: true
  3533. });
  3534. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3535. get: function () {
  3536. return Engine._TEXTUREFORMAT_ALPHA;
  3537. },
  3538. enumerable: true,
  3539. configurable: true
  3540. });
  3541. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3542. get: function () {
  3543. return Engine._TEXTUREFORMAT_LUMINANCE;
  3544. },
  3545. enumerable: true,
  3546. configurable: true
  3547. });
  3548. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3549. get: function () {
  3550. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3551. },
  3552. enumerable: true,
  3553. configurable: true
  3554. });
  3555. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3556. get: function () {
  3557. return Engine._TEXTUREFORMAT_RGB;
  3558. },
  3559. enumerable: true,
  3560. configurable: true
  3561. });
  3562. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3563. get: function () {
  3564. return Engine._TEXTUREFORMAT_RGBA;
  3565. },
  3566. enumerable: true,
  3567. configurable: true
  3568. });
  3569. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3570. get: function () {
  3571. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3572. },
  3573. enumerable: true,
  3574. configurable: true
  3575. });
  3576. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3577. get: function () {
  3578. return Engine._TEXTURETYPE_FLOAT;
  3579. },
  3580. enumerable: true,
  3581. configurable: true
  3582. });
  3583. Object.defineProperty(Engine, "Version", {
  3584. get: function () {
  3585. return "2.0.0";
  3586. },
  3587. enumerable: true,
  3588. configurable: true
  3589. });
  3590. Engine.prototype.getGlInfo = function () {
  3591. return {
  3592. vendor: this._glVendor,
  3593. renderer: this._glRenderer,
  3594. version: this._glVersion
  3595. };
  3596. };
  3597. Engine.prototype.getAudioEngine = function () {
  3598. return this._audioEngine;
  3599. };
  3600. Engine.prototype.getAspectRatio = function (camera) {
  3601. var viewport = camera.viewport;
  3602. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3603. };
  3604. Engine.prototype.getRenderWidth = function () {
  3605. if (this._currentRenderTarget) {
  3606. return this._currentRenderTarget._width;
  3607. }
  3608. return this._renderingCanvas.width;
  3609. };
  3610. Engine.prototype.getRenderHeight = function () {
  3611. if (this._currentRenderTarget) {
  3612. return this._currentRenderTarget._height;
  3613. }
  3614. return this._renderingCanvas.height;
  3615. };
  3616. Engine.prototype.getRenderingCanvas = function () {
  3617. return this._renderingCanvas;
  3618. };
  3619. Engine.prototype.getRenderingCanvasClientRect = function () {
  3620. return this._renderingCanvas.getBoundingClientRect();
  3621. };
  3622. Engine.prototype.setHardwareScalingLevel = function (level) {
  3623. this._hardwareScalingLevel = level;
  3624. this.resize();
  3625. };
  3626. Engine.prototype.getHardwareScalingLevel = function () {
  3627. return this._hardwareScalingLevel;
  3628. };
  3629. Engine.prototype.getLoadedTexturesCache = function () {
  3630. return this._loadedTexturesCache;
  3631. };
  3632. Engine.prototype.getCaps = function () {
  3633. return this._caps;
  3634. };
  3635. Object.defineProperty(Engine.prototype, "drawCalls", {
  3636. get: function () {
  3637. return this._drawCalls;
  3638. },
  3639. enumerable: true,
  3640. configurable: true
  3641. });
  3642. // Methods
  3643. Engine.prototype.resetDrawCalls = function () {
  3644. this._drawCalls = 0;
  3645. };
  3646. Engine.prototype.setDepthFunctionToGreater = function () {
  3647. this._depthCullingState.depthFunc = this._gl.GREATER;
  3648. };
  3649. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3650. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3651. };
  3652. Engine.prototype.setDepthFunctionToLess = function () {
  3653. this._depthCullingState.depthFunc = this._gl.LESS;
  3654. };
  3655. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3656. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3657. };
  3658. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3659. if (!renderFunction) {
  3660. this._activeRenderLoops = [];
  3661. return;
  3662. }
  3663. var index = this._activeRenderLoops.indexOf(renderFunction);
  3664. if (index >= 0) {
  3665. this._activeRenderLoops.splice(index, 1);
  3666. }
  3667. };
  3668. Engine.prototype._renderLoop = function () {
  3669. var _this = this;
  3670. var shouldRender = true;
  3671. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3672. shouldRender = false;
  3673. }
  3674. if (shouldRender) {
  3675. // Start new frame
  3676. this.beginFrame();
  3677. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3678. var renderFunction = this._activeRenderLoops[index];
  3679. renderFunction();
  3680. }
  3681. // Present
  3682. this.endFrame();
  3683. }
  3684. if (this._activeRenderLoops.length > 0) {
  3685. // Register new frame
  3686. BABYLON.Tools.QueueNewFrame(function () {
  3687. _this._renderLoop();
  3688. });
  3689. } else {
  3690. this._renderingQueueLaunched = false;
  3691. }
  3692. };
  3693. Engine.prototype.runRenderLoop = function (renderFunction) {
  3694. var _this = this;
  3695. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3696. return;
  3697. }
  3698. this._activeRenderLoops.push(renderFunction);
  3699. if (!this._renderingQueueLaunched) {
  3700. this._renderingQueueLaunched = true;
  3701. BABYLON.Tools.QueueNewFrame(function () {
  3702. _this._renderLoop();
  3703. });
  3704. }
  3705. };
  3706. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3707. if (this.isFullscreen) {
  3708. BABYLON.Tools.ExitFullscreen();
  3709. } else {
  3710. this._pointerLockRequested = requestPointerLock;
  3711. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3712. }
  3713. };
  3714. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3715. this.applyStates();
  3716. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3717. if (this._depthCullingState.depthMask) {
  3718. this._gl.clearDepth(1.0);
  3719. }
  3720. var mode = 0;
  3721. if (backBuffer)
  3722. mode |= this._gl.COLOR_BUFFER_BIT;
  3723. if (depthStencil && this._depthCullingState.depthMask)
  3724. mode |= this._gl.DEPTH_BUFFER_BIT;
  3725. this._gl.clear(mode);
  3726. };
  3727. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3728. var width = requiredWidth || this._renderingCanvas.width;
  3729. var height = requiredHeight || this._renderingCanvas.height;
  3730. var x = viewport.x || 0;
  3731. var y = viewport.y || 0;
  3732. this._cachedViewport = viewport;
  3733. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3734. };
  3735. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3736. this._cachedViewport = null;
  3737. this._gl.viewport(x, y, width, height);
  3738. };
  3739. Engine.prototype.beginFrame = function () {
  3740. this._measureFps();
  3741. };
  3742. Engine.prototype.endFrame = function () {
  3743. this.flushFramebuffer();
  3744. };
  3745. Engine.prototype.resize = function () {
  3746. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3747. };
  3748. Engine.prototype.setSize = function (width, height) {
  3749. this._renderingCanvas.width = width;
  3750. this._renderingCanvas.height = height;
  3751. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3752. };
  3753. Engine.prototype.bindFramebuffer = function (texture) {
  3754. this._currentRenderTarget = texture;
  3755. var gl = this._gl;
  3756. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3757. this._gl.viewport(0, 0, texture._width, texture._height);
  3758. this.wipeCaches();
  3759. };
  3760. Engine.prototype.unBindFramebuffer = function (texture) {
  3761. this._currentRenderTarget = null;
  3762. if (texture.generateMipMaps) {
  3763. var gl = this._gl;
  3764. gl.bindTexture(gl.TEXTURE_2D, texture);
  3765. gl.generateMipmap(gl.TEXTURE_2D);
  3766. gl.bindTexture(gl.TEXTURE_2D, null);
  3767. }
  3768. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3769. };
  3770. Engine.prototype.flushFramebuffer = function () {
  3771. // this._gl.flush();
  3772. };
  3773. Engine.prototype.restoreDefaultFramebuffer = function () {
  3774. this._currentRenderTarget = null;
  3775. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3776. this.setViewport(this._cachedViewport);
  3777. this.wipeCaches();
  3778. };
  3779. // VBOs
  3780. Engine.prototype._resetVertexBufferBinding = function () {
  3781. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3782. this._cachedVertexBuffers = null;
  3783. };
  3784. Engine.prototype.createVertexBuffer = function (vertices) {
  3785. var vbo = this._gl.createBuffer();
  3786. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3787. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3788. this._resetVertexBufferBinding();
  3789. vbo.references = 1;
  3790. return vbo;
  3791. };
  3792. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3793. var vbo = this._gl.createBuffer();
  3794. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3795. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3796. this._resetVertexBufferBinding();
  3797. vbo.references = 1;
  3798. return vbo;
  3799. };
  3800. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3801. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3802. if (offset === undefined) {
  3803. offset = 0;
  3804. }
  3805. if (vertices instanceof Float32Array) {
  3806. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3807. } else {
  3808. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3809. }
  3810. this._resetVertexBufferBinding();
  3811. };
  3812. Engine.prototype._resetIndexBufferBinding = function () {
  3813. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3814. this._cachedIndexBuffer = null;
  3815. };
  3816. Engine.prototype.createIndexBuffer = function (indices) {
  3817. var vbo = this._gl.createBuffer();
  3818. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3819. // Check for 32 bits indices
  3820. var arrayBuffer;
  3821. var need32Bits = false;
  3822. if (this._caps.uintIndices) {
  3823. for (var index = 0; index < indices.length; index++) {
  3824. if (indices[index] > 65535) {
  3825. need32Bits = true;
  3826. break;
  3827. }
  3828. }
  3829. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3830. } else {
  3831. arrayBuffer = new Uint16Array(indices);
  3832. }
  3833. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3834. this._resetIndexBufferBinding();
  3835. vbo.references = 1;
  3836. vbo.is32Bits = need32Bits;
  3837. return vbo;
  3838. };
  3839. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3840. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3841. this._cachedVertexBuffers = vertexBuffer;
  3842. this._cachedEffectForVertexBuffers = effect;
  3843. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3844. var offset = 0;
  3845. for (var index = 0; index < vertexDeclaration.length; index++) {
  3846. var order = effect.getAttributeLocation(index);
  3847. if (order >= 0) {
  3848. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3849. }
  3850. offset += vertexDeclaration[index] * 4;
  3851. }
  3852. }
  3853. if (this._cachedIndexBuffer !== indexBuffer) {
  3854. this._cachedIndexBuffer = indexBuffer;
  3855. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3856. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3857. }
  3858. };
  3859. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3860. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3861. this._cachedVertexBuffers = vertexBuffers;
  3862. this._cachedEffectForVertexBuffers = effect;
  3863. var attributes = effect.getAttributesNames();
  3864. for (var index = 0; index < attributes.length; index++) {
  3865. var order = effect.getAttributeLocation(index);
  3866. if (order >= 0) {
  3867. var vertexBuffer = vertexBuffers[attributes[index]];
  3868. if (!vertexBuffer) {
  3869. continue;
  3870. }
  3871. var stride = vertexBuffer.getStrideSize();
  3872. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3873. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3874. }
  3875. }
  3876. }
  3877. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3878. this._cachedIndexBuffer = indexBuffer;
  3879. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3880. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3881. }
  3882. };
  3883. Engine.prototype._releaseBuffer = function (buffer) {
  3884. buffer.references--;
  3885. if (buffer.references === 0) {
  3886. this._gl.deleteBuffer(buffer);
  3887. return true;
  3888. }
  3889. return false;
  3890. };
  3891. Engine.prototype.createInstancesBuffer = function (capacity) {
  3892. var buffer = this._gl.createBuffer();
  3893. buffer.capacity = capacity;
  3894. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3895. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3896. return buffer;
  3897. };
  3898. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3899. this._gl.deleteBuffer(buffer);
  3900. };
  3901. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3902. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3903. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3904. for (var index = 0; index < 4; index++) {
  3905. var offsetLocation = offsetLocations[index];
  3906. this._gl.enableVertexAttribArray(offsetLocation);
  3907. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3908. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3909. }
  3910. };
  3911. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3912. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3913. for (var index = 0; index < 4; index++) {
  3914. var offsetLocation = offsetLocations[index];
  3915. this._gl.disableVertexAttribArray(offsetLocation);
  3916. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3917. }
  3918. };
  3919. Engine.prototype.applyStates = function () {
  3920. this._depthCullingState.apply(this._gl);
  3921. this._alphaState.apply(this._gl);
  3922. };
  3923. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3924. // Apply states
  3925. this.applyStates();
  3926. this._drawCalls++;
  3927. // Render
  3928. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3929. if (instancesCount) {
  3930. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3931. return;
  3932. }
  3933. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3934. };
  3935. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3936. // Apply states
  3937. this.applyStates();
  3938. this._drawCalls++;
  3939. if (instancesCount) {
  3940. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3941. return;
  3942. }
  3943. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3944. };
  3945. // Shaders
  3946. Engine.prototype._releaseEffect = function (effect) {
  3947. if (this._compiledEffects[effect._key]) {
  3948. delete this._compiledEffects[effect._key];
  3949. if (effect.getProgram()) {
  3950. this._gl.deleteProgram(effect.getProgram());
  3951. }
  3952. }
  3953. };
  3954. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3955. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3956. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3957. var name = vertex + "+" + fragment + "@" + defines;
  3958. if (this._compiledEffects[name]) {
  3959. return this._compiledEffects[name];
  3960. }
  3961. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3962. effect._key = name;
  3963. this._compiledEffects[name] = effect;
  3964. return effect;
  3965. };
  3966. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3967. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3968. if (typeof samplers === "undefined") { samplers = []; }
  3969. if (typeof defines === "undefined") { defines = ""; }
  3970. return this.createEffect({
  3971. vertex: "particles",
  3972. fragmentElement: fragmentName
  3973. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3974. };
  3975. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3976. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3977. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3978. var shaderProgram = this._gl.createProgram();
  3979. this._gl.attachShader(shaderProgram, vertexShader);
  3980. this._gl.attachShader(shaderProgram, fragmentShader);
  3981. this._gl.linkProgram(shaderProgram);
  3982. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3983. if (!linked) {
  3984. var error = this._gl.getProgramInfoLog(shaderProgram);
  3985. if (error) {
  3986. throw new Error(error);
  3987. }
  3988. }
  3989. this._gl.deleteShader(vertexShader);
  3990. this._gl.deleteShader(fragmentShader);
  3991. return shaderProgram;
  3992. };
  3993. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3994. var results = [];
  3995. for (var index = 0; index < uniformsNames.length; index++) {
  3996. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3997. }
  3998. return results;
  3999. };
  4000. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4001. var results = [];
  4002. for (var index = 0; index < attributesNames.length; index++) {
  4003. try {
  4004. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4005. } catch (e) {
  4006. results.push(-1);
  4007. }
  4008. }
  4009. return results;
  4010. };
  4011. Engine.prototype.enableEffect = function (effect) {
  4012. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4013. if (effect && effect.onBind) {
  4014. effect.onBind(effect);
  4015. }
  4016. return;
  4017. }
  4018. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4019. // Use program
  4020. this._gl.useProgram(effect.getProgram());
  4021. for (var i in this._vertexAttribArrays) {
  4022. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4023. continue;
  4024. }
  4025. this._vertexAttribArrays[i] = false;
  4026. this._gl.disableVertexAttribArray(i);
  4027. }
  4028. var attributesCount = effect.getAttributesCount();
  4029. for (var index = 0; index < attributesCount; index++) {
  4030. // Attributes
  4031. var order = effect.getAttributeLocation(index);
  4032. if (order >= 0) {
  4033. this._vertexAttribArrays[order] = true;
  4034. this._gl.enableVertexAttribArray(order);
  4035. }
  4036. }
  4037. this._currentEffect = effect;
  4038. if (effect.onBind) {
  4039. effect.onBind(effect);
  4040. }
  4041. };
  4042. Engine.prototype.setArray = function (uniform, array) {
  4043. if (!uniform)
  4044. return;
  4045. this._gl.uniform1fv(uniform, array);
  4046. };
  4047. Engine.prototype.setMatrices = function (uniform, matrices) {
  4048. if (!uniform)
  4049. return;
  4050. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4051. };
  4052. Engine.prototype.setMatrix = function (uniform, matrix) {
  4053. if (!uniform)
  4054. return;
  4055. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4056. };
  4057. Engine.prototype.setFloat = function (uniform, value) {
  4058. if (!uniform)
  4059. return;
  4060. this._gl.uniform1f(uniform, value);
  4061. };
  4062. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4063. if (!uniform)
  4064. return;
  4065. this._gl.uniform2f(uniform, x, y);
  4066. };
  4067. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4068. if (!uniform)
  4069. return;
  4070. this._gl.uniform3f(uniform, x, y, z);
  4071. };
  4072. Engine.prototype.setBool = function (uniform, bool) {
  4073. if (!uniform)
  4074. return;
  4075. this._gl.uniform1i(uniform, bool);
  4076. };
  4077. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4078. if (!uniform)
  4079. return;
  4080. this._gl.uniform4f(uniform, x, y, z, w);
  4081. };
  4082. Engine.prototype.setColor3 = function (uniform, color3) {
  4083. if (!uniform)
  4084. return;
  4085. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4086. };
  4087. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4088. if (!uniform)
  4089. return;
  4090. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4091. };
  4092. // States
  4093. Engine.prototype.setState = function (culling, force) {
  4094. // Culling
  4095. if (this._depthCullingState.cull !== culling || force) {
  4096. if (culling) {
  4097. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4098. this._depthCullingState.cull = true;
  4099. } else {
  4100. this._depthCullingState.cull = false;
  4101. }
  4102. }
  4103. };
  4104. Engine.prototype.setDepthBuffer = function (enable) {
  4105. this._depthCullingState.depthTest = enable;
  4106. };
  4107. Engine.prototype.getDepthWrite = function () {
  4108. return this._depthCullingState.depthMask;
  4109. };
  4110. Engine.prototype.setDepthWrite = function (enable) {
  4111. this._depthCullingState.depthMask = enable;
  4112. };
  4113. Engine.prototype.setColorWrite = function (enable) {
  4114. this._gl.colorMask(enable, enable, enable, enable);
  4115. };
  4116. Engine.prototype.setAlphaMode = function (mode) {
  4117. switch (mode) {
  4118. case Engine.ALPHA_DISABLE:
  4119. this.setDepthWrite(true);
  4120. this._alphaState.alphaBlend = false;
  4121. break;
  4122. case Engine.ALPHA_COMBINE:
  4123. this.setDepthWrite(false);
  4124. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4125. this._alphaState.alphaBlend = true;
  4126. break;
  4127. case Engine.ALPHA_ADD:
  4128. this.setDepthWrite(false);
  4129. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4130. this._alphaState.alphaBlend = true;
  4131. break;
  4132. }
  4133. this._alphaMode = mode;
  4134. };
  4135. Engine.prototype.getAlphaMode = function () {
  4136. return this._alphaMode;
  4137. };
  4138. Engine.prototype.setAlphaTesting = function (enable) {
  4139. this._alphaTest = enable;
  4140. };
  4141. Engine.prototype.getAlphaTesting = function () {
  4142. return this._alphaTest;
  4143. };
  4144. // Textures
  4145. Engine.prototype.wipeCaches = function () {
  4146. this._activeTexturesCache = [];
  4147. this._currentEffect = null;
  4148. this._depthCullingState.reset();
  4149. this._alphaState.reset();
  4150. this._cachedVertexBuffers = null;
  4151. this._cachedIndexBuffer = null;
  4152. this._cachedEffectForVertexBuffers = null;
  4153. };
  4154. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4155. var gl = this._gl;
  4156. gl.bindTexture(gl.TEXTURE_2D, texture);
  4157. var magFilter = gl.NEAREST;
  4158. var minFilter = gl.NEAREST;
  4159. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4160. magFilter = gl.LINEAR;
  4161. minFilter = gl.LINEAR;
  4162. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4163. magFilter = gl.LINEAR;
  4164. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4165. }
  4166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4168. gl.bindTexture(gl.TEXTURE_2D, null);
  4169. texture.samplingMode = samplingMode;
  4170. };
  4171. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4172. var _this = this;
  4173. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4174. if (typeof onLoad === "undefined") { onLoad = null; }
  4175. if (typeof onError === "undefined") { onError = null; }
  4176. if (typeof buffer === "undefined") { buffer = null; }
  4177. var texture = this._gl.createTexture();
  4178. var extension;
  4179. var fromData = false;
  4180. if (url.substr(0, 5) === "data:") {
  4181. fromData = true;
  4182. }
  4183. if (!fromData)
  4184. extension = url.substr(url.length - 4, 4).toLowerCase();
  4185. else {
  4186. var oldUrl = url;
  4187. fromData = oldUrl.split(':');
  4188. url = oldUrl;
  4189. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4190. }
  4191. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4192. var isTGA = (extension === ".tga");
  4193. scene._addPendingData(texture);
  4194. texture.url = url;
  4195. texture.noMipmap = noMipmap;
  4196. texture.references = 1;
  4197. this._loadedTexturesCache.push(texture);
  4198. var onerror = function () {
  4199. scene._removePendingData(texture);
  4200. if (onError) {
  4201. onError();
  4202. }
  4203. };
  4204. if (isTGA) {
  4205. var callback = function (arrayBuffer) {
  4206. var data = new Uint8Array(arrayBuffer);
  4207. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4208. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4209. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4210. if (onLoad) {
  4211. onLoad();
  4212. }
  4213. }, samplingMode);
  4214. };
  4215. if (!(fromData instanceof Array))
  4216. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4217. callback(arrayBuffer);
  4218. }, onerror, scene.database, true);
  4219. else
  4220. callback(buffer);
  4221. } else if (isDDS) {
  4222. callback = function (data) {
  4223. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4224. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4225. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4226. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4227. if (onLoad) {
  4228. onLoad();
  4229. }
  4230. }, samplingMode);
  4231. };
  4232. if (!(fromData instanceof Array))
  4233. BABYLON.Tools.LoadFile(url, function (data) {
  4234. callback(data);
  4235. }, onerror, scene.database, true);
  4236. else
  4237. callback(buffer);
  4238. } else {
  4239. var onload = function (img) {
  4240. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4241. var isPot = (img.width === potWidth && img.height === potHeight);
  4242. if (!isPot) {
  4243. _this._workingCanvas.width = potWidth;
  4244. _this._workingCanvas.height = potHeight;
  4245. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4246. _this._workingContext.imageSmoothingEnabled = false;
  4247. _this._workingContext.mozImageSmoothingEnabled = false;
  4248. _this._workingContext.oImageSmoothingEnabled = false;
  4249. _this._workingContext.webkitImageSmoothingEnabled = false;
  4250. _this._workingContext.msImageSmoothingEnabled = false;
  4251. }
  4252. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4253. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4254. _this._workingContext.imageSmoothingEnabled = true;
  4255. _this._workingContext.mozImageSmoothingEnabled = true;
  4256. _this._workingContext.oImageSmoothingEnabled = true;
  4257. _this._workingContext.webkitImageSmoothingEnabled = true;
  4258. _this._workingContext.msImageSmoothingEnabled = true;
  4259. }
  4260. }
  4261. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4262. if (onLoad) {
  4263. onLoad();
  4264. }
  4265. }, samplingMode);
  4266. };
  4267. if (!(fromData instanceof Array))
  4268. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4269. else
  4270. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4271. }
  4272. return texture;
  4273. };
  4274. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4275. var texture = this._gl.createTexture();
  4276. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4277. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4278. // Format
  4279. var internalFormat = this._gl.RGBA;
  4280. switch (format) {
  4281. case Engine.TEXTUREFORMAT_ALPHA:
  4282. internalFormat = this._gl.ALPHA;
  4283. break;
  4284. case Engine.TEXTUREFORMAT_LUMINANCE:
  4285. internalFormat = this._gl.LUMINANCE;
  4286. break;
  4287. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4288. internalFormat = this._gl.LUMINANCE_ALPHA;
  4289. break;
  4290. case Engine.TEXTUREFORMAT_RGB:
  4291. internalFormat = this._gl.RGB;
  4292. break;
  4293. case Engine.TEXTUREFORMAT_RGBA:
  4294. internalFormat = this._gl.RGBA;
  4295. break;
  4296. }
  4297. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4298. if (generateMipMaps) {
  4299. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4300. }
  4301. // Filters
  4302. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4303. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4304. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4305. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4306. this._activeTexturesCache = [];
  4307. texture._baseWidth = width;
  4308. texture._baseHeight = height;
  4309. texture._width = width;
  4310. texture._height = height;
  4311. texture.isReady = true;
  4312. texture.references = 1;
  4313. texture.samplingMode = samplingMode;
  4314. this._loadedTexturesCache.push(texture);
  4315. return texture;
  4316. };
  4317. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4318. var texture = this._gl.createTexture();
  4319. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4320. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4321. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4322. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4324. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4325. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4326. this._activeTexturesCache = [];
  4327. texture._baseWidth = width;
  4328. texture._baseHeight = height;
  4329. texture._width = width;
  4330. texture._height = height;
  4331. texture.isReady = false;
  4332. texture.generateMipMaps = generateMipMaps;
  4333. texture.references = 1;
  4334. texture.samplingMode = samplingMode;
  4335. this._loadedTexturesCache.push(texture);
  4336. return texture;
  4337. };
  4338. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4339. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4340. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4341. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4342. if (texture.generateMipMaps) {
  4343. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4344. }
  4345. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4346. this._activeTexturesCache = [];
  4347. texture.isReady = true;
  4348. };
  4349. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4350. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4351. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4352. // Scale the video if it is a NPOT using the current working canvas
  4353. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4354. if (!texture._workingCanvas) {
  4355. texture._workingCanvas = document.createElement("canvas");
  4356. texture._workingContext = texture._workingCanvas.getContext("2d");
  4357. texture._workingCanvas.width = texture._width;
  4358. texture._workingCanvas.height = texture._height;
  4359. }
  4360. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4362. } else {
  4363. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4364. }
  4365. if (texture.generateMipMaps) {
  4366. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4367. }
  4368. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4369. this._activeTexturesCache = [];
  4370. texture.isReady = true;
  4371. };
  4372. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4373. // old version had a "generateMipMaps" arg instead of options.
  4374. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4375. // in the same way, generateDepthBuffer is defaulted to true
  4376. var generateMipMaps = false;
  4377. var generateDepthBuffer = true;
  4378. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4379. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4380. if (options !== undefined) {
  4381. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4382. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4383. type = options.type === undefined ? type : options.type;
  4384. if (options.samplingMode !== undefined) {
  4385. samplingMode = options.samplingMode;
  4386. }
  4387. if (type === Engine.TEXTURETYPE_FLOAT) {
  4388. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4389. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4390. }
  4391. }
  4392. var gl = this._gl;
  4393. var texture = gl.createTexture();
  4394. gl.bindTexture(gl.TEXTURE_2D, texture);
  4395. var width = size.width || size;
  4396. var height = size.height || size;
  4397. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4398. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4399. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4400. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4401. }
  4402. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4403. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4404. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4405. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4406. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4407. var depthBuffer;
  4408. // Create the depth buffer
  4409. if (generateDepthBuffer) {
  4410. depthBuffer = gl.createRenderbuffer();
  4411. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4412. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4413. }
  4414. // Create the framebuffer
  4415. var framebuffer = gl.createFramebuffer();
  4416. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4417. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4418. if (generateDepthBuffer) {
  4419. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4420. }
  4421. // Unbind
  4422. gl.bindTexture(gl.TEXTURE_2D, null);
  4423. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4424. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4425. texture._framebuffer = framebuffer;
  4426. if (generateDepthBuffer) {
  4427. texture._depthBuffer = depthBuffer;
  4428. }
  4429. texture._width = width;
  4430. texture._height = height;
  4431. texture.isReady = true;
  4432. texture.generateMipMaps = generateMipMaps;
  4433. texture.references = 1;
  4434. texture.samplingMode = samplingMode;
  4435. this._activeTexturesCache = [];
  4436. this._loadedTexturesCache.push(texture);
  4437. return texture;
  4438. };
  4439. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4440. var _this = this;
  4441. var gl = this._gl;
  4442. var texture = gl.createTexture();
  4443. texture.isCube = true;
  4444. texture.url = rootUrl;
  4445. texture.references = 1;
  4446. this._loadedTexturesCache.push(texture);
  4447. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4448. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4449. if (isDDS) {
  4450. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4451. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4452. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4453. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4454. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4455. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4456. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4457. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4458. }
  4459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4463. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4464. _this._activeTexturesCache = [];
  4465. texture._width = info.width;
  4466. texture._height = info.height;
  4467. texture.isReady = true;
  4468. }, null, null, true);
  4469. } else {
  4470. cascadeLoad(rootUrl, scene, function (imgs) {
  4471. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4472. var height = width;
  4473. _this._workingCanvas.width = width;
  4474. _this._workingCanvas.height = height;
  4475. var faces = [
  4476. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4477. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4478. ];
  4479. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4480. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4481. for (var index = 0; index < faces.length; index++) {
  4482. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4483. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4484. }
  4485. if (!noMipmap) {
  4486. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4487. }
  4488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4490. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4492. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4493. _this._activeTexturesCache = [];
  4494. texture._width = width;
  4495. texture._height = height;
  4496. texture.isReady = true;
  4497. }, extensions);
  4498. }
  4499. return texture;
  4500. };
  4501. Engine.prototype._releaseTexture = function (texture) {
  4502. var gl = this._gl;
  4503. if (texture._framebuffer) {
  4504. gl.deleteFramebuffer(texture._framebuffer);
  4505. }
  4506. if (texture._depthBuffer) {
  4507. gl.deleteRenderbuffer(texture._depthBuffer);
  4508. }
  4509. gl.deleteTexture(texture);
  4510. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4511. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4512. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4513. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4514. this._activeTexturesCache[channel] = null;
  4515. }
  4516. var index = this._loadedTexturesCache.indexOf(texture);
  4517. if (index !== -1) {
  4518. this._loadedTexturesCache.splice(index, 1);
  4519. }
  4520. };
  4521. Engine.prototype.bindSamplers = function (effect) {
  4522. this._gl.useProgram(effect.getProgram());
  4523. var samplers = effect.getSamplers();
  4524. for (var index = 0; index < samplers.length; index++) {
  4525. var uniform = effect.getUniform(samplers[index]);
  4526. this._gl.uniform1i(uniform, index);
  4527. }
  4528. this._currentEffect = null;
  4529. };
  4530. Engine.prototype._bindTexture = function (channel, texture) {
  4531. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4532. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4533. this._activeTexturesCache[channel] = null;
  4534. };
  4535. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4536. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4537. };
  4538. Engine.prototype.setTexture = function (channel, texture) {
  4539. if (channel < 0) {
  4540. return;
  4541. }
  4542. // Not ready?
  4543. if (!texture || !texture.isReady()) {
  4544. if (this._activeTexturesCache[channel] != null) {
  4545. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4546. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4547. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4548. this._activeTexturesCache[channel] = null;
  4549. }
  4550. return;
  4551. }
  4552. // Video
  4553. if (texture instanceof BABYLON.VideoTexture) {
  4554. if (texture.update()) {
  4555. this._activeTexturesCache[channel] = null;
  4556. }
  4557. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4558. texture.delayLoad();
  4559. return;
  4560. }
  4561. if (this._activeTexturesCache[channel] === texture) {
  4562. return;
  4563. }
  4564. this._activeTexturesCache[channel] = texture;
  4565. var internalTexture = texture.getInternalTexture();
  4566. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4567. if (internalTexture.isCube) {
  4568. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4569. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4570. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4571. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4572. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4573. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4574. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4575. }
  4576. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4577. } else {
  4578. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4579. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4580. internalTexture._cachedWrapU = texture.wrapU;
  4581. switch (texture.wrapU) {
  4582. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4583. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4584. break;
  4585. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4586. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4587. break;
  4588. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4589. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4590. break;
  4591. }
  4592. }
  4593. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4594. internalTexture._cachedWrapV = texture.wrapV;
  4595. switch (texture.wrapV) {
  4596. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4598. break;
  4599. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4600. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4601. break;
  4602. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4603. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4604. break;
  4605. }
  4606. }
  4607. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4608. }
  4609. };
  4610. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4611. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4612. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4613. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4614. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4615. }
  4616. };
  4617. Engine.prototype.readPixels = function (x, y, width, height) {
  4618. var data = new Uint8Array(height * width * 4);
  4619. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4620. return data;
  4621. };
  4622. // Dispose
  4623. Engine.prototype.dispose = function () {
  4624. this.hideLoadingUI();
  4625. this.stopRenderLoop();
  4626. while (this.scenes.length) {
  4627. this.scenes[0].dispose();
  4628. }
  4629. for (var name in this._compiledEffects) {
  4630. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4631. }
  4632. for (var i in this._vertexAttribArrays) {
  4633. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4634. continue;
  4635. }
  4636. this._gl.disableVertexAttribArray(i);
  4637. }
  4638. // Events
  4639. window.removeEventListener("blur", this._onBlur);
  4640. window.removeEventListener("focus", this._onFocus);
  4641. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4642. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4643. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4644. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4645. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4646. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4647. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4648. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4649. };
  4650. // Loading screen
  4651. Engine.prototype.displayLoadingUI = function () {
  4652. var _this = this;
  4653. this._loadingDiv = document.createElement("div");
  4654. this._loadingDiv.style.opacity = "0";
  4655. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4656. // Loading text
  4657. this._loadingTextDiv = document.createElement("div");
  4658. this._loadingTextDiv.style.position = "absolute";
  4659. this._loadingTextDiv.style.left = "0";
  4660. this._loadingTextDiv.style.top = "50%";
  4661. this._loadingTextDiv.style.marginTop = "80px";
  4662. this._loadingTextDiv.style.width = "100%";
  4663. this._loadingTextDiv.style.height = "20px";
  4664. this._loadingTextDiv.style.fontFamily = "Arial";
  4665. this._loadingTextDiv.style.fontSize = "14px";
  4666. this._loadingTextDiv.style.color = "white";
  4667. this._loadingTextDiv.style.textAlign = "center";
  4668. this._loadingTextDiv.innerHTML = "Loading";
  4669. this._loadingDiv.appendChild(this._loadingTextDiv);
  4670. // Loading img
  4671. var imgBack = new Image();
  4672. 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==";
  4673. imgBack.style.position = "absolute";
  4674. imgBack.style.left = "50%";
  4675. imgBack.style.top = "50%";
  4676. imgBack.style.marginLeft = "-50px";
  4677. imgBack.style.marginTop = "-50px";
  4678. imgBack.style.transition = "transform 1.0s ease";
  4679. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4680. var deg = 360;
  4681. var onTransitionEnd = function () {
  4682. deg += 360;
  4683. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4684. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4685. };
  4686. imgBack.addEventListener("transitionend", onTransitionEnd);
  4687. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4688. this._loadingDiv.appendChild(imgBack);
  4689. // front image
  4690. var imgFront = new Image();
  4691. 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=";
  4692. imgFront.style.position = "absolute";
  4693. imgFront.style.left = "50%";
  4694. imgFront.style.top = "50%";
  4695. imgFront.style.marginLeft = "-50px";
  4696. imgFront.style.marginTop = "-50px";
  4697. this._loadingDiv.appendChild(imgFront);
  4698. // Resize
  4699. this._resizeLoadingUI = function () {
  4700. var canvasRect = _this.getRenderingCanvasClientRect();
  4701. _this._loadingDiv.style.position = "absolute";
  4702. _this._loadingDiv.style.left = canvasRect.left + "px";
  4703. _this._loadingDiv.style.top = canvasRect.top + "px";
  4704. _this._loadingDiv.style.width = canvasRect.width + "px";
  4705. _this._loadingDiv.style.height = canvasRect.height + "px";
  4706. };
  4707. this._resizeLoadingUI();
  4708. window.addEventListener("resize", this._resizeLoadingUI);
  4709. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4710. document.body.appendChild(this._loadingDiv);
  4711. setTimeout(function () {
  4712. _this._loadingDiv.style.opacity = "1";
  4713. imgBack.style.transform = "rotateZ(360deg)";
  4714. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4715. }, 0);
  4716. };
  4717. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4718. set: function (text) {
  4719. if (!this._loadingDiv) {
  4720. return;
  4721. }
  4722. this._loadingTextDiv.innerHTML = text;
  4723. },
  4724. enumerable: true,
  4725. configurable: true
  4726. });
  4727. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4728. get: function () {
  4729. return this._loadingDivBackgroundColor;
  4730. },
  4731. set: function (color) {
  4732. this._loadingDivBackgroundColor = color;
  4733. if (!this._loadingDiv) {
  4734. return;
  4735. }
  4736. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4737. },
  4738. enumerable: true,
  4739. configurable: true
  4740. });
  4741. Engine.prototype.hideLoadingUI = function () {
  4742. var _this = this;
  4743. if (!this._loadingDiv) {
  4744. return;
  4745. }
  4746. var onTransitionEnd = function () {
  4747. if (!_this._loadingDiv) {
  4748. return;
  4749. }
  4750. document.body.removeChild(_this._loadingDiv);
  4751. window.removeEventListener("resize", _this._resizeLoadingUI);
  4752. _this._loadingDiv = null;
  4753. };
  4754. this._loadingDiv.style.opacity = "0";
  4755. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4756. };
  4757. // FPS
  4758. Engine.prototype.getFps = function () {
  4759. return this.fps;
  4760. };
  4761. Engine.prototype.getDeltaTime = function () {
  4762. return this.deltaTime;
  4763. };
  4764. Engine.prototype._measureFps = function () {
  4765. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4766. var length = this.previousFramesDuration.length;
  4767. if (length >= 2) {
  4768. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4769. }
  4770. if (length >= this.fpsRange) {
  4771. if (length > this.fpsRange) {
  4772. this.previousFramesDuration.splice(0, 1);
  4773. length = this.previousFramesDuration.length;
  4774. }
  4775. var sum = 0;
  4776. for (var id = 0; id < length - 1; id++) {
  4777. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4778. }
  4779. this.fps = 1000.0 / (sum / (length - 1));
  4780. }
  4781. };
  4782. // Statics
  4783. Engine.isSupported = function () {
  4784. try {
  4785. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4786. if (navigator.isCocoonJS) {
  4787. return true;
  4788. }
  4789. var tempcanvas = document.createElement("canvas");
  4790. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4791. return gl != null && !!window.WebGLRenderingContext;
  4792. } catch (e) {
  4793. return false;
  4794. }
  4795. };
  4796. Engine._ALPHA_DISABLE = 0;
  4797. Engine._ALPHA_ADD = 1;
  4798. Engine._ALPHA_COMBINE = 2;
  4799. Engine._DELAYLOADSTATE_NONE = 0;
  4800. Engine._DELAYLOADSTATE_LOADED = 1;
  4801. Engine._DELAYLOADSTATE_LOADING = 2;
  4802. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4803. Engine._TEXTUREFORMAT_ALPHA = 0;
  4804. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4805. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4806. Engine._TEXTUREFORMAT_RGB = 4;
  4807. Engine._TEXTUREFORMAT_RGBA = 4;
  4808. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  4809. Engine._TEXTURETYPE_FLOAT = 1;
  4810. Engine.Epsilon = 0.001;
  4811. Engine.CollisionsEpsilon = 0.001;
  4812. Engine.ShadersRepository = "Babylon/Shaders/";
  4813. return Engine;
  4814. })();
  4815. BABYLON.Engine = Engine;
  4816. })(BABYLON || (BABYLON = {}));
  4817. //# sourceMappingURL=babylon.engine.js.map
  4818. var BABYLON;
  4819. (function (BABYLON) {
  4820. /**
  4821. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4822. */
  4823. var Node = (function () {
  4824. /**
  4825. * @constructor
  4826. * @param {string} name - the name and id to be given to this node
  4827. * @param {BABYLON.Scene} the scene this node will be added to
  4828. */
  4829. function Node(name, scene) {
  4830. this.state = "";
  4831. this.animations = new Array();
  4832. this._childrenFlag = -1;
  4833. this._isEnabled = true;
  4834. this._isReady = true;
  4835. this._currentRenderId = -1;
  4836. this.name = name;
  4837. this.id = name;
  4838. this._scene = scene;
  4839. this._initCache();
  4840. }
  4841. Node.prototype.getScene = function () {
  4842. return this._scene;
  4843. };
  4844. Node.prototype.getEngine = function () {
  4845. return this._scene.getEngine();
  4846. };
  4847. // override it in derived class
  4848. Node.prototype.getWorldMatrix = function () {
  4849. return BABYLON.Matrix.Identity();
  4850. };
  4851. // override it in derived class if you add new variables to the cache
  4852. // and call the parent class method
  4853. Node.prototype._initCache = function () {
  4854. this._cache = {};
  4855. this._cache.parent = undefined;
  4856. };
  4857. Node.prototype.updateCache = function (force) {
  4858. if (!force && this.isSynchronized())
  4859. return;
  4860. this._cache.parent = this.parent;
  4861. this._updateCache();
  4862. };
  4863. // override it in derived class if you add new variables to the cache
  4864. // and call the parent class method if !ignoreParentClass
  4865. Node.prototype._updateCache = function (ignoreParentClass) {
  4866. };
  4867. // override it in derived class if you add new variables to the cache
  4868. Node.prototype._isSynchronized = function () {
  4869. return true;
  4870. };
  4871. Node.prototype.isSynchronizedWithParent = function () {
  4872. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4873. };
  4874. Node.prototype.isSynchronized = function (updateCache) {
  4875. var check = this.hasNewParent();
  4876. check = check || !this.isSynchronizedWithParent();
  4877. check = check || !this._isSynchronized();
  4878. if (updateCache)
  4879. this.updateCache(true);
  4880. return !check;
  4881. };
  4882. Node.prototype.hasNewParent = function (update) {
  4883. if (this._cache.parent === this.parent)
  4884. return false;
  4885. if (update)
  4886. this._cache.parent = this.parent;
  4887. return true;
  4888. };
  4889. /**
  4890. * Is this node ready to be used/rendered
  4891. * @return {boolean} is it ready
  4892. */
  4893. Node.prototype.isReady = function () {
  4894. return this._isReady;
  4895. };
  4896. /**
  4897. * Is this node enabled.
  4898. * If the node has a parent and is enabled, the parent will be inspected as well.
  4899. * @return {boolean} whether this node (and its parent) is enabled.
  4900. * @see setEnabled
  4901. */
  4902. Node.prototype.isEnabled = function () {
  4903. if (!this._isEnabled) {
  4904. return false;
  4905. }
  4906. if (this.parent) {
  4907. return this.parent.isEnabled();
  4908. }
  4909. return true;
  4910. };
  4911. /**
  4912. * Set the enabled state of this node.
  4913. * @param {boolean} value - the new enabled state
  4914. * @see isEnabled
  4915. */
  4916. Node.prototype.setEnabled = function (value) {
  4917. this._isEnabled = value;
  4918. };
  4919. /**
  4920. * Is this node a descendant of the given node.
  4921. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  4922. * @param {BABYLON.Node} ancestor - The parent node to inspect
  4923. * @see parent
  4924. */
  4925. Node.prototype.isDescendantOf = function (ancestor) {
  4926. if (this.parent) {
  4927. if (this.parent === ancestor) {
  4928. return true;
  4929. }
  4930. return this.parent.isDescendantOf(ancestor);
  4931. }
  4932. return false;
  4933. };
  4934. Node.prototype._getDescendants = function (list, results) {
  4935. for (var index = 0; index < list.length; index++) {
  4936. var item = list[index];
  4937. if (item.isDescendantOf(this)) {
  4938. results.push(item);
  4939. }
  4940. }
  4941. };
  4942. /**
  4943. * Will return all nodes that have this node as parent.
  4944. * @return {BABYLON.Node[]} all children nodes of all types.
  4945. */
  4946. Node.prototype.getDescendants = function () {
  4947. var results = [];
  4948. this._getDescendants(this._scene.meshes, results);
  4949. this._getDescendants(this._scene.lights, results);
  4950. this._getDescendants(this._scene.cameras, results);
  4951. return results;
  4952. };
  4953. Node.prototype._setReady = function (state) {
  4954. if (state == this._isReady) {
  4955. return;
  4956. }
  4957. if (!state) {
  4958. this._isReady = false;
  4959. return;
  4960. }
  4961. this._isReady = true;
  4962. if (this.onReady) {
  4963. this.onReady(this);
  4964. }
  4965. };
  4966. return Node;
  4967. })();
  4968. BABYLON.Node = Node;
  4969. })(BABYLON || (BABYLON = {}));
  4970. //# sourceMappingURL=babylon.node.js.map
  4971. var BABYLON;
  4972. (function (BABYLON) {
  4973. var BoundingSphere = (function () {
  4974. function BoundingSphere(minimum, maximum) {
  4975. this.minimum = minimum;
  4976. this.maximum = maximum;
  4977. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4978. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4979. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4980. this.radius = distance * 0.5;
  4981. this.centerWorld = BABYLON.Vector3.Zero();
  4982. this._update(BABYLON.Matrix.Identity());
  4983. }
  4984. // Methods
  4985. BoundingSphere.prototype._update = function (world) {
  4986. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4987. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4988. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4989. };
  4990. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4991. for (var i = 0; i < 6; i++) {
  4992. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4993. return false;
  4994. }
  4995. return true;
  4996. };
  4997. BoundingSphere.prototype.intersectsPoint = function (point) {
  4998. var x = this.centerWorld.x - point.x;
  4999. var y = this.centerWorld.y - point.y;
  5000. var z = this.centerWorld.z - point.z;
  5001. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5002. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5003. return false;
  5004. return true;
  5005. };
  5006. // Statics
  5007. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5008. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5009. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5010. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5011. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5012. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5013. return false;
  5014. return true;
  5015. };
  5016. return BoundingSphere;
  5017. })();
  5018. BABYLON.BoundingSphere = BoundingSphere;
  5019. })(BABYLON || (BABYLON = {}));
  5020. //# sourceMappingURL=babylon.boundingSphere.js.map
  5021. var BABYLON;
  5022. (function (BABYLON) {
  5023. var BoundingBox = (function () {
  5024. function BoundingBox(minimum, maximum) {
  5025. this.minimum = minimum;
  5026. this.maximum = maximum;
  5027. this.vectors = new Array();
  5028. this.vectorsWorld = new Array();
  5029. // Bounding vectors
  5030. this.vectors.push(this.minimum.clone());
  5031. this.vectors.push(this.maximum.clone());
  5032. this.vectors.push(this.minimum.clone());
  5033. this.vectors[2].x = this.maximum.x;
  5034. this.vectors.push(this.minimum.clone());
  5035. this.vectors[3].y = this.maximum.y;
  5036. this.vectors.push(this.minimum.clone());
  5037. this.vectors[4].z = this.maximum.z;
  5038. this.vectors.push(this.maximum.clone());
  5039. this.vectors[5].z = this.minimum.z;
  5040. this.vectors.push(this.maximum.clone());
  5041. this.vectors[6].x = this.minimum.x;
  5042. this.vectors.push(this.maximum.clone());
  5043. this.vectors[7].y = this.minimum.y;
  5044. // OBB
  5045. this.center = this.maximum.add(this.minimum).scale(0.5);
  5046. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5047. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5048. for (var index = 0; index < this.vectors.length; index++) {
  5049. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5050. }
  5051. this.minimumWorld = BABYLON.Vector3.Zero();
  5052. this.maximumWorld = BABYLON.Vector3.Zero();
  5053. this._update(BABYLON.Matrix.Identity());
  5054. }
  5055. // Methods
  5056. BoundingBox.prototype.getWorldMatrix = function () {
  5057. return this._worldMatrix;
  5058. };
  5059. BoundingBox.prototype._update = function (world) {
  5060. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5061. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5062. for (var index = 0; index < this.vectors.length; index++) {
  5063. var v = this.vectorsWorld[index];
  5064. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5065. if (v.x < this.minimumWorld.x)
  5066. this.minimumWorld.x = v.x;
  5067. if (v.y < this.minimumWorld.y)
  5068. this.minimumWorld.y = v.y;
  5069. if (v.z < this.minimumWorld.z)
  5070. this.minimumWorld.z = v.z;
  5071. if (v.x > this.maximumWorld.x)
  5072. this.maximumWorld.x = v.x;
  5073. if (v.y > this.maximumWorld.y)
  5074. this.maximumWorld.y = v.y;
  5075. if (v.z > this.maximumWorld.z)
  5076. this.maximumWorld.z = v.z;
  5077. }
  5078. // OBB
  5079. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5080. this.center.scaleInPlace(0.5);
  5081. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5082. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5083. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5084. this._worldMatrix = world;
  5085. };
  5086. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5087. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5088. };
  5089. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5090. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5091. };
  5092. BoundingBox.prototype.intersectsPoint = function (point) {
  5093. var delta = BABYLON.Engine.Epsilon;
  5094. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5095. return false;
  5096. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5097. return false;
  5098. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5099. return false;
  5100. return true;
  5101. };
  5102. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5103. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5104. };
  5105. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5106. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5107. return false;
  5108. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5109. return false;
  5110. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5111. return false;
  5112. return true;
  5113. };
  5114. // Statics
  5115. BoundingBox.Intersects = function (box0, box1) {
  5116. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5117. return false;
  5118. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5119. return false;
  5120. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5121. return false;
  5122. return true;
  5123. };
  5124. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5125. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5126. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5127. return (num <= (sphereRadius * sphereRadius));
  5128. };
  5129. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5130. for (var p = 0; p < 6; p++) {
  5131. for (var i = 0; i < 8; i++) {
  5132. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5133. return false;
  5134. }
  5135. }
  5136. }
  5137. return true;
  5138. };
  5139. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5140. for (var p = 0; p < 6; p++) {
  5141. var inCount = 8;
  5142. for (var i = 0; i < 8; i++) {
  5143. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5144. --inCount;
  5145. } else {
  5146. break;
  5147. }
  5148. }
  5149. if (inCount == 0)
  5150. return false;
  5151. }
  5152. return true;
  5153. };
  5154. return BoundingBox;
  5155. })();
  5156. BABYLON.BoundingBox = BoundingBox;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.boundingBox.js.map
  5159. var BABYLON;
  5160. (function (BABYLON) {
  5161. var computeBoxExtents = function (axis, box) {
  5162. var p = BABYLON.Vector3.Dot(box.center, axis);
  5163. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5164. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5165. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5166. var r = r0 + r1 + r2;
  5167. return {
  5168. min: p - r,
  5169. max: p + r
  5170. };
  5171. };
  5172. var extentsOverlap = function (min0, max0, min1, max1) {
  5173. return !(min0 > max1 || min1 > max0);
  5174. };
  5175. var axisOverlap = function (axis, box0, box1) {
  5176. var result0 = computeBoxExtents(axis, box0);
  5177. var result1 = computeBoxExtents(axis, box1);
  5178. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5179. };
  5180. var BoundingInfo = (function () {
  5181. function BoundingInfo(minimum, maximum) {
  5182. this.minimum = minimum;
  5183. this.maximum = maximum;
  5184. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5185. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5186. }
  5187. // Methods
  5188. BoundingInfo.prototype._update = function (world) {
  5189. this.boundingBox._update(world);
  5190. this.boundingSphere._update(world);
  5191. };
  5192. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5193. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5194. return false;
  5195. return this.boundingBox.isInFrustum(frustumPlanes);
  5196. };
  5197. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5198. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5199. };
  5200. BoundingInfo.prototype._checkCollision = function (collider) {
  5201. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5202. };
  5203. BoundingInfo.prototype.intersectsPoint = function (point) {
  5204. if (!this.boundingSphere.centerWorld) {
  5205. return false;
  5206. }
  5207. if (!this.boundingSphere.intersectsPoint(point)) {
  5208. return false;
  5209. }
  5210. if (!this.boundingBox.intersectsPoint(point)) {
  5211. return false;
  5212. }
  5213. return true;
  5214. };
  5215. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5216. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5217. return false;
  5218. }
  5219. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5220. return false;
  5221. }
  5222. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5223. return false;
  5224. }
  5225. if (!precise) {
  5226. return true;
  5227. }
  5228. var box0 = this.boundingBox;
  5229. var box1 = boundingInfo.boundingBox;
  5230. if (!axisOverlap(box0.directions[0], box0, box1))
  5231. return false;
  5232. if (!axisOverlap(box0.directions[1], box0, box1))
  5233. return false;
  5234. if (!axisOverlap(box0.directions[2], box0, box1))
  5235. return false;
  5236. if (!axisOverlap(box1.directions[0], box0, box1))
  5237. return false;
  5238. if (!axisOverlap(box1.directions[1], box0, box1))
  5239. return false;
  5240. if (!axisOverlap(box1.directions[2], box0, box1))
  5241. return false;
  5242. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5243. return false;
  5244. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5245. return false;
  5246. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5247. return false;
  5248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5249. return false;
  5250. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5251. return false;
  5252. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5253. return false;
  5254. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5255. return false;
  5256. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5257. return false;
  5258. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5259. return false;
  5260. return true;
  5261. };
  5262. return BoundingInfo;
  5263. })();
  5264. BABYLON.BoundingInfo = BoundingInfo;
  5265. })(BABYLON || (BABYLON = {}));
  5266. //# sourceMappingURL=babylon.boundingInfo.js.map
  5267. var BABYLON;
  5268. (function (BABYLON) {
  5269. var Light = (function (_super) {
  5270. __extends(Light, _super);
  5271. function Light(name, scene) {
  5272. _super.call(this, name, scene);
  5273. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5274. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5275. this.intensity = 1.0;
  5276. this.range = Number.MAX_VALUE;
  5277. this.includedOnlyMeshes = new Array();
  5278. this.excludedMeshes = new Array();
  5279. this._excludedMeshesIds = new Array();
  5280. this._includedOnlyMeshesIds = new Array();
  5281. scene.lights.push(this);
  5282. }
  5283. Light.prototype.getShadowGenerator = function () {
  5284. return this._shadowGenerator;
  5285. };
  5286. Light.prototype.getAbsolutePosition = function () {
  5287. return BABYLON.Vector3.Zero();
  5288. };
  5289. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5290. };
  5291. Light.prototype._getWorldMatrix = function () {
  5292. return BABYLON.Matrix.Identity();
  5293. };
  5294. Light.prototype.canAffectMesh = function (mesh) {
  5295. if (!mesh) {
  5296. return true;
  5297. }
  5298. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5299. return false;
  5300. }
  5301. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5302. return false;
  5303. }
  5304. return true;
  5305. };
  5306. Light.prototype.getWorldMatrix = function () {
  5307. this._currentRenderId = this.getScene().getRenderId();
  5308. var worldMatrix = this._getWorldMatrix();
  5309. if (this.parent && this.parent.getWorldMatrix) {
  5310. if (!this._parentedWorldMatrix) {
  5311. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5312. }
  5313. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5314. return this._parentedWorldMatrix;
  5315. }
  5316. return worldMatrix;
  5317. };
  5318. Light.prototype.dispose = function () {
  5319. if (this._shadowGenerator) {
  5320. this._shadowGenerator.dispose();
  5321. this._shadowGenerator = null;
  5322. }
  5323. // Remove from scene
  5324. var index = this.getScene().lights.indexOf(this);
  5325. this.getScene().lights.splice(index, 1);
  5326. };
  5327. return Light;
  5328. })(BABYLON.Node);
  5329. BABYLON.Light = Light;
  5330. })(BABYLON || (BABYLON = {}));
  5331. //# sourceMappingURL=babylon.light.js.map
  5332. var BABYLON;
  5333. (function (BABYLON) {
  5334. var PointLight = (function (_super) {
  5335. __extends(PointLight, _super);
  5336. function PointLight(name, position, scene) {
  5337. _super.call(this, name, scene);
  5338. this.position = position;
  5339. }
  5340. PointLight.prototype.getAbsolutePosition = function () {
  5341. return this._transformedPosition ? this._transformedPosition : this.position;
  5342. };
  5343. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5344. if (this.parent && this.parent.getWorldMatrix) {
  5345. if (!this._transformedPosition) {
  5346. this._transformedPosition = BABYLON.Vector3.Zero();
  5347. }
  5348. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5349. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5350. return;
  5351. }
  5352. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5353. };
  5354. PointLight.prototype.getShadowGenerator = function () {
  5355. return null;
  5356. };
  5357. PointLight.prototype._getWorldMatrix = function () {
  5358. if (!this._worldMatrix) {
  5359. this._worldMatrix = BABYLON.Matrix.Identity();
  5360. }
  5361. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5362. return this._worldMatrix;
  5363. };
  5364. return PointLight;
  5365. })(BABYLON.Light);
  5366. BABYLON.PointLight = PointLight;
  5367. })(BABYLON || (BABYLON = {}));
  5368. //# sourceMappingURL=babylon.pointLight.js.map
  5369. var BABYLON;
  5370. (function (BABYLON) {
  5371. var SpotLight = (function (_super) {
  5372. __extends(SpotLight, _super);
  5373. function SpotLight(name, position, direction, angle, exponent, scene) {
  5374. _super.call(this, name, scene);
  5375. this.position = position;
  5376. this.direction = direction;
  5377. this.angle = angle;
  5378. this.exponent = exponent;
  5379. }
  5380. SpotLight.prototype.getAbsolutePosition = function () {
  5381. return this.transformedPosition ? this.transformedPosition : this.position;
  5382. };
  5383. SpotLight.prototype.setDirectionToTarget = function (target) {
  5384. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5385. return this.direction;
  5386. };
  5387. SpotLight.prototype.computeTransformedPosition = function () {
  5388. if (this.parent && this.parent.getWorldMatrix) {
  5389. if (!this.transformedPosition) {
  5390. this.transformedPosition = BABYLON.Vector3.Zero();
  5391. }
  5392. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5393. return true;
  5394. }
  5395. return false;
  5396. };
  5397. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5398. var normalizeDirection;
  5399. if (this.parent && this.parent.getWorldMatrix) {
  5400. if (!this._transformedDirection) {
  5401. this._transformedDirection = BABYLON.Vector3.Zero();
  5402. }
  5403. this.computeTransformedPosition();
  5404. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5405. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5406. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5407. } else {
  5408. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5409. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5410. }
  5411. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5412. };
  5413. SpotLight.prototype._getWorldMatrix = function () {
  5414. if (!this._worldMatrix) {
  5415. this._worldMatrix = BABYLON.Matrix.Identity();
  5416. }
  5417. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5418. return this._worldMatrix;
  5419. };
  5420. return SpotLight;
  5421. })(BABYLON.Light);
  5422. BABYLON.SpotLight = SpotLight;
  5423. })(BABYLON || (BABYLON = {}));
  5424. //# sourceMappingURL=babylon.spotLight.js.map
  5425. var BABYLON;
  5426. (function (BABYLON) {
  5427. var DirectionalLight = (function (_super) {
  5428. __extends(DirectionalLight, _super);
  5429. function DirectionalLight(name, direction, scene) {
  5430. _super.call(this, name, scene);
  5431. this.direction = direction;
  5432. this.position = direction.scale(-1);
  5433. }
  5434. DirectionalLight.prototype.getAbsolutePosition = function () {
  5435. return this.transformedPosition ? this.transformedPosition : this.position;
  5436. };
  5437. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5438. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5439. return this.direction;
  5440. };
  5441. DirectionalLight.prototype.computeTransformedPosition = function () {
  5442. if (this.parent && this.parent.getWorldMatrix) {
  5443. if (!this.transformedPosition) {
  5444. this.transformedPosition = BABYLON.Vector3.Zero();
  5445. }
  5446. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5447. return true;
  5448. }
  5449. return false;
  5450. };
  5451. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5452. if (this.parent && this.parent.getWorldMatrix) {
  5453. if (!this._transformedDirection) {
  5454. this._transformedDirection = BABYLON.Vector3.Zero();
  5455. }
  5456. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5457. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5458. return;
  5459. }
  5460. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5461. };
  5462. DirectionalLight.prototype._getWorldMatrix = function () {
  5463. if (!this._worldMatrix) {
  5464. this._worldMatrix = BABYLON.Matrix.Identity();
  5465. }
  5466. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5467. return this._worldMatrix;
  5468. };
  5469. return DirectionalLight;
  5470. })(BABYLON.Light);
  5471. BABYLON.DirectionalLight = DirectionalLight;
  5472. })(BABYLON || (BABYLON = {}));
  5473. //# sourceMappingURL=babylon.directionalLight.js.map
  5474. var BABYLON;
  5475. (function (BABYLON) {
  5476. var ShadowGenerator = (function () {
  5477. function ShadowGenerator(mapSize, light) {
  5478. var _this = this;
  5479. // Members
  5480. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5481. this._darkness = 0;
  5482. this._transparencyShadow = false;
  5483. this._viewMatrix = BABYLON.Matrix.Zero();
  5484. this._projectionMatrix = BABYLON.Matrix.Zero();
  5485. this._transformMatrix = BABYLON.Matrix.Zero();
  5486. this._worldViewProjection = BABYLON.Matrix.Zero();
  5487. this._light = light;
  5488. this._scene = light.getScene();
  5489. light._shadowGenerator = this;
  5490. // Render target
  5491. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5492. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5493. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5494. this._shadowMap.renderParticles = false;
  5495. // Custom render function
  5496. var renderSubMesh = function (subMesh) {
  5497. var mesh = subMesh.getRenderingMesh();
  5498. var scene = _this._scene;
  5499. var engine = scene.getEngine();
  5500. // Culling
  5501. engine.setState(subMesh.getMaterial().backFaceCulling);
  5502. // Managing instances
  5503. var batch = mesh._getInstancesRenderList(subMesh._id);
  5504. if (batch.mustReturn) {
  5505. return;
  5506. }
  5507. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5508. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5509. engine.enableEffect(_this._effect);
  5510. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5511. var material = subMesh.getMaterial();
  5512. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5513. // Alpha test
  5514. if (material && material.needAlphaTesting()) {
  5515. var alphaTexture = material.getAlphaTestTexture();
  5516. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5517. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5518. }
  5519. // Bones
  5520. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5521. if (useBones) {
  5522. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5523. }
  5524. if (hardwareInstancedRendering) {
  5525. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5526. } else {
  5527. if (batch.renderSelf[subMesh._id]) {
  5528. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5529. // Draw
  5530. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5531. }
  5532. if (batch.visibleInstances[subMesh._id]) {
  5533. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5534. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5535. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5536. // Draw
  5537. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5538. }
  5539. }
  5540. }
  5541. } else {
  5542. // Need to reset refresh rate of the shadowMap
  5543. _this._shadowMap.resetRefreshCounter();
  5544. }
  5545. };
  5546. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5547. var index;
  5548. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5549. renderSubMesh(opaqueSubMeshes.data[index]);
  5550. }
  5551. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5552. renderSubMesh(alphaTestSubMeshes.data[index]);
  5553. }
  5554. if (_this._transparencyShadow) {
  5555. for (index = 0; index < transparentSubMeshes.length; index++) {
  5556. renderSubMesh(transparentSubMeshes.data[index]);
  5557. }
  5558. }
  5559. };
  5560. }
  5561. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5562. // Static
  5563. get: function () {
  5564. return ShadowGenerator._FILTER_NONE;
  5565. },
  5566. enumerable: true,
  5567. configurable: true
  5568. });
  5569. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5570. get: function () {
  5571. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5572. },
  5573. enumerable: true,
  5574. configurable: true
  5575. });
  5576. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5577. get: function () {
  5578. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5579. },
  5580. enumerable: true,
  5581. configurable: true
  5582. });
  5583. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5584. get: function () {
  5585. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5586. },
  5587. set: function (value) {
  5588. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5589. },
  5590. enumerable: true,
  5591. configurable: true
  5592. });
  5593. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5594. get: function () {
  5595. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5596. },
  5597. set: function (value) {
  5598. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5599. },
  5600. enumerable: true,
  5601. configurable: true
  5602. });
  5603. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5604. var defines = [];
  5605. if (this.useVarianceShadowMap) {
  5606. defines.push("#define VSM");
  5607. }
  5608. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5609. var mesh = subMesh.getMesh();
  5610. var scene = mesh.getScene();
  5611. var material = subMesh.getMaterial();
  5612. // Alpha test
  5613. if (material && material.needAlphaTesting()) {
  5614. defines.push("#define ALPHATEST");
  5615. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5616. attribs.push(BABYLON.VertexBuffer.UVKind);
  5617. defines.push("#define UV1");
  5618. }
  5619. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5620. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5621. defines.push("#define UV2");
  5622. }
  5623. }
  5624. // Bones
  5625. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5626. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5627. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5628. defines.push("#define BONES");
  5629. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5630. }
  5631. // Instances
  5632. if (useInstances) {
  5633. defines.push("#define INSTANCES");
  5634. attribs.push("world0");
  5635. attribs.push("world1");
  5636. attribs.push("world2");
  5637. attribs.push("world3");
  5638. }
  5639. // Get correct effect
  5640. var join = defines.join("\n");
  5641. if (this._cachedDefines !== join) {
  5642. this._cachedDefines = join;
  5643. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5644. }
  5645. return this._effect.isReady();
  5646. };
  5647. ShadowGenerator.prototype.getShadowMap = function () {
  5648. return this._shadowMap;
  5649. };
  5650. ShadowGenerator.prototype.getLight = function () {
  5651. return this._light;
  5652. };
  5653. // Methods
  5654. ShadowGenerator.prototype.getTransformMatrix = function () {
  5655. var lightPosition = this._light.position;
  5656. var lightDirection = this._light.direction;
  5657. if (this._light.computeTransformedPosition()) {
  5658. lightPosition = this._light.transformedPosition;
  5659. }
  5660. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5661. this._cachedPosition = lightPosition.clone();
  5662. this._cachedDirection = lightDirection.clone();
  5663. var activeCamera = this._scene.activeCamera;
  5664. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5665. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5666. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5667. }
  5668. return this._transformMatrix;
  5669. };
  5670. ShadowGenerator.prototype.getDarkness = function () {
  5671. return this._darkness;
  5672. };
  5673. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5674. if (darkness >= 1.0)
  5675. this._darkness = 1.0;
  5676. else if (darkness <= 0.0)
  5677. this._darkness = 0.0;
  5678. else
  5679. this._darkness = darkness;
  5680. };
  5681. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5682. this._transparencyShadow = hasShadow;
  5683. };
  5684. ShadowGenerator.prototype.dispose = function () {
  5685. this._shadowMap.dispose();
  5686. };
  5687. ShadowGenerator._FILTER_NONE = 0;
  5688. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5689. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5690. return ShadowGenerator;
  5691. })();
  5692. BABYLON.ShadowGenerator = ShadowGenerator;
  5693. })(BABYLON || (BABYLON = {}));
  5694. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5695. var BABYLON;
  5696. (function (BABYLON) {
  5697. var HemisphericLight = (function (_super) {
  5698. __extends(HemisphericLight, _super);
  5699. function HemisphericLight(name, direction, scene) {
  5700. _super.call(this, name, scene);
  5701. this.direction = direction;
  5702. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5703. }
  5704. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5705. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5706. return this.direction;
  5707. };
  5708. HemisphericLight.prototype.getShadowGenerator = function () {
  5709. return null;
  5710. };
  5711. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5712. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5713. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5714. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5715. };
  5716. HemisphericLight.prototype._getWorldMatrix = function () {
  5717. if (!this._worldMatrix) {
  5718. this._worldMatrix = BABYLON.Matrix.Identity();
  5719. }
  5720. return this._worldMatrix;
  5721. };
  5722. return HemisphericLight;
  5723. })(BABYLON.Light);
  5724. BABYLON.HemisphericLight = HemisphericLight;
  5725. })(BABYLON || (BABYLON = {}));
  5726. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5727. var BABYLON;
  5728. (function (BABYLON) {
  5729. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5730. if (boxMin.x > sphereCenter.x + sphereRadius)
  5731. return false;
  5732. if (sphereCenter.x - sphereRadius > boxMax.x)
  5733. return false;
  5734. if (boxMin.y > sphereCenter.y + sphereRadius)
  5735. return false;
  5736. if (sphereCenter.y - sphereRadius > boxMax.y)
  5737. return false;
  5738. if (boxMin.z > sphereCenter.z + sphereRadius)
  5739. return false;
  5740. if (sphereCenter.z - sphereRadius > boxMax.z)
  5741. return false;
  5742. return true;
  5743. };
  5744. var getLowestRoot = function (a, b, c, maxR) {
  5745. var determinant = b * b - 4.0 * a * c;
  5746. var result = { root: 0, found: false };
  5747. if (determinant < 0)
  5748. return result;
  5749. var sqrtD = Math.sqrt(determinant);
  5750. var r1 = (-b - sqrtD) / (2.0 * a);
  5751. var r2 = (-b + sqrtD) / (2.0 * a);
  5752. if (r1 > r2) {
  5753. var temp = r2;
  5754. r2 = r1;
  5755. r1 = temp;
  5756. }
  5757. if (r1 > 0 && r1 < maxR) {
  5758. result.root = r1;
  5759. result.found = true;
  5760. return result;
  5761. }
  5762. if (r2 > 0 && r2 < maxR) {
  5763. result.root = r2;
  5764. result.found = true;
  5765. return result;
  5766. }
  5767. return result;
  5768. };
  5769. var Collider = (function () {
  5770. function Collider() {
  5771. this.radius = new BABYLON.Vector3(1, 1, 1);
  5772. this.retry = 0;
  5773. this.basePointWorld = BABYLON.Vector3.Zero();
  5774. this.velocityWorld = BABYLON.Vector3.Zero();
  5775. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5776. this._collisionPoint = BABYLON.Vector3.Zero();
  5777. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5778. this._tempVector = BABYLON.Vector3.Zero();
  5779. this._tempVector2 = BABYLON.Vector3.Zero();
  5780. this._tempVector3 = BABYLON.Vector3.Zero();
  5781. this._tempVector4 = BABYLON.Vector3.Zero();
  5782. this._edge = BABYLON.Vector3.Zero();
  5783. this._baseToVertex = BABYLON.Vector3.Zero();
  5784. this._destinationPoint = BABYLON.Vector3.Zero();
  5785. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5786. this._displacementVector = BABYLON.Vector3.Zero();
  5787. }
  5788. // Methods
  5789. Collider.prototype._initialize = function (source, dir, e) {
  5790. this.velocity = dir;
  5791. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5792. this.basePoint = source;
  5793. source.multiplyToRef(this.radius, this.basePointWorld);
  5794. dir.multiplyToRef(this.radius, this.velocityWorld);
  5795. this.velocityWorldLength = this.velocityWorld.length();
  5796. this.epsilon = e;
  5797. this.collisionFound = false;
  5798. };
  5799. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5800. pa.subtractToRef(point, this._tempVector);
  5801. pb.subtractToRef(point, this._tempVector2);
  5802. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5803. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5804. if (d < 0)
  5805. return false;
  5806. pc.subtractToRef(point, this._tempVector3);
  5807. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5808. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5809. if (d < 0)
  5810. return false;
  5811. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5812. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5813. return d >= 0;
  5814. };
  5815. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5816. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5817. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5818. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5819. return false;
  5820. }
  5821. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5822. return false;
  5823. return true;
  5824. };
  5825. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5826. var t0;
  5827. var embeddedInPlane = false;
  5828. if (!subMesh._trianglePlanes) {
  5829. subMesh._trianglePlanes = [];
  5830. }
  5831. if (!subMesh._trianglePlanes[faceIndex]) {
  5832. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5833. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5834. }
  5835. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5836. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5837. return;
  5838. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5839. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5840. if (normalDotVelocity == 0) {
  5841. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5842. return;
  5843. embeddedInPlane = true;
  5844. t0 = 0;
  5845. } else {
  5846. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5847. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5848. if (t0 > t1) {
  5849. var temp = t1;
  5850. t1 = t0;
  5851. t0 = temp;
  5852. }
  5853. if (t0 > 1.0 || t1 < 0.0)
  5854. return;
  5855. if (t0 < 0)
  5856. t0 = 0;
  5857. if (t0 > 1.0)
  5858. t0 = 1.0;
  5859. }
  5860. this._collisionPoint.copyFromFloats(0, 0, 0);
  5861. var found = false;
  5862. var t = 1.0;
  5863. if (!embeddedInPlane) {
  5864. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5865. this.velocity.scaleToRef(t0, this._tempVector);
  5866. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5867. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5868. found = true;
  5869. t = t0;
  5870. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5871. }
  5872. }
  5873. if (!found) {
  5874. var velocitySquaredLength = this.velocity.lengthSquared();
  5875. var a = velocitySquaredLength;
  5876. this.basePoint.subtractToRef(p1, this._tempVector);
  5877. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5878. var c = this._tempVector.lengthSquared() - 1.0;
  5879. var lowestRoot = getLowestRoot(a, b, c, t);
  5880. if (lowestRoot.found) {
  5881. t = lowestRoot.root;
  5882. found = true;
  5883. this._collisionPoint.copyFrom(p1);
  5884. }
  5885. this.basePoint.subtractToRef(p2, this._tempVector);
  5886. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5887. c = this._tempVector.lengthSquared() - 1.0;
  5888. lowestRoot = getLowestRoot(a, b, c, t);
  5889. if (lowestRoot.found) {
  5890. t = lowestRoot.root;
  5891. found = true;
  5892. this._collisionPoint.copyFrom(p2);
  5893. }
  5894. this.basePoint.subtractToRef(p3, this._tempVector);
  5895. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5896. c = this._tempVector.lengthSquared() - 1.0;
  5897. lowestRoot = getLowestRoot(a, b, c, t);
  5898. if (lowestRoot.found) {
  5899. t = lowestRoot.root;
  5900. found = true;
  5901. this._collisionPoint.copyFrom(p3);
  5902. }
  5903. p2.subtractToRef(p1, this._edge);
  5904. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5905. var edgeSquaredLength = this._edge.lengthSquared();
  5906. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5907. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5908. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5909. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5910. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5911. lowestRoot = getLowestRoot(a, b, c, t);
  5912. if (lowestRoot.found) {
  5913. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5914. if (f >= 0.0 && f <= 1.0) {
  5915. t = lowestRoot.root;
  5916. found = true;
  5917. this._edge.scaleInPlace(f);
  5918. p1.addToRef(this._edge, this._collisionPoint);
  5919. }
  5920. }
  5921. p3.subtractToRef(p2, this._edge);
  5922. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5923. edgeSquaredLength = this._edge.lengthSquared();
  5924. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5925. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5926. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5927. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5928. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5929. lowestRoot = getLowestRoot(a, b, c, t);
  5930. if (lowestRoot.found) {
  5931. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5932. if (f >= 0.0 && f <= 1.0) {
  5933. t = lowestRoot.root;
  5934. found = true;
  5935. this._edge.scaleInPlace(f);
  5936. p2.addToRef(this._edge, this._collisionPoint);
  5937. }
  5938. }
  5939. p1.subtractToRef(p3, this._edge);
  5940. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5941. edgeSquaredLength = this._edge.lengthSquared();
  5942. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5943. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5944. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5945. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5946. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5947. lowestRoot = getLowestRoot(a, b, c, t);
  5948. if (lowestRoot.found) {
  5949. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5950. if (f >= 0.0 && f <= 1.0) {
  5951. t = lowestRoot.root;
  5952. found = true;
  5953. this._edge.scaleInPlace(f);
  5954. p3.addToRef(this._edge, this._collisionPoint);
  5955. }
  5956. }
  5957. }
  5958. if (found) {
  5959. var distToCollision = t * this.velocity.length();
  5960. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5961. if (!this.intersectionPoint) {
  5962. this.intersectionPoint = this._collisionPoint.clone();
  5963. } else {
  5964. this.intersectionPoint.copyFrom(this._collisionPoint);
  5965. }
  5966. this.nearestDistance = distToCollision;
  5967. this.collisionFound = true;
  5968. this.collidedMesh = subMesh.getMesh();
  5969. }
  5970. }
  5971. };
  5972. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5973. for (var i = indexStart; i < indexEnd; i += 3) {
  5974. var p1 = pts[indices[i] - decal];
  5975. var p2 = pts[indices[i + 1] - decal];
  5976. var p3 = pts[indices[i + 2] - decal];
  5977. this._testTriangle(i, subMesh, p3, p2, p1);
  5978. }
  5979. };
  5980. Collider.prototype._getResponse = function (pos, vel) {
  5981. pos.addToRef(vel, this._destinationPoint);
  5982. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5983. this.basePoint.addToRef(vel, pos);
  5984. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5985. this._slidePlaneNormal.normalize();
  5986. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5987. pos.addInPlace(this._displacementVector);
  5988. this.intersectionPoint.addInPlace(this._displacementVector);
  5989. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5990. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5991. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5992. };
  5993. return Collider;
  5994. })();
  5995. BABYLON.Collider = Collider;
  5996. })(BABYLON || (BABYLON = {}));
  5997. //# sourceMappingURL=babylon.collider.js.map
  5998. var BABYLON;
  5999. (function (BABYLON) {
  6000. var Camera = (function (_super) {
  6001. __extends(Camera, _super);
  6002. function Camera(name, position, scene) {
  6003. _super.call(this, name, scene);
  6004. this.position = position;
  6005. // Members
  6006. this.upVector = BABYLON.Vector3.Up();
  6007. this.orthoLeft = null;
  6008. this.orthoRight = null;
  6009. this.orthoBottom = null;
  6010. this.orthoTop = null;
  6011. this.fov = 0.8;
  6012. this.minZ = 1.0;
  6013. this.maxZ = 10000.0;
  6014. this.inertia = 0.9;
  6015. this.mode = Camera.PERSPECTIVE_CAMERA;
  6016. this.isIntermediate = false;
  6017. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6018. this.subCameras = [];
  6019. this.layerMask = 0xFFFFFFFF;
  6020. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6021. this._projectionMatrix = new BABYLON.Matrix();
  6022. this._postProcesses = new Array();
  6023. this._postProcessesTakenIndices = [];
  6024. scene.cameras.push(this);
  6025. if (!scene.activeCamera) {
  6026. scene.activeCamera = this;
  6027. }
  6028. }
  6029. //Cache
  6030. Camera.prototype._initCache = function () {
  6031. _super.prototype._initCache.call(this);
  6032. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6033. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6034. this._cache.mode = undefined;
  6035. this._cache.minZ = undefined;
  6036. this._cache.maxZ = undefined;
  6037. this._cache.fov = undefined;
  6038. this._cache.aspectRatio = undefined;
  6039. this._cache.orthoLeft = undefined;
  6040. this._cache.orthoRight = undefined;
  6041. this._cache.orthoBottom = undefined;
  6042. this._cache.orthoTop = undefined;
  6043. this._cache.renderWidth = undefined;
  6044. this._cache.renderHeight = undefined;
  6045. };
  6046. Camera.prototype._updateCache = function (ignoreParentClass) {
  6047. if (!ignoreParentClass) {
  6048. _super.prototype._updateCache.call(this);
  6049. }
  6050. var engine = this.getEngine();
  6051. this._cache.position.copyFrom(this.position);
  6052. this._cache.upVector.copyFrom(this.upVector);
  6053. this._cache.mode = this.mode;
  6054. this._cache.minZ = this.minZ;
  6055. this._cache.maxZ = this.maxZ;
  6056. this._cache.fov = this.fov;
  6057. this._cache.aspectRatio = engine.getAspectRatio(this);
  6058. this._cache.orthoLeft = this.orthoLeft;
  6059. this._cache.orthoRight = this.orthoRight;
  6060. this._cache.orthoBottom = this.orthoBottom;
  6061. this._cache.orthoTop = this.orthoTop;
  6062. this._cache.renderWidth = engine.getRenderWidth();
  6063. this._cache.renderHeight = engine.getRenderHeight();
  6064. };
  6065. Camera.prototype._updateFromScene = function () {
  6066. this.updateCache();
  6067. this._update();
  6068. };
  6069. // Synchronized
  6070. Camera.prototype._isSynchronized = function () {
  6071. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6072. };
  6073. Camera.prototype._isSynchronizedViewMatrix = function () {
  6074. if (!_super.prototype._isSynchronized.call(this))
  6075. return false;
  6076. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6077. };
  6078. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6079. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6080. if (!check) {
  6081. return false;
  6082. }
  6083. var engine = this.getEngine();
  6084. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6085. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6086. } else {
  6087. 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();
  6088. }
  6089. return check;
  6090. };
  6091. // Controls
  6092. Camera.prototype.attachControl = function (element) {
  6093. };
  6094. Camera.prototype.detachControl = function (element) {
  6095. };
  6096. Camera.prototype._update = function () {
  6097. };
  6098. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6099. if (typeof insertAt === "undefined") { insertAt = null; }
  6100. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6101. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6102. return 0;
  6103. }
  6104. if (insertAt == null || insertAt < 0) {
  6105. this._postProcesses.push(postProcess);
  6106. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6107. return this._postProcesses.length - 1;
  6108. }
  6109. var add = 0;
  6110. if (this._postProcesses[insertAt]) {
  6111. var start = this._postProcesses.length - 1;
  6112. for (var i = start; i >= insertAt + 1; --i) {
  6113. this._postProcesses[i + 1] = this._postProcesses[i];
  6114. }
  6115. add = 1;
  6116. }
  6117. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6118. if (this._postProcessesTakenIndices[i] < insertAt) {
  6119. continue;
  6120. }
  6121. start = this._postProcessesTakenIndices.length - 1;
  6122. for (var j = start; j >= i; --j) {
  6123. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6124. }
  6125. this._postProcessesTakenIndices[i] = insertAt;
  6126. break;
  6127. }
  6128. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6129. this._postProcessesTakenIndices.push(insertAt);
  6130. }
  6131. var result = insertAt + add;
  6132. this._postProcesses[result] = postProcess;
  6133. return result;
  6134. };
  6135. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6136. if (typeof atIndices === "undefined") { atIndices = null; }
  6137. var result = [];
  6138. if (!atIndices) {
  6139. var length = this._postProcesses.length;
  6140. for (var i = 0; i < length; i++) {
  6141. if (this._postProcesses[i] !== postProcess) {
  6142. continue;
  6143. }
  6144. delete this._postProcesses[i];
  6145. var index = this._postProcessesTakenIndices.indexOf(i);
  6146. this._postProcessesTakenIndices.splice(index, 1);
  6147. }
  6148. } else {
  6149. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6150. for (i = 0; i < atIndices.length; i++) {
  6151. var foundPostProcess = this._postProcesses[atIndices[i]];
  6152. if (foundPostProcess !== postProcess) {
  6153. result.push(i);
  6154. continue;
  6155. }
  6156. delete this._postProcesses[atIndices[i]];
  6157. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6158. this._postProcessesTakenIndices.splice(index, 1);
  6159. }
  6160. }
  6161. return result;
  6162. };
  6163. Camera.prototype.getWorldMatrix = function () {
  6164. if (!this._worldMatrix) {
  6165. this._worldMatrix = BABYLON.Matrix.Identity();
  6166. }
  6167. var viewMatrix = this.getViewMatrix();
  6168. viewMatrix.invertToRef(this._worldMatrix);
  6169. return this._worldMatrix;
  6170. };
  6171. Camera.prototype._getViewMatrix = function () {
  6172. return BABYLON.Matrix.Identity();
  6173. };
  6174. Camera.prototype.getViewMatrix = function () {
  6175. this._computedViewMatrix = this._computeViewMatrix();
  6176. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6177. return this._computedViewMatrix;
  6178. }
  6179. if (!this._worldMatrix) {
  6180. this._worldMatrix = BABYLON.Matrix.Identity();
  6181. }
  6182. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6183. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6184. this._computedViewMatrix.invert();
  6185. this._currentRenderId = this.getScene().getRenderId();
  6186. return this._computedViewMatrix;
  6187. };
  6188. Camera.prototype._computeViewMatrix = function (force) {
  6189. if (!force && this._isSynchronizedViewMatrix()) {
  6190. return this._computedViewMatrix;
  6191. }
  6192. this._computedViewMatrix = this._getViewMatrix();
  6193. if (!this.parent || !this.parent.getWorldMatrix) {
  6194. this._currentRenderId = this.getScene().getRenderId();
  6195. }
  6196. return this._computedViewMatrix;
  6197. };
  6198. Camera.prototype.getProjectionMatrix = function (force) {
  6199. if (!force && this._isSynchronizedProjectionMatrix()) {
  6200. return this._projectionMatrix;
  6201. }
  6202. var engine = this.getEngine();
  6203. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6204. if (this.minZ <= 0) {
  6205. this.minZ = 0.1;
  6206. }
  6207. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6208. return this._projectionMatrix;
  6209. }
  6210. var halfWidth = engine.getRenderWidth() / 2.0;
  6211. var halfHeight = engine.getRenderHeight() / 2.0;
  6212. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6213. return this._projectionMatrix;
  6214. };
  6215. Camera.prototype.dispose = function () {
  6216. // Remove from scene
  6217. var index = this.getScene().cameras.indexOf(this);
  6218. this.getScene().cameras.splice(index, 1);
  6219. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6220. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6221. }
  6222. };
  6223. Camera.PERSPECTIVE_CAMERA = 0;
  6224. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6225. return Camera;
  6226. })(BABYLON.Node);
  6227. BABYLON.Camera = Camera;
  6228. })(BABYLON || (BABYLON = {}));
  6229. //# sourceMappingURL=babylon.camera.js.map
  6230. var BABYLON;
  6231. (function (BABYLON) {
  6232. var TargetCamera = (function (_super) {
  6233. __extends(TargetCamera, _super);
  6234. function TargetCamera(name, position, scene) {
  6235. _super.call(this, name, position, scene);
  6236. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6237. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6238. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6239. this.speed = 2.0;
  6240. this.noRotationConstraint = false;
  6241. this.lockedTarget = null;
  6242. this._currentTarget = BABYLON.Vector3.Zero();
  6243. this._viewMatrix = BABYLON.Matrix.Zero();
  6244. this._camMatrix = BABYLON.Matrix.Zero();
  6245. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6246. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6247. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6248. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6249. this._lookAtTemp = BABYLON.Matrix.Zero();
  6250. this._tempMatrix = BABYLON.Matrix.Zero();
  6251. }
  6252. TargetCamera.prototype._getLockedTargetPosition = function () {
  6253. if (!this.lockedTarget) {
  6254. return null;
  6255. }
  6256. return this.lockedTarget.position || this.lockedTarget;
  6257. };
  6258. // Cache
  6259. TargetCamera.prototype._initCache = function () {
  6260. _super.prototype._initCache.call(this);
  6261. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6262. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6263. };
  6264. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6265. if (!ignoreParentClass) {
  6266. _super.prototype._updateCache.call(this);
  6267. }
  6268. var lockedTargetPosition = this._getLockedTargetPosition();
  6269. if (!lockedTargetPosition) {
  6270. this._cache.lockedTarget = null;
  6271. } else {
  6272. if (!this._cache.lockedTarget) {
  6273. this._cache.lockedTarget = lockedTargetPosition.clone();
  6274. } else {
  6275. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6276. }
  6277. }
  6278. this._cache.rotation.copyFrom(this.rotation);
  6279. };
  6280. // Synchronized
  6281. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6282. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6283. return false;
  6284. }
  6285. var lockedTargetPosition = this._getLockedTargetPosition();
  6286. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6287. };
  6288. // Methods
  6289. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6290. var engine = this.getEngine();
  6291. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6292. };
  6293. // Target
  6294. TargetCamera.prototype.setTarget = function (target) {
  6295. this.upVector.normalize();
  6296. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6297. this._camMatrix.invert();
  6298. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6299. var vDir = target.subtract(this.position);
  6300. if (vDir.x >= 0.0) {
  6301. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6302. } else {
  6303. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6304. }
  6305. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6306. if (isNaN(this.rotation.x)) {
  6307. this.rotation.x = 0;
  6308. }
  6309. if (isNaN(this.rotation.y)) {
  6310. this.rotation.y = 0;
  6311. }
  6312. if (isNaN(this.rotation.z)) {
  6313. this.rotation.z = 0;
  6314. }
  6315. };
  6316. TargetCamera.prototype.getTarget = function () {
  6317. return this._currentTarget;
  6318. };
  6319. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6320. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6321. };
  6322. TargetCamera.prototype._updatePosition = function () {
  6323. this.position.addInPlace(this.cameraDirection);
  6324. };
  6325. TargetCamera.prototype._update = function () {
  6326. var needToMove = this._decideIfNeedsToMove();
  6327. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6328. // Move
  6329. if (needToMove) {
  6330. this._updatePosition();
  6331. }
  6332. // Rotate
  6333. if (needToRotate) {
  6334. this.rotation.x += this.cameraRotation.x;
  6335. this.rotation.y += this.cameraRotation.y;
  6336. if (!this.noRotationConstraint) {
  6337. var limit = (Math.PI / 2) * 0.95;
  6338. if (this.rotation.x > limit)
  6339. this.rotation.x = limit;
  6340. if (this.rotation.x < -limit)
  6341. this.rotation.x = -limit;
  6342. }
  6343. }
  6344. // Inertia
  6345. if (needToMove) {
  6346. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6347. this.cameraDirection.x = 0;
  6348. }
  6349. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6350. this.cameraDirection.y = 0;
  6351. }
  6352. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6353. this.cameraDirection.z = 0;
  6354. }
  6355. this.cameraDirection.scaleInPlace(this.inertia);
  6356. }
  6357. if (needToRotate) {
  6358. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6359. this.cameraRotation.x = 0;
  6360. }
  6361. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6362. this.cameraRotation.y = 0;
  6363. }
  6364. this.cameraRotation.scaleInPlace(this.inertia);
  6365. }
  6366. };
  6367. TargetCamera.prototype._getViewMatrix = function () {
  6368. if (!this.lockedTarget) {
  6369. // Compute
  6370. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6371. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6372. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6373. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6374. this._lookAtTemp.invert();
  6375. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6376. } else {
  6377. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6378. }
  6379. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6380. // Computing target and final matrix
  6381. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6382. } else {
  6383. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6384. }
  6385. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6386. return this._viewMatrix;
  6387. };
  6388. return TargetCamera;
  6389. })(BABYLON.Camera);
  6390. BABYLON.TargetCamera = TargetCamera;
  6391. })(BABYLON || (BABYLON = {}));
  6392. //# sourceMappingURL=babylon.targetCamera.js.map
  6393. var BABYLON;
  6394. (function (BABYLON) {
  6395. var FollowCamera = (function (_super) {
  6396. __extends(FollowCamera, _super);
  6397. function FollowCamera(name, position, scene) {
  6398. _super.call(this, name, position, scene);
  6399. this.radius = 12;
  6400. this.rotationOffset = 0;
  6401. this.heightOffset = 4;
  6402. this.cameraAcceleration = 0.05;
  6403. this.maxCameraSpeed = 20;
  6404. }
  6405. FollowCamera.prototype.getRadians = function (degrees) {
  6406. return degrees * Math.PI / 180;
  6407. };
  6408. FollowCamera.prototype.follow = function (cameraTarget) {
  6409. if (!cameraTarget)
  6410. return;
  6411. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6412. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6413. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6414. var dx = targetX - this.position.x;
  6415. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6416. var dz = (targetZ) - this.position.z;
  6417. var vx = dx * this.cameraAcceleration * 2;
  6418. var vy = dy * this.cameraAcceleration;
  6419. var vz = dz * this.cameraAcceleration * 2;
  6420. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6421. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6422. }
  6423. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6424. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6425. }
  6426. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6427. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6428. }
  6429. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6430. this.setTarget(cameraTarget.position);
  6431. };
  6432. FollowCamera.prototype._update = function () {
  6433. _super.prototype._update.call(this);
  6434. this.follow(this.target);
  6435. };
  6436. return FollowCamera;
  6437. })(BABYLON.TargetCamera);
  6438. BABYLON.FollowCamera = FollowCamera;
  6439. })(BABYLON || (BABYLON = {}));
  6440. //# sourceMappingURL=babylon.followCamera.js.map
  6441. var BABYLON;
  6442. (function (BABYLON) {
  6443. var FreeCamera = (function (_super) {
  6444. __extends(FreeCamera, _super);
  6445. function FreeCamera(name, position, scene) {
  6446. _super.call(this, name, position, scene);
  6447. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6448. this.keysUp = [38];
  6449. this.keysDown = [40];
  6450. this.keysLeft = [37];
  6451. this.keysRight = [39];
  6452. this.checkCollisions = false;
  6453. this.applyGravity = false;
  6454. this.angularSensibility = 2000.0;
  6455. this._keys = [];
  6456. this._collider = new BABYLON.Collider();
  6457. this._needMoveForGravity = true;
  6458. this._oldPosition = BABYLON.Vector3.Zero();
  6459. this._diffPosition = BABYLON.Vector3.Zero();
  6460. this._newPosition = BABYLON.Vector3.Zero();
  6461. }
  6462. // Controls
  6463. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6464. var _this = this;
  6465. var previousPosition;
  6466. var engine = this.getEngine();
  6467. if (this._attachedElement) {
  6468. return;
  6469. }
  6470. this._attachedElement = element;
  6471. if (this._onMouseDown === undefined) {
  6472. this._onMouseDown = function (evt) {
  6473. previousPosition = {
  6474. x: evt.clientX,
  6475. y: evt.clientY
  6476. };
  6477. if (!noPreventDefault) {
  6478. evt.preventDefault();
  6479. }
  6480. };
  6481. this._onMouseUp = function (evt) {
  6482. previousPosition = null;
  6483. if (!noPreventDefault) {
  6484. evt.preventDefault();
  6485. }
  6486. };
  6487. this._onMouseOut = function (evt) {
  6488. previousPosition = null;
  6489. _this._keys = [];
  6490. if (!noPreventDefault) {
  6491. evt.preventDefault();
  6492. }
  6493. };
  6494. this._onMouseMove = function (evt) {
  6495. if (!previousPosition && !engine.isPointerLock) {
  6496. return;
  6497. }
  6498. var offsetX;
  6499. var offsetY;
  6500. if (!engine.isPointerLock) {
  6501. offsetX = evt.clientX - previousPosition.x;
  6502. offsetY = evt.clientY - previousPosition.y;
  6503. } else {
  6504. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6505. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6506. }
  6507. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6508. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6509. previousPosition = {
  6510. x: evt.clientX,
  6511. y: evt.clientY
  6512. };
  6513. if (!noPreventDefault) {
  6514. evt.preventDefault();
  6515. }
  6516. };
  6517. this._onKeyDown = function (evt) {
  6518. 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) {
  6519. var index = _this._keys.indexOf(evt.keyCode);
  6520. if (index === -1) {
  6521. _this._keys.push(evt.keyCode);
  6522. }
  6523. if (!noPreventDefault) {
  6524. evt.preventDefault();
  6525. }
  6526. }
  6527. };
  6528. this._onKeyUp = function (evt) {
  6529. 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) {
  6530. var index = _this._keys.indexOf(evt.keyCode);
  6531. if (index >= 0) {
  6532. _this._keys.splice(index, 1);
  6533. }
  6534. if (!noPreventDefault) {
  6535. evt.preventDefault();
  6536. }
  6537. }
  6538. };
  6539. this._onLostFocus = function () {
  6540. _this._keys = [];
  6541. };
  6542. this._reset = function () {
  6543. _this._keys = [];
  6544. previousPosition = null;
  6545. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6546. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6547. };
  6548. }
  6549. element.addEventListener("mousedown", this._onMouseDown, false);
  6550. element.addEventListener("mouseup", this._onMouseUp, false);
  6551. element.addEventListener("mouseout", this._onMouseOut, false);
  6552. element.addEventListener("mousemove", this._onMouseMove, false);
  6553. BABYLON.Tools.RegisterTopRootEvents([
  6554. { name: "keydown", handler: this._onKeyDown },
  6555. { name: "keyup", handler: this._onKeyUp },
  6556. { name: "blur", handler: this._onLostFocus }
  6557. ]);
  6558. };
  6559. FreeCamera.prototype.detachControl = function (element) {
  6560. if (this._attachedElement != element) {
  6561. return;
  6562. }
  6563. element.removeEventListener("mousedown", this._onMouseDown);
  6564. element.removeEventListener("mouseup", this._onMouseUp);
  6565. element.removeEventListener("mouseout", this._onMouseOut);
  6566. element.removeEventListener("mousemove", this._onMouseMove);
  6567. BABYLON.Tools.UnregisterTopRootEvents([
  6568. { name: "keydown", handler: this._onKeyDown },
  6569. { name: "keyup", handler: this._onKeyUp },
  6570. { name: "blur", handler: this._onLostFocus }
  6571. ]);
  6572. this._attachedElement = null;
  6573. if (this._reset) {
  6574. this._reset();
  6575. }
  6576. };
  6577. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6578. var globalPosition;
  6579. if (this.parent) {
  6580. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6581. } else {
  6582. globalPosition = this.position;
  6583. }
  6584. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6585. this._collider.radius = this.ellipsoid;
  6586. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6587. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6588. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6589. this.position.addInPlace(this._diffPosition);
  6590. if (this.onCollide) {
  6591. this.onCollide(this._collider.collidedMesh);
  6592. }
  6593. }
  6594. };
  6595. FreeCamera.prototype._checkInputs = function () {
  6596. if (!this._localDirection) {
  6597. this._localDirection = BABYLON.Vector3.Zero();
  6598. this._transformedDirection = BABYLON.Vector3.Zero();
  6599. }
  6600. for (var index = 0; index < this._keys.length; index++) {
  6601. var keyCode = this._keys[index];
  6602. var speed = this._computeLocalCameraSpeed();
  6603. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6604. this._localDirection.copyFromFloats(-speed, 0, 0);
  6605. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6606. this._localDirection.copyFromFloats(0, 0, speed);
  6607. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6608. this._localDirection.copyFromFloats(speed, 0, 0);
  6609. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6610. this._localDirection.copyFromFloats(0, 0, -speed);
  6611. }
  6612. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6613. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6614. this.cameraDirection.addInPlace(this._transformedDirection);
  6615. }
  6616. };
  6617. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6618. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6619. };
  6620. FreeCamera.prototype._updatePosition = function () {
  6621. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6622. this._collideWithWorld(this.cameraDirection);
  6623. if (this.applyGravity) {
  6624. var oldPosition = this.position;
  6625. this._collideWithWorld(this.getScene().gravity);
  6626. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6627. }
  6628. } else {
  6629. this.position.addInPlace(this.cameraDirection);
  6630. }
  6631. };
  6632. FreeCamera.prototype._update = function () {
  6633. this._checkInputs();
  6634. _super.prototype._update.call(this);
  6635. };
  6636. return FreeCamera;
  6637. })(BABYLON.TargetCamera);
  6638. BABYLON.FreeCamera = FreeCamera;
  6639. })(BABYLON || (BABYLON = {}));
  6640. //# sourceMappingURL=babylon.freeCamera.js.map
  6641. var BABYLON;
  6642. (function (BABYLON) {
  6643. // We're mainly based on the logic defined into the FreeCamera code
  6644. var TouchCamera = (function (_super) {
  6645. __extends(TouchCamera, _super);
  6646. function TouchCamera(name, position, scene) {
  6647. _super.call(this, name, position, scene);
  6648. this._offsetX = null;
  6649. this._offsetY = null;
  6650. this._pointerCount = 0;
  6651. this._pointerPressed = [];
  6652. this.angularSensibility = 200000.0;
  6653. this.moveSensibility = 500.0;
  6654. }
  6655. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6656. var _this = this;
  6657. var previousPosition;
  6658. if (this._attachedCanvas) {
  6659. return;
  6660. }
  6661. this._attachedCanvas = canvas;
  6662. if (this._onPointerDown === undefined) {
  6663. this._onPointerDown = function (evt) {
  6664. if (!noPreventDefault) {
  6665. evt.preventDefault();
  6666. }
  6667. _this._pointerPressed.push(evt.pointerId);
  6668. if (_this._pointerPressed.length !== 1) {
  6669. return;
  6670. }
  6671. previousPosition = {
  6672. x: evt.clientX,
  6673. y: evt.clientY
  6674. };
  6675. };
  6676. this._onPointerUp = function (evt) {
  6677. if (!noPreventDefault) {
  6678. evt.preventDefault();
  6679. }
  6680. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6681. if (index === -1) {
  6682. return;
  6683. }
  6684. _this._pointerPressed.splice(index, 1);
  6685. if (index != 0) {
  6686. return;
  6687. }
  6688. previousPosition = null;
  6689. _this._offsetX = null;
  6690. _this._offsetY = null;
  6691. };
  6692. this._onPointerMove = function (evt) {
  6693. if (!noPreventDefault) {
  6694. evt.preventDefault();
  6695. }
  6696. if (!previousPosition) {
  6697. return;
  6698. }
  6699. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6700. if (index != 0) {
  6701. return;
  6702. }
  6703. _this._offsetX = evt.clientX - previousPosition.x;
  6704. _this._offsetY = -(evt.clientY - previousPosition.y);
  6705. };
  6706. this._onLostFocus = function () {
  6707. _this._offsetX = null;
  6708. _this._offsetY = null;
  6709. };
  6710. }
  6711. canvas.addEventListener("pointerdown", this._onPointerDown);
  6712. canvas.addEventListener("pointerup", this._onPointerUp);
  6713. canvas.addEventListener("pointerout", this._onPointerUp);
  6714. canvas.addEventListener("pointermove", this._onPointerMove);
  6715. BABYLON.Tools.RegisterTopRootEvents([
  6716. { name: "blur", handler: this._onLostFocus }
  6717. ]);
  6718. };
  6719. TouchCamera.prototype.detachControl = function (canvas) {
  6720. if (this._attachedCanvas != canvas) {
  6721. return;
  6722. }
  6723. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6724. canvas.removeEventListener("pointerup", this._onPointerUp);
  6725. canvas.removeEventListener("pointerout", this._onPointerUp);
  6726. canvas.removeEventListener("pointermove", this._onPointerMove);
  6727. BABYLON.Tools.UnregisterTopRootEvents([
  6728. { name: "blur", handler: this._onLostFocus }
  6729. ]);
  6730. this._attachedCanvas = null;
  6731. };
  6732. TouchCamera.prototype._checkInputs = function () {
  6733. if (!this._offsetX) {
  6734. return;
  6735. }
  6736. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6737. if (this._pointerPressed.length > 1) {
  6738. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6739. } else {
  6740. var speed = this._computeLocalCameraSpeed();
  6741. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6742. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6743. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6744. }
  6745. };
  6746. return TouchCamera;
  6747. })(BABYLON.FreeCamera);
  6748. BABYLON.TouchCamera = TouchCamera;
  6749. })(BABYLON || (BABYLON = {}));
  6750. //# sourceMappingURL=babylon.touchCamera.js.map
  6751. var BABYLON;
  6752. (function (BABYLON) {
  6753. // We're mainly based on the logic defined into the FreeCamera code
  6754. var DeviceOrientationCamera = (function (_super) {
  6755. __extends(DeviceOrientationCamera, _super);
  6756. function DeviceOrientationCamera(name, position, scene) {
  6757. var _this = this;
  6758. _super.call(this, name, position, scene);
  6759. this._offsetX = null;
  6760. this._offsetY = null;
  6761. this._orientationGamma = 0;
  6762. this._orientationBeta = 0;
  6763. this._initialOrientationGamma = 0;
  6764. this._initialOrientationBeta = 0;
  6765. this.angularSensibility = 10000.0;
  6766. this.moveSensibility = 50.0;
  6767. window.addEventListener("resize", function () {
  6768. _this._initialOrientationGamma = null;
  6769. }, false);
  6770. }
  6771. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6772. var _this = this;
  6773. if (this._attachedCanvas) {
  6774. return;
  6775. }
  6776. this._attachedCanvas = canvas;
  6777. if (!this._orientationChanged) {
  6778. this._orientationChanged = function (evt) {
  6779. if (!_this._initialOrientationGamma) {
  6780. _this._initialOrientationGamma = evt.gamma;
  6781. _this._initialOrientationBeta = evt.beta;
  6782. }
  6783. _this._orientationGamma = evt.gamma;
  6784. _this._orientationBeta = evt.beta;
  6785. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6786. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6787. };
  6788. }
  6789. window.addEventListener("deviceorientation", this._orientationChanged);
  6790. };
  6791. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6792. if (this._attachedCanvas != canvas) {
  6793. return;
  6794. }
  6795. window.removeEventListener("deviceorientation", this._orientationChanged);
  6796. this._attachedCanvas = null;
  6797. this._orientationGamma = 0;
  6798. this._orientationBeta = 0;
  6799. this._initialOrientationGamma = 0;
  6800. this._initialOrientationBeta = 0;
  6801. };
  6802. DeviceOrientationCamera.prototype._checkInputs = function () {
  6803. if (!this._offsetX) {
  6804. return;
  6805. }
  6806. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6807. var speed = this._computeLocalCameraSpeed();
  6808. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6809. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6810. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6811. };
  6812. return DeviceOrientationCamera;
  6813. })(BABYLON.FreeCamera);
  6814. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6815. })(BABYLON || (BABYLON = {}));
  6816. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6817. var BABYLON;
  6818. (function (BABYLON) {
  6819. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6820. var ArcRotateCamera = (function (_super) {
  6821. __extends(ArcRotateCamera, _super);
  6822. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6823. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6824. this.alpha = alpha;
  6825. this.beta = beta;
  6826. this.radius = radius;
  6827. this.target = target;
  6828. this.inertialAlphaOffset = 0;
  6829. this.inertialBetaOffset = 0;
  6830. this.inertialRadiusOffset = 0;
  6831. this.lowerAlphaLimit = null;
  6832. this.upperAlphaLimit = null;
  6833. this.lowerBetaLimit = 0.01;
  6834. this.upperBetaLimit = Math.PI;
  6835. this.lowerRadiusLimit = null;
  6836. this.upperRadiusLimit = null;
  6837. this.angularSensibility = 1000.0;
  6838. this.wheelPrecision = 3.0;
  6839. this.keysUp = [38];
  6840. this.keysDown = [40];
  6841. this.keysLeft = [37];
  6842. this.keysRight = [39];
  6843. this.zoomOnFactor = 1;
  6844. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6845. this._keys = [];
  6846. this._viewMatrix = new BABYLON.Matrix();
  6847. this.checkCollisions = false;
  6848. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6849. this._collider = new BABYLON.Collider();
  6850. this._previousPosition = BABYLON.Vector3.Zero();
  6851. this._collisionVelocity = BABYLON.Vector3.Zero();
  6852. this._newPosition = BABYLON.Vector3.Zero();
  6853. // Pinch
  6854. // value for pinch step scaling
  6855. // set to 20 by default
  6856. this.pinchPrecision = 20;
  6857. this.getViewMatrix();
  6858. }
  6859. ArcRotateCamera.prototype._getTargetPosition = function () {
  6860. return this.target.position || this.target;
  6861. };
  6862. // Cache
  6863. ArcRotateCamera.prototype._initCache = function () {
  6864. _super.prototype._initCache.call(this);
  6865. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6866. this._cache.alpha = undefined;
  6867. this._cache.beta = undefined;
  6868. this._cache.radius = undefined;
  6869. this._cache.targetScreenOffset = undefined;
  6870. };
  6871. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6872. if (!ignoreParentClass) {
  6873. _super.prototype._updateCache.call(this);
  6874. }
  6875. this._cache.target.copyFrom(this._getTargetPosition());
  6876. this._cache.alpha = this.alpha;
  6877. this._cache.beta = this.beta;
  6878. this._cache.radius = this.radius;
  6879. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6880. };
  6881. // Synchronized
  6882. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6883. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6884. return false;
  6885. 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);
  6886. };
  6887. // Methods
  6888. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6889. var _this = this;
  6890. var previousPosition;
  6891. var pointerId;
  6892. // to know if pinch started
  6893. var pinchStarted = false;
  6894. // two pinch point on X
  6895. // that will use for find if user action is pinch open or pinch close
  6896. var pinchPointX1, pinchPointX2;
  6897. if (this._attachedElement) {
  6898. return;
  6899. }
  6900. this._attachedElement = element;
  6901. var engine = this.getEngine();
  6902. if (this._onPointerDown === undefined) {
  6903. this._onPointerDown = function (evt) {
  6904. if (pointerId) {
  6905. return;
  6906. }
  6907. pointerId = evt.pointerId;
  6908. previousPosition = {
  6909. x: evt.clientX,
  6910. y: evt.clientY
  6911. };
  6912. if (!noPreventDefault) {
  6913. evt.preventDefault();
  6914. }
  6915. };
  6916. this._onPointerUp = function (evt) {
  6917. previousPosition = null;
  6918. pointerId = null;
  6919. if (!noPreventDefault) {
  6920. evt.preventDefault();
  6921. }
  6922. };
  6923. this._onPointerMove = function (evt) {
  6924. if (!previousPosition) {
  6925. return;
  6926. }
  6927. if (pointerId !== evt.pointerId) {
  6928. return;
  6929. }
  6930. // return pinch is started
  6931. if (pinchStarted) {
  6932. return;
  6933. }
  6934. var offsetX = evt.clientX - previousPosition.x;
  6935. var offsetY = evt.clientY - previousPosition.y;
  6936. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6937. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6938. previousPosition = {
  6939. x: evt.clientX,
  6940. y: evt.clientY
  6941. };
  6942. if (!noPreventDefault) {
  6943. evt.preventDefault();
  6944. }
  6945. };
  6946. this._onMouseMove = function (evt) {
  6947. if (!engine.isPointerLock) {
  6948. return;
  6949. }
  6950. // return pinch is started
  6951. if (pinchStarted) {
  6952. return;
  6953. }
  6954. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6955. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6956. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6957. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6958. if (!noPreventDefault) {
  6959. evt.preventDefault();
  6960. }
  6961. };
  6962. this._wheel = function (event) {
  6963. var delta = 0;
  6964. if (event.wheelDelta) {
  6965. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6966. } else if (event.detail) {
  6967. delta = -event.detail / _this.wheelPrecision;
  6968. }
  6969. if (delta)
  6970. _this.inertialRadiusOffset += delta;
  6971. if (event.preventDefault) {
  6972. if (!noPreventDefault) {
  6973. event.preventDefault();
  6974. }
  6975. }
  6976. };
  6977. this._onKeyDown = function (evt) {
  6978. 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) {
  6979. var index = _this._keys.indexOf(evt.keyCode);
  6980. if (index === -1) {
  6981. _this._keys.push(evt.keyCode);
  6982. }
  6983. if (evt.preventDefault) {
  6984. if (!noPreventDefault) {
  6985. evt.preventDefault();
  6986. }
  6987. }
  6988. }
  6989. };
  6990. this._onKeyUp = function (evt) {
  6991. 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) {
  6992. var index = _this._keys.indexOf(evt.keyCode);
  6993. if (index >= 0) {
  6994. _this._keys.splice(index, 1);
  6995. }
  6996. if (evt.preventDefault) {
  6997. if (!noPreventDefault) {
  6998. evt.preventDefault();
  6999. }
  7000. }
  7001. }
  7002. };
  7003. this._onLostFocus = function () {
  7004. _this._keys = [];
  7005. pointerId = null;
  7006. };
  7007. this._onGestureStart = function (e) {
  7008. if (window.MSGesture === undefined) {
  7009. return;
  7010. }
  7011. if (!_this._MSGestureHandler) {
  7012. _this._MSGestureHandler = new MSGesture();
  7013. _this._MSGestureHandler.target = element;
  7014. }
  7015. _this._MSGestureHandler.addPointer(e.pointerId);
  7016. };
  7017. this._onGesture = function (e) {
  7018. _this.radius *= e.scale;
  7019. if (e.preventDefault) {
  7020. if (!noPreventDefault) {
  7021. e.stopPropagation();
  7022. e.preventDefault();
  7023. }
  7024. }
  7025. };
  7026. this._reset = function () {
  7027. _this._keys = [];
  7028. _this.inertialAlphaOffset = 0;
  7029. _this.inertialBetaOffset = 0;
  7030. _this.inertialRadiusOffset = 0;
  7031. previousPosition = null;
  7032. pointerId = null;
  7033. };
  7034. this._touchStart = function (event) {
  7035. if (event.touches.length === 2) {
  7036. //-- start pinch if two fingers on the screen
  7037. pinchStarted = true;
  7038. _this._pinchStart(event);
  7039. }
  7040. };
  7041. this._touchMove = function (event) {
  7042. if (pinchStarted) {
  7043. //-- make scaling
  7044. _this._pinchMove(event);
  7045. }
  7046. };
  7047. this._touchEnd = function (event) {
  7048. if (pinchStarted) {
  7049. //-- end of pinch
  7050. _this._pinchEnd(event);
  7051. }
  7052. };
  7053. this._pinchStart = function (event) {
  7054. // save origin touch point
  7055. pinchPointX1 = event.touches[0].clientX;
  7056. pinchPointX2 = event.touches[1].clientX;
  7057. // block the camera
  7058. // if not it rotate around target during pinch
  7059. pinchStarted = true;
  7060. };
  7061. this._pinchMove = function (event) {
  7062. // variable for new camera's radius
  7063. var delta = 0;
  7064. // variables to know if pinch open or pinch close
  7065. var direction = 1;
  7066. var distanceXOrigine, distanceXNow;
  7067. if (event.touches.length !== 2)
  7068. return;
  7069. // calculate absolute distances of the two fingers
  7070. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7071. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7072. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7073. if (distanceXNow < distanceXOrigine) {
  7074. direction = -1;
  7075. }
  7076. // calculate new radius
  7077. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7078. // set new radius
  7079. _this.inertialRadiusOffset -= delta;
  7080. // save origin touch point
  7081. pinchPointX1 = event.touches[0].clientX;
  7082. pinchPointX2 = event.touches[1].clientX;
  7083. };
  7084. this._pinchEnd = function (event) {
  7085. // cancel pinch and deblock camera rotation
  7086. pinchStarted = false;
  7087. };
  7088. }
  7089. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7090. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7091. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7092. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7093. element.addEventListener("mousemove", this._onMouseMove, false);
  7094. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7095. element.addEventListener("MSGestureChange", this._onGesture, false);
  7096. element.addEventListener('mousewheel', this._wheel, false);
  7097. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7098. // pinch
  7099. element.addEventListener('touchstart', this._touchStart, false);
  7100. element.addEventListener('touchmove', this._touchMove, false);
  7101. element.addEventListener('touchend', this._touchEnd, false);
  7102. BABYLON.Tools.RegisterTopRootEvents([
  7103. { name: "keydown", handler: this._onKeyDown },
  7104. { name: "keyup", handler: this._onKeyUp },
  7105. { name: "blur", handler: this._onLostFocus }
  7106. ]);
  7107. };
  7108. ArcRotateCamera.prototype.detachControl = function (element) {
  7109. if (this._attachedElement != element) {
  7110. return;
  7111. }
  7112. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7113. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7114. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7115. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7116. element.removeEventListener("mousemove", this._onMouseMove);
  7117. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7118. element.removeEventListener("MSGestureChange", this._onGesture);
  7119. element.removeEventListener('mousewheel', this._wheel);
  7120. element.removeEventListener('DOMMouseScroll', this._wheel);
  7121. // pinch
  7122. element.removeEventListener('touchstart', this._touchStart);
  7123. element.removeEventListener('touchmove', this._touchMove);
  7124. element.removeEventListener('touchend', this._touchEnd);
  7125. BABYLON.Tools.UnregisterTopRootEvents([
  7126. { name: "keydown", handler: this._onKeyDown },
  7127. { name: "keyup", handler: this._onKeyUp },
  7128. { name: "blur", handler: this._onLostFocus }
  7129. ]);
  7130. this._MSGestureHandler = null;
  7131. this._attachedElement = null;
  7132. if (this._reset) {
  7133. this._reset();
  7134. }
  7135. };
  7136. ArcRotateCamera.prototype._update = function () {
  7137. for (var index = 0; index < this._keys.length; index++) {
  7138. var keyCode = this._keys[index];
  7139. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7140. this.inertialAlphaOffset -= 0.01;
  7141. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  7142. this.inertialBetaOffset -= 0.01;
  7143. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  7144. this.inertialAlphaOffset += 0.01;
  7145. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  7146. this.inertialBetaOffset += 0.01;
  7147. }
  7148. }
  7149. // Inertia
  7150. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7151. this.alpha += this.inertialAlphaOffset;
  7152. this.beta += this.inertialBetaOffset;
  7153. this.radius -= this.inertialRadiusOffset;
  7154. this.inertialAlphaOffset *= this.inertia;
  7155. this.inertialBetaOffset *= this.inertia;
  7156. this.inertialRadiusOffset *= this.inertia;
  7157. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7158. this.inertialAlphaOffset = 0;
  7159. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7160. this.inertialBetaOffset = 0;
  7161. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7162. this.inertialRadiusOffset = 0;
  7163. }
  7164. // Limits
  7165. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7166. this.alpha = this.lowerAlphaLimit;
  7167. }
  7168. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7169. this.alpha = this.upperAlphaLimit;
  7170. }
  7171. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7172. this.beta = this.lowerBetaLimit;
  7173. }
  7174. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7175. this.beta = this.upperBetaLimit;
  7176. }
  7177. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7178. this.radius = this.lowerRadiusLimit;
  7179. }
  7180. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7181. this.radius = this.upperRadiusLimit;
  7182. }
  7183. };
  7184. ArcRotateCamera.prototype.setPosition = function (position) {
  7185. var radiusv3 = position.subtract(this._getTargetPosition());
  7186. this.radius = radiusv3.length();
  7187. // Alpha
  7188. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7189. if (radiusv3.z < 0) {
  7190. this.alpha = 2 * Math.PI - this.alpha;
  7191. }
  7192. // Beta
  7193. this.beta = Math.acos(radiusv3.y / this.radius);
  7194. };
  7195. ArcRotateCamera.prototype._getViewMatrix = function () {
  7196. // Compute
  7197. var cosa = Math.cos(this.alpha);
  7198. var sina = Math.sin(this.alpha);
  7199. var cosb = Math.cos(this.beta);
  7200. var sinb = Math.sin(this.beta);
  7201. var target = this._getTargetPosition();
  7202. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7203. if (this.checkCollisions) {
  7204. this._collider.radius = this.collisionRadius;
  7205. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7206. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7207. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7208. this.position.copyFrom(this._previousPosition);
  7209. this.alpha = this._previousAlpha;
  7210. this.beta = this._previousBeta;
  7211. this.radius = this._previousRadius;
  7212. if (this.onCollide) {
  7213. this.onCollide(this._collider.collidedMesh);
  7214. }
  7215. }
  7216. }
  7217. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7218. this._previousAlpha = this.alpha;
  7219. this._previousBeta = this.beta;
  7220. this._previousRadius = this.radius;
  7221. this._previousPosition.copyFrom(this.position);
  7222. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7223. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7224. return this._viewMatrix;
  7225. };
  7226. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7227. meshes = meshes || this.getScene().meshes;
  7228. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7229. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7230. this.radius = distance * this.zoomOnFactor;
  7231. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7232. };
  7233. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7234. var meshesOrMinMaxVector;
  7235. var distance;
  7236. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7237. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7238. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7239. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7240. } else {
  7241. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7242. distance = meshesOrMinMaxVectorAndDistance.distance;
  7243. }
  7244. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7245. this.maxZ = distance * 2;
  7246. };
  7247. return ArcRotateCamera;
  7248. })(BABYLON.Camera);
  7249. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7250. })(BABYLON || (BABYLON = {}));
  7251. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7252. var BABYLON;
  7253. (function (BABYLON) {
  7254. /**
  7255. * Represents a scene to be rendered by the engine.
  7256. * @see http://doc.babylonjs.com/page.php?p=21911
  7257. */
  7258. var Scene = (function () {
  7259. /**
  7260. * @constructor
  7261. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7262. */
  7263. function Scene(engine) {
  7264. // Members
  7265. this.autoClear = true;
  7266. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7267. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7268. this.forceWireframe = false;
  7269. this.forcePointsCloud = false;
  7270. this.forceShowBoundingBoxes = false;
  7271. this.animationsEnabled = true;
  7272. this.cameraToUseForPointers = null;
  7273. // Fog
  7274. /**
  7275. * is fog enabled on this scene.
  7276. * @type {boolean}
  7277. */
  7278. this.fogEnabled = true;
  7279. this.fogMode = Scene.FOGMODE_NONE;
  7280. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7281. this.fogDensity = 0.1;
  7282. this.fogStart = 0;
  7283. this.fogEnd = 1000.0;
  7284. // Lights
  7285. /**
  7286. * is shadow enabled on this scene.
  7287. * @type {boolean}
  7288. */
  7289. this.shadowsEnabled = true;
  7290. /**
  7291. * is light enabled on this scene.
  7292. * @type {boolean}
  7293. */
  7294. this.lightsEnabled = true;
  7295. /**
  7296. * All of the lights added to this scene.
  7297. * @see BABYLON.Light
  7298. * @type {BABYLON.Light[]}
  7299. */
  7300. this.lights = new Array();
  7301. // Cameras
  7302. /**
  7303. * All of the cameras added to this scene.
  7304. * @see BABYLON.Camera
  7305. * @type {BABYLON.Camera[]}
  7306. */
  7307. this.cameras = new Array();
  7308. this.activeCameras = new Array();
  7309. // Meshes
  7310. /**
  7311. * All of the (abstract) meshes added to this scene.
  7312. * @see BABYLON.AbstractMesh
  7313. * @type {BABYLON.AbstractMesh[]}
  7314. */
  7315. this.meshes = new Array();
  7316. // Geometries
  7317. this._geometries = new Array();
  7318. this.materials = new Array();
  7319. this.multiMaterials = new Array();
  7320. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7321. // Textures
  7322. this.texturesEnabled = true;
  7323. this.textures = new Array();
  7324. // Particles
  7325. this.particlesEnabled = true;
  7326. this.particleSystems = new Array();
  7327. // Sprites
  7328. this.spriteManagers = new Array();
  7329. // Layers
  7330. this.layers = new Array();
  7331. // Skeletons
  7332. this.skeletonsEnabled = true;
  7333. this.skeletons = new Array();
  7334. // Lens flares
  7335. this.lensFlaresEnabled = true;
  7336. this.lensFlareSystems = new Array();
  7337. // Collisions
  7338. this.collisionsEnabled = true;
  7339. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7340. // Postprocesses
  7341. this.postProcessesEnabled = true;
  7342. // Customs render targets
  7343. this.renderTargetsEnabled = true;
  7344. this.customRenderTargets = new Array();
  7345. // Imported meshes
  7346. this.importedMeshesFiles = new Array();
  7347. this._actionManagers = new Array();
  7348. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7349. // Procedural textures
  7350. this.proceduralTexturesEnabled = true;
  7351. this._proceduralTextures = new Array();
  7352. this.soundTracks = new Array();
  7353. this._totalVertices = 0;
  7354. this._activeVertices = 0;
  7355. this._activeParticles = 0;
  7356. this._lastFrameDuration = 0;
  7357. this._evaluateActiveMeshesDuration = 0;
  7358. this._renderTargetsDuration = 0;
  7359. this._particlesDuration = 0;
  7360. this._renderDuration = 0;
  7361. this._spritesDuration = 0;
  7362. this._animationRatio = 0;
  7363. this._renderId = 0;
  7364. this._executeWhenReadyTimeoutId = -1;
  7365. this._toBeDisposed = new BABYLON.SmartArray(256);
  7366. this._onReadyCallbacks = new Array();
  7367. this._pendingData = [];
  7368. this._onBeforeRenderCallbacks = new Array();
  7369. this._onAfterRenderCallbacks = new Array();
  7370. this._activeMeshes = new BABYLON.SmartArray(256);
  7371. this._processedMaterials = new BABYLON.SmartArray(256);
  7372. this._renderTargets = new BABYLON.SmartArray(256);
  7373. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7374. this._activeSkeletons = new BABYLON.SmartArray(32);
  7375. this._activeBones = 0;
  7376. this._activeAnimatables = new Array();
  7377. this._transformMatrix = BABYLON.Matrix.Zero();
  7378. this._scaledPosition = BABYLON.Vector3.Zero();
  7379. this._scaledVelocity = BABYLON.Vector3.Zero();
  7380. this._engine = engine;
  7381. engine.scenes.push(this);
  7382. this._renderingManager = new BABYLON.RenderingManager(this);
  7383. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7384. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7385. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7386. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7387. this.attachControl();
  7388. this._debugLayer = new BABYLON.DebugLayer(this);
  7389. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7390. }
  7391. Object.defineProperty(Scene.prototype, "debugLayer", {
  7392. // Properties
  7393. get: function () {
  7394. return this._debugLayer;
  7395. },
  7396. enumerable: true,
  7397. configurable: true
  7398. });
  7399. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7400. /**
  7401. * The mesh that is currently under the pointer.
  7402. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7403. */
  7404. get: function () {
  7405. return this._meshUnderPointer;
  7406. },
  7407. enumerable: true,
  7408. configurable: true
  7409. });
  7410. Object.defineProperty(Scene.prototype, "pointerX", {
  7411. /**
  7412. * Current on-screen X position of the pointer
  7413. * @return {number} X position of the pointer
  7414. */
  7415. get: function () {
  7416. return this._pointerX;
  7417. },
  7418. enumerable: true,
  7419. configurable: true
  7420. });
  7421. Object.defineProperty(Scene.prototype, "pointerY", {
  7422. /**
  7423. * Current on-screen Y position of the pointer
  7424. * @return {number} Y position of the pointer
  7425. */
  7426. get: function () {
  7427. return this._pointerY;
  7428. },
  7429. enumerable: true,
  7430. configurable: true
  7431. });
  7432. Scene.prototype.getCachedMaterial = function () {
  7433. return this._cachedMaterial;
  7434. };
  7435. Scene.prototype.getBoundingBoxRenderer = function () {
  7436. return this._boundingBoxRenderer;
  7437. };
  7438. Scene.prototype.getOutlineRenderer = function () {
  7439. return this._outlineRenderer;
  7440. };
  7441. Scene.prototype.getEngine = function () {
  7442. return this._engine;
  7443. };
  7444. Scene.prototype.getTotalVertices = function () {
  7445. return this._totalVertices;
  7446. };
  7447. Scene.prototype.getActiveVertices = function () {
  7448. return this._activeVertices;
  7449. };
  7450. Scene.prototype.getActiveParticles = function () {
  7451. return this._activeParticles;
  7452. };
  7453. Scene.prototype.getActiveBones = function () {
  7454. return this._activeBones;
  7455. };
  7456. // Stats
  7457. Scene.prototype.getLastFrameDuration = function () {
  7458. return this._lastFrameDuration;
  7459. };
  7460. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7461. return this._evaluateActiveMeshesDuration;
  7462. };
  7463. Scene.prototype.getActiveMeshes = function () {
  7464. return this._activeMeshes;
  7465. };
  7466. Scene.prototype.getRenderTargetsDuration = function () {
  7467. return this._renderTargetsDuration;
  7468. };
  7469. Scene.prototype.getRenderDuration = function () {
  7470. return this._renderDuration;
  7471. };
  7472. Scene.prototype.getParticlesDuration = function () {
  7473. return this._particlesDuration;
  7474. };
  7475. Scene.prototype.getSpritesDuration = function () {
  7476. return this._spritesDuration;
  7477. };
  7478. Scene.prototype.getAnimationRatio = function () {
  7479. return this._animationRatio;
  7480. };
  7481. Scene.prototype.getRenderId = function () {
  7482. return this._renderId;
  7483. };
  7484. Scene.prototype._updatePointerPosition = function (evt) {
  7485. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7486. this._pointerX = evt.clientX - canvasRect.left;
  7487. this._pointerY = evt.clientY - canvasRect.top;
  7488. if (this.cameraToUseForPointers) {
  7489. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7490. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7491. }
  7492. };
  7493. // Pointers handling
  7494. Scene.prototype.attachControl = function () {
  7495. var _this = this;
  7496. this._onPointerMove = function (evt) {
  7497. var canvas = _this._engine.getRenderingCanvas();
  7498. _this._updatePointerPosition(evt);
  7499. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7500. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7501. }, false, _this.cameraToUseForPointers);
  7502. if (pickResult.hit) {
  7503. _this._meshUnderPointer = pickResult.pickedMesh;
  7504. _this.setPointerOverMesh(pickResult.pickedMesh);
  7505. canvas.style.cursor = "pointer";
  7506. } else {
  7507. _this.setPointerOverMesh(null);
  7508. canvas.style.cursor = "";
  7509. _this._meshUnderPointer = null;
  7510. }
  7511. };
  7512. this._onPointerDown = function (evt) {
  7513. var predicate = null;
  7514. if (!_this.onPointerDown) {
  7515. predicate = function (mesh) {
  7516. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7517. };
  7518. }
  7519. _this._updatePointerPosition(evt);
  7520. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7521. if (pickResult.hit) {
  7522. if (pickResult.pickedMesh.actionManager) {
  7523. switch (evt.button) {
  7524. case 0:
  7525. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7526. break;
  7527. case 1:
  7528. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7529. break;
  7530. case 2:
  7531. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7532. break;
  7533. }
  7534. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7535. }
  7536. }
  7537. if (_this.onPointerDown) {
  7538. _this.onPointerDown(evt, pickResult);
  7539. }
  7540. };
  7541. this._onKeyDown = function (evt) {
  7542. if (_this.actionManager) {
  7543. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7544. }
  7545. };
  7546. this._onKeyUp = function (evt) {
  7547. if (_this.actionManager) {
  7548. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7549. }
  7550. };
  7551. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7552. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7553. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7554. window.addEventListener("keydown", this._onKeyDown, false);
  7555. window.addEventListener("keyup", this._onKeyUp, false);
  7556. };
  7557. Scene.prototype.detachControl = function () {
  7558. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7559. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7560. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7561. window.removeEventListener("keydown", this._onKeyDown);
  7562. window.removeEventListener("keyup", this._onKeyUp);
  7563. };
  7564. // Ready
  7565. Scene.prototype.isReady = function () {
  7566. if (this._pendingData.length > 0) {
  7567. return false;
  7568. }
  7569. for (var index = 0; index < this._geometries.length; index++) {
  7570. var geometry = this._geometries[index];
  7571. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7572. return false;
  7573. }
  7574. }
  7575. for (index = 0; index < this.meshes.length; index++) {
  7576. var mesh = this.meshes[index];
  7577. if (!mesh.isReady()) {
  7578. return false;
  7579. }
  7580. var mat = mesh.material;
  7581. if (mat) {
  7582. if (!mat.isReady(mesh)) {
  7583. return false;
  7584. }
  7585. }
  7586. }
  7587. return true;
  7588. };
  7589. Scene.prototype.resetCachedMaterial = function () {
  7590. this._cachedMaterial = null;
  7591. };
  7592. Scene.prototype.registerBeforeRender = function (func) {
  7593. this._onBeforeRenderCallbacks.push(func);
  7594. };
  7595. Scene.prototype.unregisterBeforeRender = function (func) {
  7596. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7597. if (index > -1) {
  7598. this._onBeforeRenderCallbacks.splice(index, 1);
  7599. }
  7600. };
  7601. Scene.prototype.registerAfterRender = function (func) {
  7602. this._onAfterRenderCallbacks.push(func);
  7603. };
  7604. Scene.prototype.unregisterAfterRender = function (func) {
  7605. var index = this._onAfterRenderCallbacks.indexOf(func);
  7606. if (index > -1) {
  7607. this._onAfterRenderCallbacks.splice(index, 1);
  7608. }
  7609. };
  7610. Scene.prototype._addPendingData = function (data) {
  7611. this._pendingData.push(data);
  7612. };
  7613. Scene.prototype._removePendingData = function (data) {
  7614. var index = this._pendingData.indexOf(data);
  7615. if (index !== -1) {
  7616. this._pendingData.splice(index, 1);
  7617. }
  7618. };
  7619. Scene.prototype.getWaitingItemsCount = function () {
  7620. return this._pendingData.length;
  7621. };
  7622. /**
  7623. * Registers a function to be executed when the scene is ready.
  7624. * @param {Function} func - the function to be executed.
  7625. */
  7626. Scene.prototype.executeWhenReady = function (func) {
  7627. var _this = this;
  7628. this._onReadyCallbacks.push(func);
  7629. if (this._executeWhenReadyTimeoutId !== -1) {
  7630. return;
  7631. }
  7632. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7633. _this._checkIsReady();
  7634. }, 150);
  7635. };
  7636. Scene.prototype._checkIsReady = function () {
  7637. var _this = this;
  7638. if (this.isReady()) {
  7639. this._onReadyCallbacks.forEach(function (func) {
  7640. func();
  7641. });
  7642. this._onReadyCallbacks = [];
  7643. this._executeWhenReadyTimeoutId = -1;
  7644. return;
  7645. }
  7646. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7647. _this._checkIsReady();
  7648. }, 150);
  7649. };
  7650. // Animations
  7651. /**
  7652. * Will start the animation sequence of a given target
  7653. * @param target - the target
  7654. * @param {number} from - from which frame should animation start
  7655. * @param {number} to - till which frame should animation run.
  7656. * @param {boolean} [loop] - should the animation loop
  7657. * @param {number} [speedRatio] - the speed in which to run the animation
  7658. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7659. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7660. * @return {BABYLON.Animatable} the animatable object created for this animation
  7661. * @see BABYLON.Animatable
  7662. * @see http://doc.babylonjs.com/page.php?p=22081
  7663. */
  7664. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7665. if (speedRatio === undefined) {
  7666. speedRatio = 1.0;
  7667. }
  7668. this.stopAnimation(target);
  7669. if (!animatable) {
  7670. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7671. }
  7672. // Local animations
  7673. if (target.animations) {
  7674. animatable.appendAnimations(target, target.animations);
  7675. }
  7676. // Children animations
  7677. if (target.getAnimatables) {
  7678. var animatables = target.getAnimatables();
  7679. for (var index = 0; index < animatables.length; index++) {
  7680. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7681. }
  7682. }
  7683. return animatable;
  7684. };
  7685. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7686. if (speedRatio === undefined) {
  7687. speedRatio = 1.0;
  7688. }
  7689. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7690. return animatable;
  7691. };
  7692. Scene.prototype.getAnimatableByTarget = function (target) {
  7693. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7694. if (this._activeAnimatables[index].target === target) {
  7695. return this._activeAnimatables[index];
  7696. }
  7697. }
  7698. return null;
  7699. };
  7700. /**
  7701. * Will stop the animation of the given target
  7702. * @param target - the target
  7703. * @see beginAnimation
  7704. */
  7705. Scene.prototype.stopAnimation = function (target) {
  7706. var animatable = this.getAnimatableByTarget(target);
  7707. if (animatable) {
  7708. animatable.stop();
  7709. }
  7710. };
  7711. Scene.prototype._animate = function () {
  7712. if (!this.animationsEnabled) {
  7713. return;
  7714. }
  7715. if (!this._animationStartDate) {
  7716. this._animationStartDate = BABYLON.Tools.Now;
  7717. }
  7718. // Getting time
  7719. var now = BABYLON.Tools.Now;
  7720. var delay = now - this._animationStartDate;
  7721. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7722. if (!this._activeAnimatables[index]._animate(delay)) {
  7723. this._activeAnimatables.splice(index, 1);
  7724. index--;
  7725. }
  7726. }
  7727. };
  7728. // Matrix
  7729. Scene.prototype.getViewMatrix = function () {
  7730. return this._viewMatrix;
  7731. };
  7732. Scene.prototype.getProjectionMatrix = function () {
  7733. return this._projectionMatrix;
  7734. };
  7735. Scene.prototype.getTransformMatrix = function () {
  7736. return this._transformMatrix;
  7737. };
  7738. Scene.prototype.setTransformMatrix = function (view, projection) {
  7739. this._viewMatrix = view;
  7740. this._projectionMatrix = projection;
  7741. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7742. };
  7743. // Methods
  7744. /**
  7745. * sets the active camera of the scene using its ID
  7746. * @param {string} id - the camera's ID
  7747. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7748. * @see activeCamera
  7749. */
  7750. Scene.prototype.setActiveCameraByID = function (id) {
  7751. var camera = this.getCameraByID(id);
  7752. if (camera) {
  7753. this.activeCamera = camera;
  7754. return camera;
  7755. }
  7756. return null;
  7757. };
  7758. /**
  7759. * sets the active camera of the scene using its name
  7760. * @param {string} name - the camera's name
  7761. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7762. * @see activeCamera
  7763. */
  7764. Scene.prototype.setActiveCameraByName = function (name) {
  7765. var camera = this.getCameraByName(name);
  7766. if (camera) {
  7767. this.activeCamera = camera;
  7768. return camera;
  7769. }
  7770. return null;
  7771. };
  7772. /**
  7773. * get a material using its id
  7774. * @param {string} the material's ID
  7775. * @return {BABYLON.Material|null} the material or null if none found.
  7776. */
  7777. Scene.prototype.getMaterialByID = function (id) {
  7778. for (var index = 0; index < this.materials.length; index++) {
  7779. if (this.materials[index].id === id) {
  7780. return this.materials[index];
  7781. }
  7782. }
  7783. return null;
  7784. };
  7785. /**
  7786. * get a material using its name
  7787. * @param {string} the material's name
  7788. * @return {BABYLON.Material|null} the material or null if none found.
  7789. */
  7790. Scene.prototype.getMaterialByName = function (name) {
  7791. for (var index = 0; index < this.materials.length; index++) {
  7792. if (this.materials[index].name === name) {
  7793. return this.materials[index];
  7794. }
  7795. }
  7796. return null;
  7797. };
  7798. Scene.prototype.getCameraByID = function (id) {
  7799. for (var index = 0; index < this.cameras.length; index++) {
  7800. if (this.cameras[index].id === id) {
  7801. return this.cameras[index];
  7802. }
  7803. }
  7804. return null;
  7805. };
  7806. /**
  7807. * get a camera using its name
  7808. * @param {string} the camera's name
  7809. * @return {BABYLON.Camera|null} the camera or null if none found.
  7810. */
  7811. Scene.prototype.getCameraByName = function (name) {
  7812. for (var index = 0; index < this.cameras.length; index++) {
  7813. if (this.cameras[index].name === name) {
  7814. return this.cameras[index];
  7815. }
  7816. }
  7817. return null;
  7818. };
  7819. /**
  7820. * get a light node using its name
  7821. * @param {string} the light's name
  7822. * @return {BABYLON.Light|null} the light or null if none found.
  7823. */
  7824. Scene.prototype.getLightByName = function (name) {
  7825. for (var index = 0; index < this.lights.length; index++) {
  7826. if (this.lights[index].name === name) {
  7827. return this.lights[index];
  7828. }
  7829. }
  7830. return null;
  7831. };
  7832. /**
  7833. * get a light node using its ID
  7834. * @param {string} the light's id
  7835. * @return {BABYLON.Light|null} the light or null if none found.
  7836. */
  7837. Scene.prototype.getLightByID = function (id) {
  7838. for (var index = 0; index < this.lights.length; index++) {
  7839. if (this.lights[index].id === id) {
  7840. return this.lights[index];
  7841. }
  7842. }
  7843. return null;
  7844. };
  7845. /**
  7846. * get a geometry using its ID
  7847. * @param {string} the geometry's id
  7848. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  7849. */
  7850. Scene.prototype.getGeometryByID = function (id) {
  7851. for (var index = 0; index < this._geometries.length; index++) {
  7852. if (this._geometries[index].id === id) {
  7853. return this._geometries[index];
  7854. }
  7855. }
  7856. return null;
  7857. };
  7858. /**
  7859. * add a new geometry to this scene.
  7860. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  7861. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  7862. * @return {boolean} was the geometry added or not
  7863. */
  7864. Scene.prototype.pushGeometry = function (geometry, force) {
  7865. if (!force && this.getGeometryByID(geometry.id)) {
  7866. return false;
  7867. }
  7868. this._geometries.push(geometry);
  7869. return true;
  7870. };
  7871. Scene.prototype.getGeometries = function () {
  7872. return this._geometries;
  7873. };
  7874. /**
  7875. * Get a the first added mesh found of a given ID
  7876. * @param {string} id - the id to search for
  7877. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  7878. */
  7879. Scene.prototype.getMeshByID = function (id) {
  7880. for (var index = 0; index < this.meshes.length; index++) {
  7881. if (this.meshes[index].id === id) {
  7882. return this.meshes[index];
  7883. }
  7884. }
  7885. return null;
  7886. };
  7887. /**
  7888. * Get a the last added mesh found of a given ID
  7889. * @param {string} id - the id to search for
  7890. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  7891. */
  7892. Scene.prototype.getLastMeshByID = function (id) {
  7893. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7894. if (this.meshes[index].id === id) {
  7895. return this.meshes[index];
  7896. }
  7897. }
  7898. return null;
  7899. };
  7900. /**
  7901. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  7902. * @param {string} id - the id to search for
  7903. * @return {BABYLON.Node|null} the node found or null if not found at all.
  7904. */
  7905. Scene.prototype.getLastEntryByID = function (id) {
  7906. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7907. if (this.meshes[index].id === id) {
  7908. return this.meshes[index];
  7909. }
  7910. }
  7911. for (index = this.cameras.length - 1; index >= 0; index--) {
  7912. if (this.cameras[index].id === id) {
  7913. return this.cameras[index];
  7914. }
  7915. }
  7916. for (index = this.lights.length - 1; index >= 0; index--) {
  7917. if (this.lights[index].id === id) {
  7918. return this.lights[index];
  7919. }
  7920. }
  7921. return null;
  7922. };
  7923. Scene.prototype.getNodeByName = function (name) {
  7924. var mesh = this.getMeshByName(name);
  7925. if (mesh) {
  7926. return mesh;
  7927. }
  7928. var light = this.getLightByName(name);
  7929. if (light) {
  7930. return light;
  7931. }
  7932. return this.getCameraByName(name);
  7933. };
  7934. Scene.prototype.getMeshByName = function (name) {
  7935. for (var index = 0; index < this.meshes.length; index++) {
  7936. if (this.meshes[index].name === name) {
  7937. return this.meshes[index];
  7938. }
  7939. }
  7940. return null;
  7941. };
  7942. Scene.prototype.getLastSkeletonByID = function (id) {
  7943. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7944. if (this.skeletons[index].id === id) {
  7945. return this.skeletons[index];
  7946. }
  7947. }
  7948. return null;
  7949. };
  7950. Scene.prototype.getSkeletonById = function (id) {
  7951. for (var index = 0; index < this.skeletons.length; index++) {
  7952. if (this.skeletons[index].id === id) {
  7953. return this.skeletons[index];
  7954. }
  7955. }
  7956. return null;
  7957. };
  7958. Scene.prototype.getSkeletonByName = function (name) {
  7959. for (var index = 0; index < this.skeletons.length; index++) {
  7960. if (this.skeletons[index].name === name) {
  7961. return this.skeletons[index];
  7962. }
  7963. }
  7964. return null;
  7965. };
  7966. Scene.prototype.isActiveMesh = function (mesh) {
  7967. return (this._activeMeshes.indexOf(mesh) !== -1);
  7968. };
  7969. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7970. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7971. var material = subMesh.getMaterial();
  7972. if (mesh.showSubMeshesBoundingBox) {
  7973. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7974. }
  7975. if (material) {
  7976. // Render targets
  7977. if (material.getRenderTargetTextures) {
  7978. if (this._processedMaterials.indexOf(material) === -1) {
  7979. this._processedMaterials.push(material);
  7980. this._renderTargets.concat(material.getRenderTargetTextures());
  7981. }
  7982. }
  7983. // Dispatch
  7984. this._activeVertices += subMesh.indexCount;
  7985. this._renderingManager.dispatch(subMesh);
  7986. }
  7987. }
  7988. };
  7989. Scene.prototype._evaluateActiveMeshes = function () {
  7990. this._activeMeshes.reset();
  7991. this._renderingManager.reset();
  7992. this._processedMaterials.reset();
  7993. this._activeParticleSystems.reset();
  7994. this._activeSkeletons.reset();
  7995. this._boundingBoxRenderer.reset();
  7996. if (!this._frustumPlanes) {
  7997. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7998. } else {
  7999. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8000. }
  8001. // Meshes
  8002. var meshes;
  8003. var len;
  8004. if (this._selectionOctree) {
  8005. var selection = this._selectionOctree.select(this._frustumPlanes);
  8006. meshes = selection.data;
  8007. len = selection.length;
  8008. } else {
  8009. len = this.meshes.length;
  8010. meshes = this.meshes;
  8011. }
  8012. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8013. var mesh = meshes[meshIndex];
  8014. if (mesh.isBlocked) {
  8015. continue;
  8016. }
  8017. this._totalVertices += mesh.getTotalVertices();
  8018. if (!mesh.isReady()) {
  8019. continue;
  8020. }
  8021. mesh.computeWorldMatrix();
  8022. // Intersections
  8023. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8024. this._meshesForIntersections.pushNoDuplicate(mesh);
  8025. }
  8026. // Switch to current LOD
  8027. var meshLOD = mesh.getLOD(this.activeCamera);
  8028. if (!meshLOD) {
  8029. continue;
  8030. }
  8031. mesh._preActivate();
  8032. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8033. this._activeMeshes.push(mesh);
  8034. mesh._activate(this._renderId);
  8035. this._activeMesh(meshLOD);
  8036. }
  8037. }
  8038. // Particle systems
  8039. var beforeParticlesDate = BABYLON.Tools.Now;
  8040. if (this.particlesEnabled) {
  8041. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8042. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8043. var particleSystem = this.particleSystems[particleIndex];
  8044. if (!particleSystem.isStarted()) {
  8045. continue;
  8046. }
  8047. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8048. this._activeParticleSystems.push(particleSystem);
  8049. particleSystem.animate();
  8050. }
  8051. }
  8052. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8053. }
  8054. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8055. };
  8056. Scene.prototype._activeMesh = function (mesh) {
  8057. if (mesh.skeleton && this.skeletonsEnabled) {
  8058. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8059. }
  8060. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8061. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8062. }
  8063. if (mesh && mesh.subMeshes) {
  8064. // Submeshes Octrees
  8065. var len;
  8066. var subMeshes;
  8067. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8068. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8069. len = intersections.length;
  8070. subMeshes = intersections.data;
  8071. } else {
  8072. subMeshes = mesh.subMeshes;
  8073. len = subMeshes.length;
  8074. }
  8075. for (var subIndex = 0; subIndex < len; subIndex++) {
  8076. var subMesh = subMeshes[subIndex];
  8077. this._evaluateSubMesh(subMesh, mesh);
  8078. }
  8079. }
  8080. };
  8081. Scene.prototype.updateTransformMatrix = function (force) {
  8082. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8083. };
  8084. Scene.prototype._renderForCamera = function (camera) {
  8085. var engine = this._engine;
  8086. this.activeCamera = camera;
  8087. if (!this.activeCamera)
  8088. throw new Error("Active camera not set");
  8089. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8090. // Viewport
  8091. engine.setViewport(this.activeCamera.viewport);
  8092. // Camera
  8093. this._renderId++;
  8094. this.updateTransformMatrix();
  8095. if (this.beforeCameraRender) {
  8096. this.beforeCameraRender(this.activeCamera);
  8097. }
  8098. // Meshes
  8099. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8100. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8101. this._evaluateActiveMeshes();
  8102. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8103. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8104. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8105. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8106. skeleton.prepare();
  8107. this._activeBones += skeleton.bones.length;
  8108. }
  8109. // Render targets
  8110. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8111. if (this.renderTargetsEnabled) {
  8112. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8113. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8114. var renderTarget = this._renderTargets.data[renderIndex];
  8115. if (renderTarget._shouldRender()) {
  8116. this._renderId++;
  8117. renderTarget.render();
  8118. }
  8119. }
  8120. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8121. this._renderId++;
  8122. }
  8123. if (this._renderTargets.length > 0) {
  8124. engine.restoreDefaultFramebuffer();
  8125. }
  8126. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8127. // Prepare Frame
  8128. this.postProcessManager._prepareFrame();
  8129. var beforeRenderDate = BABYLON.Tools.Now;
  8130. // Backgrounds
  8131. if (this.layers.length) {
  8132. engine.setDepthBuffer(false);
  8133. var layerIndex;
  8134. var layer;
  8135. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8136. layer = this.layers[layerIndex];
  8137. if (layer.isBackground) {
  8138. layer.render();
  8139. }
  8140. }
  8141. engine.setDepthBuffer(true);
  8142. }
  8143. // Render
  8144. BABYLON.Tools.StartPerformanceCounter("Main render");
  8145. this._renderingManager.render(null, null, true, true);
  8146. BABYLON.Tools.EndPerformanceCounter("Main render");
  8147. // Bounding boxes
  8148. this._boundingBoxRenderer.render();
  8149. // Lens flares
  8150. if (this.lensFlaresEnabled) {
  8151. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8152. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8153. this.lensFlareSystems[lensFlareSystemIndex].render();
  8154. }
  8155. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8156. }
  8157. // Foregrounds
  8158. if (this.layers.length) {
  8159. engine.setDepthBuffer(false);
  8160. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8161. layer = this.layers[layerIndex];
  8162. if (!layer.isBackground) {
  8163. layer.render();
  8164. }
  8165. }
  8166. engine.setDepthBuffer(true);
  8167. }
  8168. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8169. // Finalize frame
  8170. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8171. // Update camera
  8172. this.activeCamera._updateFromScene();
  8173. // Reset some special arrays
  8174. this._renderTargets.reset();
  8175. if (this.afterCameraRender) {
  8176. this.afterCameraRender(this.activeCamera);
  8177. }
  8178. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8179. };
  8180. Scene.prototype._processSubCameras = function (camera) {
  8181. if (camera.subCameras.length === 0) {
  8182. this._renderForCamera(camera);
  8183. return;
  8184. }
  8185. for (var index = 0; index < camera.subCameras.length; index++) {
  8186. this._renderForCamera(camera.subCameras[index]);
  8187. }
  8188. this.activeCamera = camera;
  8189. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8190. // Update camera
  8191. this.activeCamera._updateFromScene();
  8192. };
  8193. Scene.prototype._checkIntersections = function () {
  8194. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8195. var sourceMesh = this._meshesForIntersections.data[index];
  8196. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8197. var action = sourceMesh.actionManager.actions[actionIndex];
  8198. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8199. var otherMesh = action.getTriggerParameter();
  8200. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  8201. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8202. if (areIntersecting && currentIntersectionInProgress === -1) {
  8203. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8204. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8205. sourceMesh._intersectionsInProgress.push(otherMesh);
  8206. } else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8207. sourceMesh._intersectionsInProgress.push(otherMesh);
  8208. }
  8209. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8210. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8211. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8212. if (indexOfOther > -1) {
  8213. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8214. }
  8215. }
  8216. }
  8217. }
  8218. }
  8219. };
  8220. Scene.prototype.render = function () {
  8221. var startDate = BABYLON.Tools.Now;
  8222. this._particlesDuration = 0;
  8223. this._spritesDuration = 0;
  8224. this._activeParticles = 0;
  8225. this._renderDuration = 0;
  8226. this._renderTargetsDuration = 0;
  8227. this._evaluateActiveMeshesDuration = 0;
  8228. this._totalVertices = 0;
  8229. this._activeVertices = 0;
  8230. this._activeBones = 0;
  8231. this.getEngine().resetDrawCalls();
  8232. this._meshesForIntersections.reset();
  8233. this.resetCachedMaterial();
  8234. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8235. // Actions
  8236. if (this.actionManager) {
  8237. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8238. }
  8239. // Before render
  8240. if (this.beforeRender) {
  8241. this.beforeRender();
  8242. }
  8243. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8244. this._onBeforeRenderCallbacks[callbackIndex]();
  8245. }
  8246. // Animations
  8247. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8248. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8249. this._animate();
  8250. // Physics
  8251. if (this._physicsEngine) {
  8252. BABYLON.Tools.StartPerformanceCounter("Physics");
  8253. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8254. BABYLON.Tools.EndPerformanceCounter("Physics");
  8255. }
  8256. // Customs render targets
  8257. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8258. var engine = this.getEngine();
  8259. if (this.renderTargetsEnabled) {
  8260. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8261. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8262. var renderTarget = this.customRenderTargets[customIndex];
  8263. if (renderTarget._shouldRender()) {
  8264. this._renderId++;
  8265. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8266. if (!this.activeCamera)
  8267. throw new Error("Active camera not set");
  8268. // Viewport
  8269. engine.setViewport(this.activeCamera.viewport);
  8270. // Camera
  8271. this.updateTransformMatrix();
  8272. renderTarget.render();
  8273. }
  8274. }
  8275. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8276. this._renderId++;
  8277. }
  8278. if (this.customRenderTargets.length > 0) {
  8279. engine.restoreDefaultFramebuffer();
  8280. }
  8281. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8282. // Procedural textures
  8283. if (this.proceduralTexturesEnabled) {
  8284. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8285. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8286. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8287. if (proceduralTexture._shouldRender()) {
  8288. proceduralTexture.render();
  8289. }
  8290. }
  8291. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8292. }
  8293. // Clear
  8294. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8295. // Shadows
  8296. if (this.shadowsEnabled) {
  8297. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8298. var light = this.lights[lightIndex];
  8299. var shadowGenerator = light.getShadowGenerator();
  8300. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8301. this._renderTargets.push(shadowGenerator.getShadowMap());
  8302. }
  8303. }
  8304. }
  8305. // RenderPipeline
  8306. this.postProcessRenderPipelineManager.update();
  8307. // Multi-cameras?
  8308. if (this.activeCameras.length > 0) {
  8309. var currentRenderId = this._renderId;
  8310. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8311. this._renderId = currentRenderId;
  8312. this._processSubCameras(this.activeCameras[cameraIndex]);
  8313. }
  8314. } else {
  8315. if (!this.activeCamera) {
  8316. throw new Error("No camera defined");
  8317. }
  8318. this._processSubCameras(this.activeCamera);
  8319. }
  8320. // Intersection checks
  8321. this._checkIntersections();
  8322. // Update the audio listener attached to the camera
  8323. this._updateAudioParameters();
  8324. // After render
  8325. if (this.afterRender) {
  8326. this.afterRender();
  8327. }
  8328. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8329. this._onAfterRenderCallbacks[callbackIndex]();
  8330. }
  8331. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8332. this._toBeDisposed.data[index].dispose();
  8333. this._toBeDisposed[index] = null;
  8334. }
  8335. this._toBeDisposed.reset();
  8336. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8337. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8338. };
  8339. Scene.prototype._updateAudioParameters = function () {
  8340. var listeningCamera;
  8341. var audioEngine = this._engine.getAudioEngine();
  8342. if (this.activeCameras.length > 0) {
  8343. listeningCamera = this.activeCameras[0];
  8344. } else {
  8345. listeningCamera = this.activeCamera;
  8346. }
  8347. if (listeningCamera && audioEngine.canUseWebAudio) {
  8348. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8349. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8350. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8351. cameraDirection.normalize();
  8352. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8353. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8354. var sound = this.mainSoundTrack.soundCollection[i];
  8355. if (sound.useCustomAttenuation) {
  8356. sound.updateDistanceFromListener();
  8357. }
  8358. }
  8359. for (var i = 0; i < this.soundTracks.length; i++) {
  8360. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8361. var sound = this.soundTracks[i].soundCollection[j];
  8362. if (sound.useCustomAttenuation) {
  8363. sound.updateDistanceFromListener();
  8364. }
  8365. }
  8366. }
  8367. }
  8368. };
  8369. Scene.prototype.dispose = function () {
  8370. this.beforeRender = null;
  8371. this.afterRender = null;
  8372. this.skeletons = [];
  8373. this._boundingBoxRenderer.dispose();
  8374. // Debug layer
  8375. this.debugLayer.hide();
  8376. // Events
  8377. if (this.onDispose) {
  8378. this.onDispose();
  8379. }
  8380. this._onBeforeRenderCallbacks = [];
  8381. this._onAfterRenderCallbacks = [];
  8382. this.detachControl();
  8383. // Detach cameras
  8384. var canvas = this._engine.getRenderingCanvas();
  8385. var index;
  8386. for (index = 0; index < this.cameras.length; index++) {
  8387. this.cameras[index].detachControl(canvas);
  8388. }
  8389. while (this.lights.length) {
  8390. this.lights[0].dispose();
  8391. }
  8392. while (this.meshes.length) {
  8393. this.meshes[0].dispose(true);
  8394. }
  8395. while (this.cameras.length) {
  8396. this.cameras[0].dispose();
  8397. }
  8398. while (this.materials.length) {
  8399. this.materials[0].dispose();
  8400. }
  8401. while (this.particleSystems.length) {
  8402. this.particleSystems[0].dispose();
  8403. }
  8404. while (this.spriteManagers.length) {
  8405. this.spriteManagers[0].dispose();
  8406. }
  8407. while (this.layers.length) {
  8408. this.layers[0].dispose();
  8409. }
  8410. while (this.textures.length) {
  8411. this.textures[0].dispose();
  8412. }
  8413. // Post-processes
  8414. this.postProcessManager.dispose();
  8415. // Physics
  8416. if (this._physicsEngine) {
  8417. this.disablePhysicsEngine();
  8418. }
  8419. // Remove from engine
  8420. index = this._engine.scenes.indexOf(this);
  8421. if (index > -1) {
  8422. this._engine.scenes.splice(index, 1);
  8423. }
  8424. this._engine.wipeCaches();
  8425. };
  8426. // Collisions
  8427. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8428. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8429. position.divideToRef(collider.radius, this._scaledPosition);
  8430. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8431. collider.retry = 0;
  8432. collider.initialVelocity = this._scaledVelocity;
  8433. collider.initialPosition = this._scaledPosition;
  8434. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8435. finalPosition.multiplyInPlace(collider.radius);
  8436. };
  8437. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8438. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8439. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8440. if (collider.retry >= maximumRetry) {
  8441. finalPosition.copyFrom(position);
  8442. return;
  8443. }
  8444. collider._initialize(position, velocity, closeDistance);
  8445. for (var index = 0; index < this.meshes.length; index++) {
  8446. var mesh = this.meshes[index];
  8447. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8448. mesh._checkCollision(collider);
  8449. }
  8450. }
  8451. if (!collider.collisionFound) {
  8452. position.addToRef(velocity, finalPosition);
  8453. return;
  8454. }
  8455. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8456. collider._getResponse(position, velocity);
  8457. }
  8458. if (velocity.length() <= closeDistance) {
  8459. finalPosition.copyFrom(position);
  8460. return;
  8461. }
  8462. collider.retry++;
  8463. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8464. };
  8465. // Octrees
  8466. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8467. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8468. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8469. if (!this._selectionOctree) {
  8470. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8471. }
  8472. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8473. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8474. for (var index = 0; index < this.meshes.length; index++) {
  8475. var mesh = this.meshes[index];
  8476. mesh.computeWorldMatrix(true);
  8477. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8478. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8479. BABYLON.Tools.CheckExtends(minBox, min, max);
  8480. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8481. }
  8482. // Update octree
  8483. this._selectionOctree.update(min, max, this.meshes);
  8484. return this._selectionOctree;
  8485. };
  8486. // Picking
  8487. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8488. var engine = this._engine;
  8489. if (!camera) {
  8490. if (!this.activeCamera)
  8491. throw new Error("Active camera not set");
  8492. camera = this.activeCamera;
  8493. }
  8494. var cameraViewport = camera.viewport;
  8495. var viewport = cameraViewport.toGlobal(engine);
  8496. // Moving coordinates to local viewport world
  8497. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8498. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8499. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8500. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8501. };
  8502. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8503. var pickingInfo = null;
  8504. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8505. var mesh = this.meshes[meshIndex];
  8506. if (predicate) {
  8507. if (!predicate(mesh)) {
  8508. continue;
  8509. }
  8510. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8511. continue;
  8512. }
  8513. var world = mesh.getWorldMatrix();
  8514. var ray = rayFunction(world);
  8515. var result = mesh.intersects(ray, fastCheck);
  8516. if (!result || !result.hit)
  8517. continue;
  8518. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8519. continue;
  8520. pickingInfo = result;
  8521. if (fastCheck) {
  8522. break;
  8523. }
  8524. }
  8525. return pickingInfo || new BABYLON.PickingInfo();
  8526. };
  8527. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8528. var _this = this;
  8529. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8530. /// <param name="x">X position on screen</param>
  8531. /// <param name="y">Y position on screen</param>
  8532. /// <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>
  8533. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8534. /// <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>
  8535. return this._internalPick(function (world) {
  8536. return _this.createPickingRay(x, y, world, camera);
  8537. }, predicate, fastCheck);
  8538. };
  8539. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8540. var _this = this;
  8541. return this._internalPick(function (world) {
  8542. if (!_this._pickWithRayInverseMatrix) {
  8543. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8544. }
  8545. world.invertToRef(_this._pickWithRayInverseMatrix);
  8546. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8547. }, predicate, fastCheck);
  8548. };
  8549. Scene.prototype.setPointerOverMesh = function (mesh) {
  8550. if (this._pointerOverMesh === mesh) {
  8551. return;
  8552. }
  8553. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8554. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8555. }
  8556. this._pointerOverMesh = mesh;
  8557. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8558. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8559. }
  8560. };
  8561. Scene.prototype.getPointerOverMesh = function () {
  8562. return this._pointerOverMesh;
  8563. };
  8564. // Physics
  8565. Scene.prototype.getPhysicsEngine = function () {
  8566. return this._physicsEngine;
  8567. };
  8568. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8569. if (this._physicsEngine) {
  8570. return true;
  8571. }
  8572. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8573. if (!this._physicsEngine.isSupported()) {
  8574. this._physicsEngine = null;
  8575. return false;
  8576. }
  8577. this._physicsEngine._initialize(gravity);
  8578. return true;
  8579. };
  8580. Scene.prototype.disablePhysicsEngine = function () {
  8581. if (!this._physicsEngine) {
  8582. return;
  8583. }
  8584. this._physicsEngine.dispose();
  8585. this._physicsEngine = undefined;
  8586. };
  8587. Scene.prototype.isPhysicsEnabled = function () {
  8588. return this._physicsEngine !== undefined;
  8589. };
  8590. Scene.prototype.setGravity = function (gravity) {
  8591. if (!this._physicsEngine) {
  8592. return;
  8593. }
  8594. this._physicsEngine._setGravity(gravity);
  8595. };
  8596. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8597. if (parts.parts) {
  8598. options = parts;
  8599. parts = parts.parts;
  8600. }
  8601. if (!this._physicsEngine) {
  8602. return null;
  8603. }
  8604. for (var index = 0; index < parts.length; index++) {
  8605. var mesh = parts[index].mesh;
  8606. mesh._physicImpostor = parts[index].impostor;
  8607. mesh._physicsMass = options.mass / parts.length;
  8608. mesh._physicsFriction = options.friction;
  8609. mesh._physicRestitution = options.restitution;
  8610. }
  8611. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8612. };
  8613. //ANY
  8614. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8615. for (var index = 0; index < compound.parts.length; index++) {
  8616. var mesh = compound.parts[index].mesh;
  8617. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8618. this._physicsEngine._unregisterMesh(mesh);
  8619. }
  8620. };
  8621. // Tags
  8622. Scene.prototype._getByTags = function (list, tagsQuery) {
  8623. if (tagsQuery === undefined) {
  8624. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8625. return list;
  8626. }
  8627. var listByTags = [];
  8628. for (var i in list) {
  8629. var item = list[i];
  8630. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8631. listByTags.push(item);
  8632. }
  8633. }
  8634. return listByTags;
  8635. };
  8636. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8637. return this._getByTags(this.meshes, tagsQuery);
  8638. };
  8639. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8640. return this._getByTags(this.cameras, tagsQuery);
  8641. };
  8642. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8643. return this._getByTags(this.lights, tagsQuery);
  8644. };
  8645. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8646. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8647. };
  8648. Scene.FOGMODE_NONE = 0;
  8649. Scene.FOGMODE_EXP = 1;
  8650. Scene.FOGMODE_EXP2 = 2;
  8651. Scene.FOGMODE_LINEAR = 3;
  8652. Scene.MinDeltaTime = 1.0;
  8653. Scene.MaxDeltaTime = 1000.0;
  8654. return Scene;
  8655. })();
  8656. BABYLON.Scene = Scene;
  8657. })(BABYLON || (BABYLON = {}));
  8658. //# sourceMappingURL=babylon.scene.js.map
  8659. var BABYLON;
  8660. (function (BABYLON) {
  8661. var VertexBuffer = (function () {
  8662. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8663. if (engine instanceof BABYLON.Mesh) {
  8664. this._engine = engine.getScene().getEngine();
  8665. } else {
  8666. this._engine = engine;
  8667. }
  8668. this._updatable = updatable;
  8669. this._data = data;
  8670. if (!postponeInternalCreation) {
  8671. this.create();
  8672. }
  8673. this._kind = kind;
  8674. if (stride) {
  8675. this._strideSize = stride;
  8676. return;
  8677. }
  8678. switch (kind) {
  8679. case VertexBuffer.PositionKind:
  8680. this._strideSize = 3;
  8681. break;
  8682. case VertexBuffer.NormalKind:
  8683. this._strideSize = 3;
  8684. break;
  8685. case VertexBuffer.UVKind:
  8686. this._strideSize = 2;
  8687. break;
  8688. case VertexBuffer.UV2Kind:
  8689. this._strideSize = 2;
  8690. break;
  8691. case VertexBuffer.ColorKind:
  8692. this._strideSize = 4;
  8693. break;
  8694. case VertexBuffer.MatricesIndicesKind:
  8695. this._strideSize = 4;
  8696. break;
  8697. case VertexBuffer.MatricesWeightsKind:
  8698. this._strideSize = 4;
  8699. break;
  8700. }
  8701. }
  8702. // Properties
  8703. VertexBuffer.prototype.isUpdatable = function () {
  8704. return this._updatable;
  8705. };
  8706. VertexBuffer.prototype.getData = function () {
  8707. return this._data;
  8708. };
  8709. VertexBuffer.prototype.getBuffer = function () {
  8710. return this._buffer;
  8711. };
  8712. VertexBuffer.prototype.getStrideSize = function () {
  8713. return this._strideSize;
  8714. };
  8715. // Methods
  8716. VertexBuffer.prototype.create = function (data) {
  8717. if (!data && this._buffer) {
  8718. return;
  8719. }
  8720. data = data || this._data;
  8721. if (!this._buffer) {
  8722. if (this._updatable) {
  8723. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8724. } else {
  8725. this._buffer = this._engine.createVertexBuffer(data);
  8726. }
  8727. }
  8728. if (this._updatable) {
  8729. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8730. this._data = data;
  8731. }
  8732. };
  8733. VertexBuffer.prototype.update = function (data) {
  8734. this.create(data);
  8735. };
  8736. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8737. if (!this._buffer) {
  8738. return;
  8739. }
  8740. if (this._updatable) {
  8741. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8742. this._data = null;
  8743. }
  8744. };
  8745. VertexBuffer.prototype.dispose = function () {
  8746. if (!this._buffer) {
  8747. return;
  8748. }
  8749. if (this._engine._releaseBuffer(this._buffer)) {
  8750. this._buffer = null;
  8751. }
  8752. };
  8753. Object.defineProperty(VertexBuffer, "PositionKind", {
  8754. get: function () {
  8755. return VertexBuffer._PositionKind;
  8756. },
  8757. enumerable: true,
  8758. configurable: true
  8759. });
  8760. Object.defineProperty(VertexBuffer, "NormalKind", {
  8761. get: function () {
  8762. return VertexBuffer._NormalKind;
  8763. },
  8764. enumerable: true,
  8765. configurable: true
  8766. });
  8767. Object.defineProperty(VertexBuffer, "UVKind", {
  8768. get: function () {
  8769. return VertexBuffer._UVKind;
  8770. },
  8771. enumerable: true,
  8772. configurable: true
  8773. });
  8774. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8775. get: function () {
  8776. return VertexBuffer._UV2Kind;
  8777. },
  8778. enumerable: true,
  8779. configurable: true
  8780. });
  8781. Object.defineProperty(VertexBuffer, "ColorKind", {
  8782. get: function () {
  8783. return VertexBuffer._ColorKind;
  8784. },
  8785. enumerable: true,
  8786. configurable: true
  8787. });
  8788. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8789. get: function () {
  8790. return VertexBuffer._MatricesIndicesKind;
  8791. },
  8792. enumerable: true,
  8793. configurable: true
  8794. });
  8795. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8796. get: function () {
  8797. return VertexBuffer._MatricesWeightsKind;
  8798. },
  8799. enumerable: true,
  8800. configurable: true
  8801. });
  8802. VertexBuffer._PositionKind = "position";
  8803. VertexBuffer._NormalKind = "normal";
  8804. VertexBuffer._UVKind = "uv";
  8805. VertexBuffer._UV2Kind = "uv2";
  8806. VertexBuffer._ColorKind = "color";
  8807. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8808. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8809. return VertexBuffer;
  8810. })();
  8811. BABYLON.VertexBuffer = VertexBuffer;
  8812. })(BABYLON || (BABYLON = {}));
  8813. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8814. var BABYLON;
  8815. (function (BABYLON) {
  8816. var AbstractMesh = (function (_super) {
  8817. __extends(AbstractMesh, _super);
  8818. function AbstractMesh(name, scene) {
  8819. _super.call(this, name, scene);
  8820. // Properties
  8821. this.position = new BABYLON.Vector3(0, 0, 0);
  8822. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8823. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8824. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8825. this.visibility = 1.0;
  8826. this.alphaIndex = Number.MAX_VALUE;
  8827. this.infiniteDistance = false;
  8828. this.isVisible = true;
  8829. this.isPickable = true;
  8830. this.showBoundingBox = false;
  8831. this.showSubMeshesBoundingBox = false;
  8832. this.onDispose = null;
  8833. this.checkCollisions = false;
  8834. this.isBlocker = false;
  8835. this.renderingGroupId = 0;
  8836. this.receiveShadows = false;
  8837. this.renderOutline = false;
  8838. this.outlineColor = BABYLON.Color3.Red();
  8839. this.outlineWidth = 0.02;
  8840. this.renderOverlay = false;
  8841. this.overlayColor = BABYLON.Color3.Red();
  8842. this.overlayAlpha = 0.5;
  8843. this.hasVertexAlpha = false;
  8844. this.useVertexColors = true;
  8845. this.applyFog = true;
  8846. this.useOctreeForRenderingSelection = true;
  8847. this.useOctreeForPicking = true;
  8848. this.useOctreeForCollisions = true;
  8849. this.layerMask = 0xFFFFFFFF;
  8850. // Physics
  8851. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8852. // Collisions
  8853. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8854. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8855. this._collider = new BABYLON.Collider();
  8856. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8857. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8858. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8859. // Cache
  8860. this._localScaling = BABYLON.Matrix.Zero();
  8861. this._localRotation = BABYLON.Matrix.Zero();
  8862. this._localTranslation = BABYLON.Matrix.Zero();
  8863. this._localBillboard = BABYLON.Matrix.Zero();
  8864. this._localPivotScaling = BABYLON.Matrix.Zero();
  8865. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8866. this._localWorld = BABYLON.Matrix.Zero();
  8867. this._worldMatrix = BABYLON.Matrix.Zero();
  8868. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8869. this._absolutePosition = BABYLON.Vector3.Zero();
  8870. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8871. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8872. this._isDirty = false;
  8873. this._pivotMatrix = BABYLON.Matrix.Identity();
  8874. this._isDisposed = false;
  8875. this._renderId = 0;
  8876. this._intersectionsInProgress = new Array();
  8877. this._onAfterWorldMatrixUpdate = new Array();
  8878. scene.meshes.push(this);
  8879. }
  8880. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8881. get: function () {
  8882. return AbstractMesh._BILLBOARDMODE_NONE;
  8883. },
  8884. enumerable: true,
  8885. configurable: true
  8886. });
  8887. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8888. get: function () {
  8889. return AbstractMesh._BILLBOARDMODE_X;
  8890. },
  8891. enumerable: true,
  8892. configurable: true
  8893. });
  8894. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8895. get: function () {
  8896. return AbstractMesh._BILLBOARDMODE_Y;
  8897. },
  8898. enumerable: true,
  8899. configurable: true
  8900. });
  8901. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8902. get: function () {
  8903. return AbstractMesh._BILLBOARDMODE_Z;
  8904. },
  8905. enumerable: true,
  8906. configurable: true
  8907. });
  8908. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8909. get: function () {
  8910. return AbstractMesh._BILLBOARDMODE_ALL;
  8911. },
  8912. enumerable: true,
  8913. configurable: true
  8914. });
  8915. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8916. // Methods
  8917. get: function () {
  8918. return false;
  8919. },
  8920. enumerable: true,
  8921. configurable: true
  8922. });
  8923. AbstractMesh.prototype.getLOD = function (camera) {
  8924. return this;
  8925. };
  8926. AbstractMesh.prototype.getTotalVertices = function () {
  8927. return 0;
  8928. };
  8929. AbstractMesh.prototype.getIndices = function () {
  8930. return null;
  8931. };
  8932. AbstractMesh.prototype.getVerticesData = function (kind) {
  8933. return null;
  8934. };
  8935. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8936. return false;
  8937. };
  8938. AbstractMesh.prototype.getBoundingInfo = function () {
  8939. if (this._masterMesh) {
  8940. return this._masterMesh.getBoundingInfo();
  8941. }
  8942. if (!this._boundingInfo) {
  8943. this._updateBoundingInfo();
  8944. }
  8945. return this._boundingInfo;
  8946. };
  8947. AbstractMesh.prototype._preActivate = function () {
  8948. };
  8949. AbstractMesh.prototype._activate = function (renderId) {
  8950. this._renderId = renderId;
  8951. };
  8952. AbstractMesh.prototype.getWorldMatrix = function () {
  8953. if (this._masterMesh) {
  8954. return this._masterMesh.getWorldMatrix();
  8955. }
  8956. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8957. this.computeWorldMatrix();
  8958. }
  8959. return this._worldMatrix;
  8960. };
  8961. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8962. get: function () {
  8963. return this._worldMatrix;
  8964. },
  8965. enumerable: true,
  8966. configurable: true
  8967. });
  8968. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8969. get: function () {
  8970. return this._absolutePosition;
  8971. },
  8972. enumerable: true,
  8973. configurable: true
  8974. });
  8975. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8976. if (!this.rotationQuaternion) {
  8977. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8978. this.rotation = BABYLON.Vector3.Zero();
  8979. }
  8980. if (!space || space == 0 /* LOCAL */) {
  8981. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8982. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8983. } else {
  8984. if (this.parent) {
  8985. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8986. invertParentWorldMatrix.invert();
  8987. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8988. }
  8989. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8990. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8991. }
  8992. };
  8993. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8994. var displacementVector = axis.scale(distance);
  8995. if (!space || space == 0 /* LOCAL */) {
  8996. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8997. this.setPositionWithLocalVector(tempV3);
  8998. } else {
  8999. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9000. }
  9001. };
  9002. AbstractMesh.prototype.getAbsolutePosition = function () {
  9003. this.computeWorldMatrix();
  9004. return this._absolutePosition;
  9005. };
  9006. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9007. if (!absolutePosition) {
  9008. return;
  9009. }
  9010. var absolutePositionX;
  9011. var absolutePositionY;
  9012. var absolutePositionZ;
  9013. if (absolutePosition.x === undefined) {
  9014. if (arguments.length < 3) {
  9015. return;
  9016. }
  9017. absolutePositionX = arguments[0];
  9018. absolutePositionY = arguments[1];
  9019. absolutePositionZ = arguments[2];
  9020. } else {
  9021. absolutePositionX = absolutePosition.x;
  9022. absolutePositionY = absolutePosition.y;
  9023. absolutePositionZ = absolutePosition.z;
  9024. }
  9025. if (this.parent) {
  9026. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9027. invertParentWorldMatrix.invert();
  9028. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9029. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9030. } else {
  9031. this.position.x = absolutePositionX;
  9032. this.position.y = absolutePositionY;
  9033. this.position.z = absolutePositionZ;
  9034. }
  9035. };
  9036. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9037. this._pivotMatrix = matrix;
  9038. this._cache.pivotMatrixUpdated = true;
  9039. };
  9040. AbstractMesh.prototype.getPivotMatrix = function () {
  9041. return this._pivotMatrix;
  9042. };
  9043. AbstractMesh.prototype._isSynchronized = function () {
  9044. if (this._isDirty) {
  9045. return false;
  9046. }
  9047. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9048. return false;
  9049. if (this._cache.pivotMatrixUpdated) {
  9050. return false;
  9051. }
  9052. if (this.infiniteDistance) {
  9053. return false;
  9054. }
  9055. if (!this._cache.position.equals(this.position))
  9056. return false;
  9057. if (this.rotationQuaternion) {
  9058. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9059. return false;
  9060. } else {
  9061. if (!this._cache.rotation.equals(this.rotation))
  9062. return false;
  9063. }
  9064. if (!this._cache.scaling.equals(this.scaling))
  9065. return false;
  9066. return true;
  9067. };
  9068. AbstractMesh.prototype._initCache = function () {
  9069. _super.prototype._initCache.call(this);
  9070. this._cache.localMatrixUpdated = false;
  9071. this._cache.position = BABYLON.Vector3.Zero();
  9072. this._cache.scaling = BABYLON.Vector3.Zero();
  9073. this._cache.rotation = BABYLON.Vector3.Zero();
  9074. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9075. };
  9076. AbstractMesh.prototype.markAsDirty = function (property) {
  9077. if (property === "rotation") {
  9078. this.rotationQuaternion = null;
  9079. }
  9080. this._currentRenderId = Number.MAX_VALUE;
  9081. this._isDirty = true;
  9082. };
  9083. AbstractMesh.prototype._updateBoundingInfo = function () {
  9084. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9085. this._boundingInfo._update(this.worldMatrixFromCache);
  9086. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9087. };
  9088. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9089. if (!this.subMeshes) {
  9090. return;
  9091. }
  9092. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9093. var subMesh = this.subMeshes[subIndex];
  9094. subMesh.updateBoundingInfo(matrix);
  9095. }
  9096. };
  9097. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9098. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9099. return this._worldMatrix;
  9100. }
  9101. this._cache.position.copyFrom(this.position);
  9102. this._cache.scaling.copyFrom(this.scaling);
  9103. this._cache.pivotMatrixUpdated = false;
  9104. this._currentRenderId = this.getScene().getRenderId();
  9105. this._isDirty = false;
  9106. // Scaling
  9107. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9108. // Rotation
  9109. if (this.rotationQuaternion) {
  9110. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9111. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9112. } else {
  9113. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9114. this._cache.rotation.copyFrom(this.rotation);
  9115. }
  9116. // Translation
  9117. if (this.infiniteDistance && !this.parent) {
  9118. var camera = this.getScene().activeCamera;
  9119. var cameraWorldMatrix = camera.getWorldMatrix();
  9120. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9121. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9122. } else {
  9123. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9124. }
  9125. // Composing transformations
  9126. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9127. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9128. // Billboarding
  9129. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9130. var localPosition = this.position.clone();
  9131. var zero = this.getScene().activeCamera.position.clone();
  9132. if (this.parent && this.parent.position) {
  9133. localPosition.addInPlace(this.parent.position);
  9134. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9135. }
  9136. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9137. zero = this.getScene().activeCamera.position;
  9138. } else {
  9139. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9140. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9141. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9142. zero.y = localPosition.y + 0.001;
  9143. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9144. zero.z = localPosition.z + 0.001;
  9145. }
  9146. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9147. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9148. this._localBillboard.invert();
  9149. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9150. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9151. }
  9152. // Local world
  9153. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9154. // Parent
  9155. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9156. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9157. } else {
  9158. this._worldMatrix.copyFrom(this._localWorld);
  9159. }
  9160. // Bounding info
  9161. this._updateBoundingInfo();
  9162. // Absolute position
  9163. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9164. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9165. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9166. }
  9167. return this._worldMatrix;
  9168. };
  9169. /**
  9170. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9171. * @param func: callback function to add
  9172. */
  9173. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9174. this._onAfterWorldMatrixUpdate.push(func);
  9175. };
  9176. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9177. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9178. if (index > -1) {
  9179. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9180. }
  9181. };
  9182. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9183. this.computeWorldMatrix();
  9184. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9185. };
  9186. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9187. this.computeWorldMatrix();
  9188. var invLocalWorldMatrix = this._localWorld.clone();
  9189. invLocalWorldMatrix.invert();
  9190. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9191. };
  9192. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9193. this.computeWorldMatrix();
  9194. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9195. };
  9196. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9197. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9198. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9199. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9200. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9201. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9202. /// <returns>Mesh oriented towards targetMesh</returns>
  9203. yawCor = yawCor || 0; // default to zero if undefined
  9204. pitchCor = pitchCor || 0;
  9205. rollCor = rollCor || 0;
  9206. var dv = targetPoint.subtract(this.position);
  9207. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9208. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9209. var pitch = Math.atan2(dv.y, len);
  9210. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9211. };
  9212. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9213. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9214. return false;
  9215. }
  9216. return true;
  9217. };
  9218. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9219. if (!camera) {
  9220. camera = this.getScene().activeCamera;
  9221. }
  9222. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9223. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9224. return false;
  9225. }
  9226. return true;
  9227. };
  9228. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9229. if (!this._boundingInfo || !mesh._boundingInfo) {
  9230. return false;
  9231. }
  9232. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9233. };
  9234. AbstractMesh.prototype.intersectsPoint = function (point) {
  9235. if (!this._boundingInfo) {
  9236. return false;
  9237. }
  9238. return this._boundingInfo.intersectsPoint(point);
  9239. };
  9240. // Physics
  9241. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9242. var physicsEngine = this.getScene().getPhysicsEngine();
  9243. if (!physicsEngine) {
  9244. return;
  9245. }
  9246. if (impostor.impostor) {
  9247. // Old API
  9248. options = impostor;
  9249. impostor = impostor.impostor;
  9250. }
  9251. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9252. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9253. physicsEngine._unregisterMesh(this);
  9254. return;
  9255. }
  9256. options.mass = options.mass || 0;
  9257. options.friction = options.friction || 0.2;
  9258. options.restitution = options.restitution || 0.2;
  9259. this._physicImpostor = impostor;
  9260. this._physicsMass = options.mass;
  9261. this._physicsFriction = options.friction;
  9262. this._physicRestitution = options.restitution;
  9263. return physicsEngine._registerMesh(this, impostor, options);
  9264. };
  9265. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9266. if (!this._physicImpostor) {
  9267. return BABYLON.PhysicsEngine.NoImpostor;
  9268. }
  9269. return this._physicImpostor;
  9270. };
  9271. AbstractMesh.prototype.getPhysicsMass = function () {
  9272. if (!this._physicsMass) {
  9273. return 0;
  9274. }
  9275. return this._physicsMass;
  9276. };
  9277. AbstractMesh.prototype.getPhysicsFriction = function () {
  9278. if (!this._physicsFriction) {
  9279. return 0;
  9280. }
  9281. return this._physicsFriction;
  9282. };
  9283. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9284. if (!this._physicRestitution) {
  9285. return 0;
  9286. }
  9287. return this._physicRestitution;
  9288. };
  9289. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9290. if (!camera) {
  9291. camera = this.getScene().activeCamera;
  9292. }
  9293. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9294. };
  9295. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9296. if (!camera) {
  9297. camera = this.getScene().activeCamera;
  9298. }
  9299. return this.absolutePosition.subtract(camera.position).length();
  9300. };
  9301. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9302. if (!this._physicImpostor) {
  9303. return;
  9304. }
  9305. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9306. };
  9307. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9308. if (!this._physicImpostor) {
  9309. return;
  9310. }
  9311. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9312. };
  9313. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9314. if (!this._physicImpostor) {
  9315. return;
  9316. }
  9317. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9318. };
  9319. // Collisions
  9320. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9321. var globalPosition = this.getAbsolutePosition();
  9322. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9323. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9324. this._collider.radius = this.ellipsoid;
  9325. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9326. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9327. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9328. this.position.addInPlace(this._diffPositionForCollisions);
  9329. }
  9330. };
  9331. // Submeshes octree
  9332. /**
  9333. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9334. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9335. */
  9336. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9337. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  9338. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  9339. if (!this._submeshesOctree) {
  9340. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9341. }
  9342. this.computeWorldMatrix(true);
  9343. // Update octree
  9344. var bbox = this.getBoundingInfo().boundingBox;
  9345. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9346. return this._submeshesOctree;
  9347. };
  9348. // Collisions
  9349. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9350. this._generatePointsArray();
  9351. // Transformation
  9352. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9353. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9354. subMesh._lastColliderWorldVertices = [];
  9355. subMesh._trianglePlanes = [];
  9356. var start = subMesh.verticesStart;
  9357. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9358. for (var i = start; i < end; i++) {
  9359. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9360. }
  9361. }
  9362. // Collide
  9363. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9364. };
  9365. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9366. var subMeshes;
  9367. var len;
  9368. // Octrees
  9369. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9370. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9371. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9372. len = intersections.length;
  9373. subMeshes = intersections.data;
  9374. } else {
  9375. subMeshes = this.subMeshes;
  9376. len = subMeshes.length;
  9377. }
  9378. for (var index = 0; index < len; index++) {
  9379. var subMesh = subMeshes[index];
  9380. // Bounding test
  9381. if (len > 1 && !subMesh._checkCollision(collider))
  9382. continue;
  9383. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9384. }
  9385. };
  9386. AbstractMesh.prototype._checkCollision = function (collider) {
  9387. // Bounding box test
  9388. if (!this._boundingInfo._checkCollision(collider))
  9389. return;
  9390. // Transformation matrix
  9391. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9392. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9393. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9394. };
  9395. // Picking
  9396. AbstractMesh.prototype._generatePointsArray = function () {
  9397. return false;
  9398. };
  9399. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9400. var pickingInfo = new BABYLON.PickingInfo();
  9401. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9402. return pickingInfo;
  9403. }
  9404. if (!this._generatePointsArray()) {
  9405. return pickingInfo;
  9406. }
  9407. var intersectInfo = null;
  9408. // Octrees
  9409. var subMeshes;
  9410. var len;
  9411. if (this._submeshesOctree && this.useOctreeForPicking) {
  9412. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9413. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9414. len = intersections.length;
  9415. subMeshes = intersections.data;
  9416. } else {
  9417. subMeshes = this.subMeshes;
  9418. len = subMeshes.length;
  9419. }
  9420. for (var index = 0; index < len; index++) {
  9421. var subMesh = subMeshes[index];
  9422. // Bounding test
  9423. if (len > 1 && !subMesh.canIntersects(ray))
  9424. continue;
  9425. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9426. if (currentIntersectInfo) {
  9427. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9428. intersectInfo = currentIntersectInfo;
  9429. if (fastCheck) {
  9430. break;
  9431. }
  9432. }
  9433. }
  9434. }
  9435. if (intersectInfo) {
  9436. // Get picked point
  9437. var world = this.getWorldMatrix();
  9438. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9439. var direction = ray.direction.clone();
  9440. direction.normalize();
  9441. direction = direction.scale(intersectInfo.distance);
  9442. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9443. var pickedPoint = worldOrigin.add(worldDirection);
  9444. // Return result
  9445. pickingInfo.hit = true;
  9446. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9447. pickingInfo.pickedPoint = pickedPoint;
  9448. pickingInfo.pickedMesh = this;
  9449. pickingInfo.bu = intersectInfo.bu;
  9450. pickingInfo.bv = intersectInfo.bv;
  9451. pickingInfo.faceId = intersectInfo.faceId;
  9452. return pickingInfo;
  9453. }
  9454. return pickingInfo;
  9455. };
  9456. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9457. return null;
  9458. };
  9459. AbstractMesh.prototype.releaseSubMeshes = function () {
  9460. if (this.subMeshes) {
  9461. while (this.subMeshes.length) {
  9462. this.subMeshes[0].dispose();
  9463. }
  9464. } else {
  9465. this.subMeshes = new Array();
  9466. }
  9467. };
  9468. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9469. // Physics
  9470. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9471. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9472. }
  9473. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9474. var other = this._intersectionsInProgress[index];
  9475. var pos = other._intersectionsInProgress.indexOf(this);
  9476. other._intersectionsInProgress.splice(pos, 1);
  9477. }
  9478. this._intersectionsInProgress = [];
  9479. // SubMeshes
  9480. this.releaseSubMeshes();
  9481. // Remove from scene
  9482. var index = this.getScene().meshes.indexOf(this);
  9483. if (index != -1) {
  9484. // Remove from the scene if mesh found
  9485. this.getScene().meshes.splice(index, 1);
  9486. }
  9487. if (!doNotRecurse) {
  9488. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9489. if (this.getScene().particleSystems[index].emitter == this) {
  9490. this.getScene().particleSystems[index].dispose();
  9491. index--;
  9492. }
  9493. }
  9494. // Children
  9495. var objects = this.getScene().meshes.slice(0);
  9496. for (index = 0; index < objects.length; index++) {
  9497. if (objects[index].parent == this) {
  9498. objects[index].dispose();
  9499. }
  9500. }
  9501. } else {
  9502. for (index = 0; index < this.getScene().meshes.length; index++) {
  9503. var obj = this.getScene().meshes[index];
  9504. if (obj.parent === this) {
  9505. obj.parent = null;
  9506. obj.computeWorldMatrix(true);
  9507. }
  9508. }
  9509. }
  9510. this._onAfterWorldMatrixUpdate = [];
  9511. this._isDisposed = true;
  9512. // Callback
  9513. if (this.onDispose) {
  9514. this.onDispose();
  9515. }
  9516. };
  9517. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9518. AbstractMesh._BILLBOARDMODE_X = 1;
  9519. AbstractMesh._BILLBOARDMODE_Y = 2;
  9520. AbstractMesh._BILLBOARDMODE_Z = 4;
  9521. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9522. return AbstractMesh;
  9523. })(BABYLON.Node);
  9524. BABYLON.AbstractMesh = AbstractMesh;
  9525. })(BABYLON || (BABYLON = {}));
  9526. //# sourceMappingURL=babylon.abstractMesh.js.map
  9527. var BABYLON;
  9528. (function (BABYLON) {
  9529. var _InstancesBatch = (function () {
  9530. function _InstancesBatch() {
  9531. this.mustReturn = false;
  9532. this.visibleInstances = new Array();
  9533. this.renderSelf = new Array();
  9534. }
  9535. return _InstancesBatch;
  9536. })();
  9537. BABYLON._InstancesBatch = _InstancesBatch;
  9538. var Mesh = (function (_super) {
  9539. __extends(Mesh, _super);
  9540. /**
  9541. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9542. * @param {Scene} scene - The scene to add this mesh to.
  9543. * @param {Node} parent - The parent of this mesh, if it has one
  9544. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9545. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9546. * When false, achieved by calling a clone(), also passing False.
  9547. * This will make creation of children, recursive.
  9548. */
  9549. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9550. if (typeof parent === "undefined") { parent = null; }
  9551. _super.call(this, name, scene);
  9552. // Members
  9553. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9554. this.instances = new Array();
  9555. this._LODLevels = new Array();
  9556. this._onBeforeRenderCallbacks = new Array();
  9557. this._onAfterRenderCallbacks = new Array();
  9558. this._visibleInstances = {};
  9559. this._renderIdForInstances = new Array();
  9560. this._batchCache = new _InstancesBatch();
  9561. this._instancesBufferSize = 32 * 16 * 4;
  9562. if (source) {
  9563. // Geometry
  9564. if (source._geometry) {
  9565. source._geometry.applyToMesh(this);
  9566. }
  9567. // Deep copy
  9568. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9569. // Material
  9570. this.material = source.material;
  9571. if (!doNotCloneChildren) {
  9572. for (var index = 0; index < scene.meshes.length; index++) {
  9573. var mesh = scene.meshes[index];
  9574. if (mesh.parent === source) {
  9575. // doNotCloneChildren is always going to be False
  9576. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9577. }
  9578. }
  9579. }
  9580. for (index = 0; index < scene.particleSystems.length; index++) {
  9581. var system = scene.particleSystems[index];
  9582. if (system.emitter === source) {
  9583. system.clone(system.name, this);
  9584. }
  9585. }
  9586. this.computeWorldMatrix(true);
  9587. }
  9588. // Parent
  9589. if (parent !== null) {
  9590. this.parent = parent;
  9591. }
  9592. }
  9593. Mesh.prototype._clone = function () {
  9594. };
  9595. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9596. // Methods
  9597. get: function () {
  9598. return this._LODLevels.length > 0;
  9599. },
  9600. enumerable: true,
  9601. configurable: true
  9602. });
  9603. Mesh.prototype._sortLODLevels = function () {
  9604. this._LODLevels.sort(function (a, b) {
  9605. if (a.distance < b.distance) {
  9606. return 1;
  9607. }
  9608. if (a.distance > b.distance) {
  9609. return -1;
  9610. }
  9611. return 0;
  9612. });
  9613. };
  9614. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9615. if (mesh && mesh._masterMesh) {
  9616. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9617. return this;
  9618. }
  9619. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9620. this._LODLevels.push(level);
  9621. if (mesh) {
  9622. mesh._masterMesh = this;
  9623. }
  9624. this._sortLODLevels();
  9625. return this;
  9626. };
  9627. Mesh.prototype.removeLODLevel = function (mesh) {
  9628. for (var index = 0; index < this._LODLevels.length; index++) {
  9629. if (this._LODLevels[index].mesh === mesh) {
  9630. this._LODLevels.splice(index, 1);
  9631. if (mesh) {
  9632. mesh._masterMesh = null;
  9633. }
  9634. }
  9635. }
  9636. this._sortLODLevels();
  9637. return this;
  9638. };
  9639. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9640. if (!this._LODLevels || this._LODLevels.length === 0) {
  9641. return this;
  9642. }
  9643. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9644. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9645. return this;
  9646. }
  9647. for (var index = 0; index < this._LODLevels.length; index++) {
  9648. var level = this._LODLevels[index];
  9649. if (level.distance < distanceToCamera) {
  9650. if (level.mesh) {
  9651. level.mesh._preActivate();
  9652. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9653. }
  9654. return level.mesh;
  9655. }
  9656. }
  9657. return this;
  9658. };
  9659. Object.defineProperty(Mesh.prototype, "geometry", {
  9660. get: function () {
  9661. return this._geometry;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Mesh.prototype.getTotalVertices = function () {
  9667. if (!this._geometry) {
  9668. return 0;
  9669. }
  9670. return this._geometry.getTotalVertices();
  9671. };
  9672. Mesh.prototype.getVerticesData = function (kind) {
  9673. if (!this._geometry) {
  9674. return null;
  9675. }
  9676. return this._geometry.getVerticesData(kind);
  9677. };
  9678. Mesh.prototype.getVertexBuffer = function (kind) {
  9679. if (!this._geometry) {
  9680. return undefined;
  9681. }
  9682. return this._geometry.getVertexBuffer(kind);
  9683. };
  9684. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9685. if (!this._geometry) {
  9686. if (this._delayInfo) {
  9687. return this._delayInfo.indexOf(kind) !== -1;
  9688. }
  9689. return false;
  9690. }
  9691. return this._geometry.isVerticesDataPresent(kind);
  9692. };
  9693. Mesh.prototype.getVerticesDataKinds = function () {
  9694. if (!this._geometry) {
  9695. var result = [];
  9696. if (this._delayInfo) {
  9697. for (var kind in this._delayInfo) {
  9698. result.push(kind);
  9699. }
  9700. }
  9701. return result;
  9702. }
  9703. return this._geometry.getVerticesDataKinds();
  9704. };
  9705. Mesh.prototype.getTotalIndices = function () {
  9706. if (!this._geometry) {
  9707. return 0;
  9708. }
  9709. return this._geometry.getTotalIndices();
  9710. };
  9711. Mesh.prototype.getIndices = function () {
  9712. if (!this._geometry) {
  9713. return [];
  9714. }
  9715. return this._geometry.getIndices();
  9716. };
  9717. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9718. get: function () {
  9719. return this._masterMesh !== null && this._masterMesh !== undefined;
  9720. },
  9721. enumerable: true,
  9722. configurable: true
  9723. });
  9724. Mesh.prototype.isReady = function () {
  9725. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9726. return false;
  9727. }
  9728. return _super.prototype.isReady.call(this);
  9729. };
  9730. Mesh.prototype.isDisposed = function () {
  9731. return this._isDisposed;
  9732. };
  9733. // Methods
  9734. Mesh.prototype._preActivate = function () {
  9735. var sceneRenderId = this.getScene().getRenderId();
  9736. if (this._preActivateId == sceneRenderId) {
  9737. return;
  9738. }
  9739. this._preActivateId = sceneRenderId;
  9740. this._visibleInstances = null;
  9741. };
  9742. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9743. if (!this._visibleInstances) {
  9744. this._visibleInstances = {};
  9745. this._visibleInstances.defaultRenderId = renderId;
  9746. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9747. }
  9748. if (!this._visibleInstances[renderId]) {
  9749. this._visibleInstances[renderId] = new Array();
  9750. }
  9751. this._visibleInstances[renderId].push(instance);
  9752. };
  9753. Mesh.prototype.refreshBoundingInfo = function () {
  9754. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9755. if (data) {
  9756. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9757. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9758. }
  9759. if (this.subMeshes) {
  9760. for (var index = 0; index < this.subMeshes.length; index++) {
  9761. this.subMeshes[index].refreshBoundingInfo();
  9762. }
  9763. }
  9764. this._updateBoundingInfo();
  9765. };
  9766. Mesh.prototype._createGlobalSubMesh = function () {
  9767. var totalVertices = this.getTotalVertices();
  9768. if (!totalVertices || !this.getIndices()) {
  9769. return null;
  9770. }
  9771. this.releaseSubMeshes();
  9772. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9773. };
  9774. Mesh.prototype.subdivide = function (count) {
  9775. if (count < 1) {
  9776. return;
  9777. }
  9778. var totalIndices = this.getTotalIndices();
  9779. var subdivisionSize = (totalIndices / count) | 0;
  9780. var offset = 0;
  9781. while (subdivisionSize % 3 != 0) {
  9782. subdivisionSize++;
  9783. }
  9784. this.releaseSubMeshes();
  9785. for (var index = 0; index < count; index++) {
  9786. if (offset >= totalIndices) {
  9787. break;
  9788. }
  9789. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9790. offset += subdivisionSize;
  9791. }
  9792. this.synchronizeInstances();
  9793. };
  9794. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9795. if (kind instanceof Array) {
  9796. var temp = data;
  9797. data = kind;
  9798. kind = temp;
  9799. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9800. }
  9801. if (!this._geometry) {
  9802. var vertexData = new BABYLON.VertexData();
  9803. vertexData.set(data, kind);
  9804. var scene = this.getScene();
  9805. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9806. } else {
  9807. this._geometry.setVerticesData(kind, data, updatable, stride);
  9808. }
  9809. };
  9810. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9811. if (!this._geometry) {
  9812. return;
  9813. }
  9814. if (!makeItUnique) {
  9815. this._geometry.updateVerticesData(kind, data, updateExtends);
  9816. } else {
  9817. this.makeGeometryUnique();
  9818. this.updateVerticesData(kind, data, updateExtends, false);
  9819. }
  9820. };
  9821. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9822. if (!this._geometry) {
  9823. return;
  9824. }
  9825. if (!makeItUnique) {
  9826. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9827. } else {
  9828. this.makeGeometryUnique();
  9829. this.updateVerticesDataDirectly(kind, data, offset, false);
  9830. }
  9831. };
  9832. Mesh.prototype.makeGeometryUnique = function () {
  9833. if (!this._geometry) {
  9834. return;
  9835. }
  9836. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9837. geometry.applyToMesh(this);
  9838. };
  9839. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9840. if (!this._geometry) {
  9841. var vertexData = new BABYLON.VertexData();
  9842. vertexData.indices = indices;
  9843. var scene = this.getScene();
  9844. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9845. } else {
  9846. this._geometry.setIndices(indices, totalVertices);
  9847. }
  9848. };
  9849. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9850. var engine = this.getScene().getEngine();
  9851. // Wireframe
  9852. var indexToBind;
  9853. switch (fillMode) {
  9854. case BABYLON.Material.PointFillMode:
  9855. indexToBind = null;
  9856. break;
  9857. case BABYLON.Material.WireFrameFillMode:
  9858. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9859. break;
  9860. default:
  9861. case BABYLON.Material.TriangleFillMode:
  9862. indexToBind = this._geometry.getIndexBuffer();
  9863. break;
  9864. }
  9865. // VBOs
  9866. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9867. };
  9868. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9869. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9870. return;
  9871. }
  9872. var engine = this.getScene().getEngine();
  9873. switch (fillMode) {
  9874. case BABYLON.Material.PointFillMode:
  9875. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9876. break;
  9877. case BABYLON.Material.WireFrameFillMode:
  9878. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9879. break;
  9880. default:
  9881. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9882. }
  9883. };
  9884. Mesh.prototype.registerBeforeRender = function (func) {
  9885. this._onBeforeRenderCallbacks.push(func);
  9886. };
  9887. Mesh.prototype.unregisterBeforeRender = function (func) {
  9888. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9889. if (index > -1) {
  9890. this._onBeforeRenderCallbacks.splice(index, 1);
  9891. }
  9892. };
  9893. Mesh.prototype.registerAfterRender = function (func) {
  9894. this._onAfterRenderCallbacks.push(func);
  9895. };
  9896. Mesh.prototype.unregisterAfterRender = function (func) {
  9897. var index = this._onAfterRenderCallbacks.indexOf(func);
  9898. if (index > -1) {
  9899. this._onAfterRenderCallbacks.splice(index, 1);
  9900. }
  9901. };
  9902. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9903. var scene = this.getScene();
  9904. this._batchCache.mustReturn = false;
  9905. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9906. this._batchCache.visibleInstances[subMeshId] = null;
  9907. if (this._visibleInstances) {
  9908. var currentRenderId = scene.getRenderId();
  9909. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9910. var selfRenderId = this._renderId;
  9911. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9912. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9913. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9914. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9915. }
  9916. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9917. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9918. this._batchCache.mustReturn = true;
  9919. return this._batchCache;
  9920. }
  9921. if (currentRenderId !== selfRenderId) {
  9922. this._batchCache.renderSelf[subMeshId] = false;
  9923. }
  9924. }
  9925. this._renderIdForInstances[subMeshId] = currentRenderId;
  9926. }
  9927. return this._batchCache;
  9928. };
  9929. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9930. var visibleInstances = batch.visibleInstances[subMesh._id];
  9931. var matricesCount = visibleInstances.length + 1;
  9932. var bufferSize = matricesCount * 16 * 4;
  9933. while (this._instancesBufferSize < bufferSize) {
  9934. this._instancesBufferSize *= 2;
  9935. }
  9936. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9937. if (this._worldMatricesInstancesBuffer) {
  9938. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9939. }
  9940. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9941. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9942. }
  9943. var offset = 0;
  9944. var instancesCount = 0;
  9945. var world = this.getWorldMatrix();
  9946. if (batch.renderSelf[subMesh._id]) {
  9947. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9948. offset += 16;
  9949. instancesCount++;
  9950. }
  9951. if (visibleInstances) {
  9952. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9953. var instance = visibleInstances[instanceIndex];
  9954. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9955. offset += 16;
  9956. instancesCount++;
  9957. }
  9958. }
  9959. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9960. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9961. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9962. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9963. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9964. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9965. this._draw(subMesh, fillMode, instancesCount);
  9966. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9967. };
  9968. Mesh.prototype.render = function (subMesh) {
  9969. var scene = this.getScene();
  9970. // Managing instances
  9971. var batch = this._getInstancesRenderList(subMesh._id);
  9972. if (batch.mustReturn) {
  9973. return;
  9974. }
  9975. // Checking geometry state
  9976. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9977. return;
  9978. }
  9979. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9980. this._onBeforeRenderCallbacks[callbackIndex]();
  9981. }
  9982. var engine = scene.getEngine();
  9983. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9984. // Material
  9985. var effectiveMaterial = subMesh.getMaterial();
  9986. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9987. return;
  9988. }
  9989. // Outline - step 1
  9990. var savedDepthWrite = engine.getDepthWrite();
  9991. if (this.renderOutline) {
  9992. engine.setDepthWrite(false);
  9993. scene.getOutlineRenderer().render(subMesh, batch);
  9994. engine.setDepthWrite(savedDepthWrite);
  9995. }
  9996. effectiveMaterial._preBind();
  9997. var effect = effectiveMaterial.getEffect();
  9998. // Bind
  9999. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10000. this._bind(subMesh, effect, fillMode);
  10001. var world = this.getWorldMatrix();
  10002. effectiveMaterial.bind(world, this);
  10003. // Instances rendering
  10004. if (hardwareInstancedRendering) {
  10005. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10006. } else {
  10007. if (batch.renderSelf[subMesh._id]) {
  10008. // Draw
  10009. this._draw(subMesh, fillMode);
  10010. }
  10011. if (batch.visibleInstances[subMesh._id]) {
  10012. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10013. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10014. // World
  10015. world = instance.getWorldMatrix();
  10016. effectiveMaterial.bindOnlyWorldMatrix(world);
  10017. // Draw
  10018. this._draw(subMesh, fillMode);
  10019. }
  10020. }
  10021. }
  10022. // Unbind
  10023. effectiveMaterial.unbind();
  10024. // Outline - step 2
  10025. if (this.renderOutline && savedDepthWrite) {
  10026. engine.setDepthWrite(true);
  10027. engine.setColorWrite(false);
  10028. scene.getOutlineRenderer().render(subMesh, batch);
  10029. engine.setColorWrite(true);
  10030. }
  10031. // Overlay
  10032. if (this.renderOverlay) {
  10033. var currentMode = engine.getAlphaMode();
  10034. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10035. scene.getOutlineRenderer().render(subMesh, batch, true);
  10036. engine.setAlphaMode(currentMode);
  10037. }
  10038. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10039. this._onAfterRenderCallbacks[callbackIndex]();
  10040. }
  10041. };
  10042. Mesh.prototype.getEmittedParticleSystems = function () {
  10043. var results = new Array();
  10044. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10045. var particleSystem = this.getScene().particleSystems[index];
  10046. if (particleSystem.emitter === this) {
  10047. results.push(particleSystem);
  10048. }
  10049. }
  10050. return results;
  10051. };
  10052. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10053. var results = new Array();
  10054. var descendants = this.getDescendants();
  10055. descendants.push(this);
  10056. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10057. var particleSystem = this.getScene().particleSystems[index];
  10058. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10059. results.push(particleSystem);
  10060. }
  10061. }
  10062. return results;
  10063. };
  10064. Mesh.prototype.getChildren = function () {
  10065. var results = [];
  10066. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10067. var mesh = this.getScene().meshes[index];
  10068. if (mesh.parent == this) {
  10069. results.push(mesh);
  10070. }
  10071. }
  10072. return results;
  10073. };
  10074. Mesh.prototype._checkDelayState = function () {
  10075. var _this = this;
  10076. var that = this;
  10077. var scene = this.getScene();
  10078. if (this._geometry) {
  10079. this._geometry.load(scene);
  10080. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10081. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10082. scene._addPendingData(that);
  10083. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10084. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10085. if (data instanceof ArrayBuffer) {
  10086. _this._delayLoadingFunction(data, _this);
  10087. } else {
  10088. _this._delayLoadingFunction(JSON.parse(data), _this);
  10089. }
  10090. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10091. scene._removePendingData(_this);
  10092. }, function () {
  10093. }, scene.database, getBinaryData);
  10094. }
  10095. };
  10096. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10097. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10098. return false;
  10099. }
  10100. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10101. return false;
  10102. }
  10103. this._checkDelayState();
  10104. return true;
  10105. };
  10106. Mesh.prototype.setMaterialByID = function (id) {
  10107. var materials = this.getScene().materials;
  10108. for (var index = 0; index < materials.length; index++) {
  10109. if (materials[index].id == id) {
  10110. this.material = materials[index];
  10111. return;
  10112. }
  10113. }
  10114. // Multi
  10115. var multiMaterials = this.getScene().multiMaterials;
  10116. for (index = 0; index < multiMaterials.length; index++) {
  10117. if (multiMaterials[index].id == id) {
  10118. this.material = multiMaterials[index];
  10119. return;
  10120. }
  10121. }
  10122. };
  10123. Mesh.prototype.getAnimatables = function () {
  10124. var results = [];
  10125. if (this.material) {
  10126. results.push(this.material);
  10127. }
  10128. if (this.skeleton) {
  10129. results.push(this.skeleton);
  10130. }
  10131. return results;
  10132. };
  10133. // Geometry
  10134. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10135. // Position
  10136. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10137. return;
  10138. }
  10139. this._resetPointsArrayCache();
  10140. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10141. var temp = [];
  10142. for (var index = 0; index < data.length; index += 3) {
  10143. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10144. }
  10145. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10146. // Normals
  10147. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10148. return;
  10149. }
  10150. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10151. for (index = 0; index < data.length; index += 3) {
  10152. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10153. }
  10154. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10155. };
  10156. // Cache
  10157. Mesh.prototype._resetPointsArrayCache = function () {
  10158. this._positions = null;
  10159. };
  10160. Mesh.prototype._generatePointsArray = function () {
  10161. if (this._positions)
  10162. return true;
  10163. this._positions = [];
  10164. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10165. if (!data) {
  10166. return false;
  10167. }
  10168. for (var index = 0; index < data.length; index += 3) {
  10169. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10170. }
  10171. return true;
  10172. };
  10173. // Clone
  10174. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10175. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10176. };
  10177. // Dispose
  10178. Mesh.prototype.dispose = function (doNotRecurse) {
  10179. if (this._geometry) {
  10180. this._geometry.releaseForMesh(this, true);
  10181. }
  10182. // Instances
  10183. if (this._worldMatricesInstancesBuffer) {
  10184. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10185. this._worldMatricesInstancesBuffer = null;
  10186. }
  10187. while (this.instances.length) {
  10188. this.instances[0].dispose();
  10189. }
  10190. _super.prototype.dispose.call(this, doNotRecurse);
  10191. };
  10192. // Geometric tools
  10193. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  10194. var _this = this;
  10195. var scene = this.getScene();
  10196. var onload = function (img) {
  10197. // Getting height map data
  10198. var canvas = document.createElement("canvas");
  10199. var context = canvas.getContext("2d");
  10200. var heightMapWidth = img.width;
  10201. var heightMapHeight = img.height;
  10202. canvas.width = heightMapWidth;
  10203. canvas.height = heightMapHeight;
  10204. context.drawImage(img, 0, 0);
  10205. // Create VertexData from map data
  10206. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10207. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10208. };
  10209. BABYLON.Tools.LoadImage(url, onload, function () {
  10210. }, scene.database);
  10211. };
  10212. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10213. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10214. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10215. return;
  10216. }
  10217. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10218. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10219. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10220. var position = BABYLON.Vector3.Zero();
  10221. var normal = BABYLON.Vector3.Zero();
  10222. var uv = BABYLON.Vector2.Zero();
  10223. for (var index = 0; index < positions.length; index += 3) {
  10224. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10225. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10226. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10227. // Compute height
  10228. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10229. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10230. var pos = (u + v * heightMapWidth) * 4;
  10231. var r = buffer[pos] / 255.0;
  10232. var g = buffer[pos + 1] / 255.0;
  10233. var b = buffer[pos + 2] / 255.0;
  10234. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10235. normal.normalize();
  10236. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10237. position = position.add(normal);
  10238. position.toArray(positions, index);
  10239. }
  10240. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10241. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10242. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10243. };
  10244. Mesh.prototype.convertToFlatShadedMesh = function () {
  10245. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10246. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10247. var kinds = this.getVerticesDataKinds();
  10248. var vbs = [];
  10249. var data = [];
  10250. var newdata = [];
  10251. var updatableNormals = false;
  10252. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10253. var kind = kinds[kindIndex];
  10254. var vertexBuffer = this.getVertexBuffer(kind);
  10255. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10256. updatableNormals = vertexBuffer.isUpdatable();
  10257. kinds.splice(kindIndex, 1);
  10258. kindIndex--;
  10259. continue;
  10260. }
  10261. vbs[kind] = vertexBuffer;
  10262. data[kind] = vbs[kind].getData();
  10263. newdata[kind] = [];
  10264. }
  10265. // Save previous submeshes
  10266. var previousSubmeshes = this.subMeshes.slice(0);
  10267. var indices = this.getIndices();
  10268. var totalIndices = this.getTotalIndices();
  10269. for (var index = 0; index < totalIndices; index++) {
  10270. var vertexIndex = indices[index];
  10271. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10272. kind = kinds[kindIndex];
  10273. var stride = vbs[kind].getStrideSize();
  10274. for (var offset = 0; offset < stride; offset++) {
  10275. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10276. }
  10277. }
  10278. }
  10279. // Updating faces & normal
  10280. var normals = [];
  10281. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10282. for (index = 0; index < totalIndices; index += 3) {
  10283. indices[index] = index;
  10284. indices[index + 1] = index + 1;
  10285. indices[index + 2] = index + 2;
  10286. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10287. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10288. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10289. var p1p2 = p1.subtract(p2);
  10290. var p3p2 = p3.subtract(p2);
  10291. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10292. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10293. normals.push(normal.x);
  10294. normals.push(normal.y);
  10295. normals.push(normal.z);
  10296. }
  10297. }
  10298. this.setIndices(indices);
  10299. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10300. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10301. kind = kinds[kindIndex];
  10302. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10303. }
  10304. // Updating submeshes
  10305. this.releaseSubMeshes();
  10306. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10307. var previousOne = previousSubmeshes[submeshIndex];
  10308. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10309. }
  10310. this.synchronizeInstances();
  10311. };
  10312. // Instances
  10313. Mesh.prototype.createInstance = function (name) {
  10314. return new BABYLON.InstancedMesh(name, this);
  10315. };
  10316. Mesh.prototype.synchronizeInstances = function () {
  10317. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10318. var instance = this.instances[instanceIndex];
  10319. instance._syncSubMeshes();
  10320. }
  10321. };
  10322. /**
  10323. * Simplify the mesh according to the given array of settings.
  10324. * Function will return immediately and will simplify async.
  10325. * @param settings a collection of simplification settings.
  10326. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10327. * @param type the type of simplification to run.
  10328. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10329. */
  10330. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10331. var _this = this;
  10332. if (typeof parallelProcessing === "undefined") { parallelProcessing = true; }
  10333. if (typeof type === "undefined") { type = 0 /* QUADRATIC */; }
  10334. var getSimplifier = function () {
  10335. switch (type) {
  10336. case 0 /* QUADRATIC */:
  10337. default:
  10338. return new BABYLON.QuadraticErrorSimplification(_this);
  10339. }
  10340. };
  10341. if (parallelProcessing) {
  10342. //parallel simplifier
  10343. settings.forEach(function (setting) {
  10344. var simplifier = getSimplifier();
  10345. simplifier.simplify(setting, function (newMesh) {
  10346. _this.addLODLevel(setting.distance, newMesh);
  10347. //check if it is the last
  10348. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10349. //all done, run the success callback.
  10350. successCallback();
  10351. }
  10352. });
  10353. });
  10354. } else {
  10355. //single simplifier.
  10356. var simplifier = getSimplifier();
  10357. var runDecimation = function (setting, callback) {
  10358. simplifier.simplify(setting, function (newMesh) {
  10359. _this.addLODLevel(setting.distance, newMesh);
  10360. //run the next quality level
  10361. callback();
  10362. });
  10363. };
  10364. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10365. runDecimation(settings[loop.index], function () {
  10366. loop.executeNext();
  10367. });
  10368. }, function () {
  10369. //execution ended, run the success callback.
  10370. if (successCallback) {
  10371. successCallback();
  10372. }
  10373. });
  10374. }
  10375. };
  10376. // Statics
  10377. Mesh.CreateBox = function (name, size, scene, updatable) {
  10378. var box = new Mesh(name, scene);
  10379. var vertexData = BABYLON.VertexData.CreateBox(size);
  10380. vertexData.applyToMesh(box, updatable);
  10381. return box;
  10382. };
  10383. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10384. var sphere = new Mesh(name, scene);
  10385. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10386. vertexData.applyToMesh(sphere, updatable);
  10387. return sphere;
  10388. };
  10389. // Cylinder and cone (Code inspired by SharpDX.org)
  10390. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10391. // subdivisions is a new parameter, we need to support old signature
  10392. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10393. if (scene !== undefined) {
  10394. updatable = scene;
  10395. }
  10396. scene = subdivisions;
  10397. subdivisions = 1;
  10398. }
  10399. var cylinder = new Mesh(name, scene);
  10400. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10401. vertexData.applyToMesh(cylinder, updatable);
  10402. return cylinder;
  10403. };
  10404. // Torus (Code from SharpDX.org)
  10405. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10406. var torus = new Mesh(name, scene);
  10407. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10408. vertexData.applyToMesh(torus, updatable);
  10409. return torus;
  10410. };
  10411. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10412. var torusKnot = new Mesh(name, scene);
  10413. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10414. vertexData.applyToMesh(torusKnot, updatable);
  10415. return torusKnot;
  10416. };
  10417. // Lines
  10418. Mesh.CreateLines = function (name, points, scene, updatable) {
  10419. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10420. var vertexData = BABYLON.VertexData.CreateLines(points);
  10421. vertexData.applyToMesh(lines, updatable);
  10422. return lines;
  10423. };
  10424. // Plane & ground
  10425. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10426. var plane = new Mesh(name, scene);
  10427. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10428. vertexData.applyToMesh(plane, updatable);
  10429. return plane;
  10430. };
  10431. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10432. var ground = new BABYLON.GroundMesh(name, scene);
  10433. ground._setReady(false);
  10434. ground._subdivisions = subdivisions;
  10435. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10436. vertexData.applyToMesh(ground, updatable);
  10437. ground._setReady(true);
  10438. return ground;
  10439. };
  10440. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10441. var tiledGround = new Mesh(name, scene);
  10442. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10443. vertexData.applyToMesh(tiledGround, updatable);
  10444. return tiledGround;
  10445. };
  10446. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10447. var ground = new BABYLON.GroundMesh(name, scene);
  10448. ground._subdivisions = subdivisions;
  10449. ground._setReady(false);
  10450. var onload = function (img) {
  10451. // Getting height map data
  10452. var canvas = document.createElement("canvas");
  10453. var context = canvas.getContext("2d");
  10454. var heightMapWidth = img.width;
  10455. var heightMapHeight = img.height;
  10456. canvas.width = heightMapWidth;
  10457. canvas.height = heightMapHeight;
  10458. context.drawImage(img, 0, 0);
  10459. // Create VertexData from map data
  10460. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10461. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10462. vertexData.applyToMesh(ground, updatable);
  10463. ground._setReady(true);
  10464. };
  10465. BABYLON.Tools.LoadImage(url, onload, function () {
  10466. }, scene.database);
  10467. return ground;
  10468. };
  10469. // Tools
  10470. Mesh.MinMax = function (meshes) {
  10471. var minVector = null;
  10472. var maxVector = null;
  10473. for (var i in meshes) {
  10474. var mesh = meshes[i];
  10475. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10476. if (!minVector) {
  10477. minVector = boundingBox.minimumWorld;
  10478. maxVector = boundingBox.maximumWorld;
  10479. continue;
  10480. }
  10481. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10482. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10483. }
  10484. return {
  10485. min: minVector,
  10486. max: maxVector
  10487. };
  10488. };
  10489. Mesh.Center = function (meshesOrMinMaxVector) {
  10490. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10491. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10492. };
  10493. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10494. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10495. var source = meshes[0];
  10496. var material = source.material;
  10497. var scene = source.getScene();
  10498. if (!allow32BitsIndices) {
  10499. var totalVertices = 0;
  10500. for (var index = 0; index < meshes.length; index++) {
  10501. totalVertices += meshes[index].getTotalVertices();
  10502. if (totalVertices > 65536) {
  10503. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10504. return null;
  10505. }
  10506. }
  10507. }
  10508. // Merge
  10509. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10510. vertexData.transform(source.getWorldMatrix());
  10511. for (index = 1; index < meshes.length; index++) {
  10512. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10513. otherVertexData.transform(meshes[index].getWorldMatrix());
  10514. vertexData.merge(otherVertexData);
  10515. }
  10516. var newMesh = new Mesh(source.name + "_merged", scene);
  10517. vertexData.applyToMesh(newMesh);
  10518. // Setting properties
  10519. newMesh.material = material;
  10520. newMesh.checkCollisions = source.checkCollisions;
  10521. // Cleaning
  10522. if (disposeSource) {
  10523. for (index = 0; index < meshes.length; index++) {
  10524. meshes[index].dispose();
  10525. }
  10526. }
  10527. return newMesh;
  10528. };
  10529. return Mesh;
  10530. })(BABYLON.AbstractMesh);
  10531. BABYLON.Mesh = Mesh;
  10532. })(BABYLON || (BABYLON = {}));
  10533. //# sourceMappingURL=babylon.mesh.js.map
  10534. var BABYLON;
  10535. (function (BABYLON) {
  10536. var GroundMesh = (function (_super) {
  10537. __extends(GroundMesh, _super);
  10538. function GroundMesh(name, scene) {
  10539. _super.call(this, name, scene);
  10540. this.generateOctree = false;
  10541. this._worldInverse = new BABYLON.Matrix();
  10542. }
  10543. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10544. get: function () {
  10545. return this._subdivisions;
  10546. },
  10547. enumerable: true,
  10548. configurable: true
  10549. });
  10550. GroundMesh.prototype.optimize = function (chunksCount) {
  10551. this.subdivide(this._subdivisions);
  10552. this.createOrUpdateSubmeshesOctree(32);
  10553. };
  10554. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10555. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10556. this.getWorldMatrix().invertToRef(this._worldInverse);
  10557. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10558. var pickInfo = this.intersects(ray);
  10559. if (pickInfo.hit) {
  10560. return pickInfo.pickedPoint.y;
  10561. }
  10562. return 0;
  10563. };
  10564. return GroundMesh;
  10565. })(BABYLON.Mesh);
  10566. BABYLON.GroundMesh = GroundMesh;
  10567. })(BABYLON || (BABYLON = {}));
  10568. //# sourceMappingURL=babylon.groundMesh.js.map
  10569. var BABYLON;
  10570. (function (BABYLON) {
  10571. var InstancedMesh = (function (_super) {
  10572. __extends(InstancedMesh, _super);
  10573. function InstancedMesh(name, source) {
  10574. _super.call(this, name, source.getScene());
  10575. source.instances.push(this);
  10576. this._sourceMesh = source;
  10577. this.position.copyFrom(source.position);
  10578. this.rotation.copyFrom(source.rotation);
  10579. this.scaling.copyFrom(source.scaling);
  10580. if (source.rotationQuaternion) {
  10581. this.rotationQuaternion = source.rotationQuaternion.clone();
  10582. }
  10583. this.infiniteDistance = source.infiniteDistance;
  10584. this.setPivotMatrix(source.getPivotMatrix());
  10585. this.refreshBoundingInfo();
  10586. this._syncSubMeshes();
  10587. }
  10588. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10589. // Methods
  10590. get: function () {
  10591. return this._sourceMesh.receiveShadows;
  10592. },
  10593. enumerable: true,
  10594. configurable: true
  10595. });
  10596. Object.defineProperty(InstancedMesh.prototype, "material", {
  10597. get: function () {
  10598. return this._sourceMesh.material;
  10599. },
  10600. enumerable: true,
  10601. configurable: true
  10602. });
  10603. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10604. get: function () {
  10605. return this._sourceMesh.visibility;
  10606. },
  10607. enumerable: true,
  10608. configurable: true
  10609. });
  10610. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10611. get: function () {
  10612. return this._sourceMesh.skeleton;
  10613. },
  10614. enumerable: true,
  10615. configurable: true
  10616. });
  10617. InstancedMesh.prototype.getTotalVertices = function () {
  10618. return this._sourceMesh.getTotalVertices();
  10619. };
  10620. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10621. get: function () {
  10622. return this._sourceMesh;
  10623. },
  10624. enumerable: true,
  10625. configurable: true
  10626. });
  10627. InstancedMesh.prototype.getVerticesData = function (kind) {
  10628. return this._sourceMesh.getVerticesData(kind);
  10629. };
  10630. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10631. return this._sourceMesh.isVerticesDataPresent(kind);
  10632. };
  10633. InstancedMesh.prototype.getIndices = function () {
  10634. return this._sourceMesh.getIndices();
  10635. };
  10636. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10637. get: function () {
  10638. return this._sourceMesh._positions;
  10639. },
  10640. enumerable: true,
  10641. configurable: true
  10642. });
  10643. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10644. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10645. if (data) {
  10646. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10647. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10648. }
  10649. this._updateBoundingInfo();
  10650. };
  10651. InstancedMesh.prototype._preActivate = function () {
  10652. if (this._currentLOD) {
  10653. this._currentLOD._preActivate();
  10654. }
  10655. };
  10656. InstancedMesh.prototype._activate = function (renderId) {
  10657. if (this._currentLOD) {
  10658. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10659. }
  10660. };
  10661. InstancedMesh.prototype.getLOD = function (camera) {
  10662. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10663. if (this._currentLOD === this.sourceMesh) {
  10664. return this;
  10665. }
  10666. return this._currentLOD;
  10667. };
  10668. InstancedMesh.prototype._syncSubMeshes = function () {
  10669. this.releaseSubMeshes();
  10670. if (this._sourceMesh.subMeshes) {
  10671. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10672. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10673. }
  10674. }
  10675. };
  10676. InstancedMesh.prototype._generatePointsArray = function () {
  10677. return this._sourceMesh._generatePointsArray();
  10678. };
  10679. // Clone
  10680. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10681. var result = this._sourceMesh.createInstance(name);
  10682. // Deep copy
  10683. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10684. // Bounding info
  10685. this.refreshBoundingInfo();
  10686. // Parent
  10687. if (newParent) {
  10688. result.parent = newParent;
  10689. }
  10690. if (!doNotCloneChildren) {
  10691. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10692. var mesh = this.getScene().meshes[index];
  10693. if (mesh.parent == this) {
  10694. mesh.clone(mesh.name, result);
  10695. }
  10696. }
  10697. }
  10698. result.computeWorldMatrix(true);
  10699. return result;
  10700. };
  10701. // Dispoe
  10702. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10703. // Remove from mesh
  10704. var index = this._sourceMesh.instances.indexOf(this);
  10705. this._sourceMesh.instances.splice(index, 1);
  10706. _super.prototype.dispose.call(this, doNotRecurse);
  10707. };
  10708. return InstancedMesh;
  10709. })(BABYLON.AbstractMesh);
  10710. BABYLON.InstancedMesh = InstancedMesh;
  10711. })(BABYLON || (BABYLON = {}));
  10712. //# sourceMappingURL=babylon.instancedMesh.js.map
  10713. var BABYLON;
  10714. (function (BABYLON) {
  10715. var SubMesh = (function () {
  10716. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10717. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10718. this.materialIndex = materialIndex;
  10719. this.verticesStart = verticesStart;
  10720. this.verticesCount = verticesCount;
  10721. this.indexStart = indexStart;
  10722. this.indexCount = indexCount;
  10723. this._renderId = 0;
  10724. this._mesh = mesh;
  10725. this._renderingMesh = renderingMesh || mesh;
  10726. mesh.subMeshes.push(this);
  10727. this._id = mesh.subMeshes.length - 1;
  10728. if (createBoundingBox) {
  10729. this.refreshBoundingInfo();
  10730. }
  10731. }
  10732. SubMesh.prototype.getBoundingInfo = function () {
  10733. return this._boundingInfo;
  10734. };
  10735. SubMesh.prototype.getMesh = function () {
  10736. return this._mesh;
  10737. };
  10738. SubMesh.prototype.getRenderingMesh = function () {
  10739. return this._renderingMesh;
  10740. };
  10741. SubMesh.prototype.getMaterial = function () {
  10742. var rootMaterial = this._renderingMesh.material;
  10743. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10744. var multiMaterial = rootMaterial;
  10745. return multiMaterial.getSubMaterial(this.materialIndex);
  10746. }
  10747. if (!rootMaterial) {
  10748. return this._mesh.getScene().defaultMaterial;
  10749. }
  10750. return rootMaterial;
  10751. };
  10752. // Methods
  10753. SubMesh.prototype.refreshBoundingInfo = function () {
  10754. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10755. if (!data) {
  10756. this._boundingInfo = this._mesh._boundingInfo;
  10757. return;
  10758. }
  10759. var indices = this._renderingMesh.getIndices();
  10760. var extend;
  10761. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10762. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10763. } else {
  10764. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10765. }
  10766. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10767. };
  10768. SubMesh.prototype._checkCollision = function (collider) {
  10769. return this._boundingInfo._checkCollision(collider);
  10770. };
  10771. SubMesh.prototype.updateBoundingInfo = function (world) {
  10772. if (!this._boundingInfo) {
  10773. this.refreshBoundingInfo();
  10774. }
  10775. this._boundingInfo._update(world);
  10776. };
  10777. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10778. return this._boundingInfo.isInFrustum(frustumPlanes);
  10779. };
  10780. SubMesh.prototype.render = function () {
  10781. this._renderingMesh.render(this);
  10782. };
  10783. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10784. if (!this._linesIndexBuffer) {
  10785. var linesIndices = [];
  10786. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10787. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10788. }
  10789. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10790. this.linesIndexCount = linesIndices.length;
  10791. }
  10792. return this._linesIndexBuffer;
  10793. };
  10794. SubMesh.prototype.canIntersects = function (ray) {
  10795. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10796. };
  10797. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10798. var intersectInfo = null;
  10799. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10800. var p0 = positions[indices[index]];
  10801. var p1 = positions[indices[index + 1]];
  10802. var p2 = positions[indices[index + 2]];
  10803. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10804. if (currentIntersectInfo) {
  10805. if (currentIntersectInfo.distance < 0) {
  10806. continue;
  10807. }
  10808. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10809. intersectInfo = currentIntersectInfo;
  10810. intersectInfo.faceId = index / 3;
  10811. if (fastCheck) {
  10812. break;
  10813. }
  10814. }
  10815. }
  10816. }
  10817. return intersectInfo;
  10818. };
  10819. // Clone
  10820. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10821. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10822. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10823. return result;
  10824. };
  10825. // Dispose
  10826. SubMesh.prototype.dispose = function () {
  10827. if (this._linesIndexBuffer) {
  10828. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10829. this._linesIndexBuffer = null;
  10830. }
  10831. // Remove from mesh
  10832. var index = this._mesh.subMeshes.indexOf(this);
  10833. this._mesh.subMeshes.splice(index, 1);
  10834. };
  10835. // Statics
  10836. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10837. var minVertexIndex = Number.MAX_VALUE;
  10838. var maxVertexIndex = -Number.MAX_VALUE;
  10839. renderingMesh = renderingMesh || mesh;
  10840. var indices = renderingMesh.getIndices();
  10841. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10842. var vertexIndex = indices[index];
  10843. if (vertexIndex < minVertexIndex)
  10844. minVertexIndex = vertexIndex;
  10845. if (vertexIndex > maxVertexIndex)
  10846. maxVertexIndex = vertexIndex;
  10847. }
  10848. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10849. };
  10850. return SubMesh;
  10851. })();
  10852. BABYLON.SubMesh = SubMesh;
  10853. })(BABYLON || (BABYLON = {}));
  10854. //# sourceMappingURL=babylon.subMesh.js.map
  10855. var BABYLON;
  10856. (function (BABYLON) {
  10857. var BaseTexture = (function () {
  10858. function BaseTexture(scene) {
  10859. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10860. this.hasAlpha = false;
  10861. this.getAlphaFromRGB = false;
  10862. this.level = 1;
  10863. this.isCube = false;
  10864. this.isRenderTarget = false;
  10865. this.animations = new Array();
  10866. this.coordinatesIndex = 0;
  10867. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10868. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10869. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10870. this.anisotropicFilteringLevel = 4;
  10871. this._scene = scene;
  10872. this._scene.textures.push(this);
  10873. }
  10874. BaseTexture.prototype.getScene = function () {
  10875. return this._scene;
  10876. };
  10877. BaseTexture.prototype.getTextureMatrix = function () {
  10878. return null;
  10879. };
  10880. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10881. return null;
  10882. };
  10883. BaseTexture.prototype.getInternalTexture = function () {
  10884. return this._texture;
  10885. };
  10886. BaseTexture.prototype.isReady = function () {
  10887. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10888. return true;
  10889. }
  10890. if (this._texture) {
  10891. return this._texture.isReady;
  10892. }
  10893. return false;
  10894. };
  10895. BaseTexture.prototype.getSize = function () {
  10896. if (this._texture._width) {
  10897. return { width: this._texture._width, height: this._texture._height };
  10898. }
  10899. if (this._texture._size) {
  10900. return { width: this._texture._size, height: this._texture._size };
  10901. }
  10902. return { width: 0, height: 0 };
  10903. };
  10904. BaseTexture.prototype.getBaseSize = function () {
  10905. if (!this.isReady())
  10906. return { width: 0, height: 0 };
  10907. if (this._texture._size) {
  10908. return { width: this._texture._size, height: this._texture._size };
  10909. }
  10910. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10911. };
  10912. BaseTexture.prototype.scale = function (ratio) {
  10913. };
  10914. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10915. get: function () {
  10916. return false;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10922. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10923. for (var index = 0; index < texturesCache.length; index++) {
  10924. var texturesCacheEntry = texturesCache[index];
  10925. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10926. texturesCache.splice(index, 1);
  10927. return;
  10928. }
  10929. }
  10930. };
  10931. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10932. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10933. for (var index = 0; index < texturesCache.length; index++) {
  10934. var texturesCacheEntry = texturesCache[index];
  10935. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10936. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10937. texturesCacheEntry.references++;
  10938. return texturesCacheEntry;
  10939. }
  10940. }
  10941. }
  10942. return null;
  10943. };
  10944. BaseTexture.prototype.delayLoad = function () {
  10945. };
  10946. BaseTexture.prototype.releaseInternalTexture = function () {
  10947. if (!this._texture) {
  10948. return;
  10949. }
  10950. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10951. this._texture.references--;
  10952. // Final reference ?
  10953. if (this._texture.references === 0) {
  10954. var index = texturesCache.indexOf(this._texture);
  10955. texturesCache.splice(index, 1);
  10956. this._scene.getEngine()._releaseTexture(this._texture);
  10957. delete this._texture;
  10958. }
  10959. };
  10960. BaseTexture.prototype.clone = function () {
  10961. return null;
  10962. };
  10963. BaseTexture.prototype.dispose = function () {
  10964. // Remove from scene
  10965. var index = this._scene.textures.indexOf(this);
  10966. if (index >= 0) {
  10967. this._scene.textures.splice(index, 1);
  10968. }
  10969. if (this._texture === undefined) {
  10970. return;
  10971. }
  10972. this.releaseInternalTexture();
  10973. // Callback
  10974. if (this.onDispose) {
  10975. this.onDispose();
  10976. }
  10977. };
  10978. return BaseTexture;
  10979. })();
  10980. BABYLON.BaseTexture = BaseTexture;
  10981. })(BABYLON || (BABYLON = {}));
  10982. //# sourceMappingURL=babylon.baseTexture.js.map
  10983. var BABYLON;
  10984. (function (BABYLON) {
  10985. var RenderingGroup = (function () {
  10986. function RenderingGroup(index, scene) {
  10987. this.index = index;
  10988. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10989. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10990. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10991. this._scene = scene;
  10992. }
  10993. RenderingGroup.prototype.render = function (customRenderFunction) {
  10994. if (customRenderFunction) {
  10995. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10996. return true;
  10997. }
  10998. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10999. return false;
  11000. }
  11001. var engine = this._scene.getEngine();
  11002. // Opaque
  11003. var subIndex;
  11004. var submesh;
  11005. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11006. submesh = this._opaqueSubMeshes.data[subIndex];
  11007. submesh.render();
  11008. }
  11009. // Alpha test
  11010. engine.setAlphaTesting(true);
  11011. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11012. submesh = this._alphaTestSubMeshes.data[subIndex];
  11013. submesh.render();
  11014. }
  11015. engine.setAlphaTesting(false);
  11016. // Transparent
  11017. if (this._transparentSubMeshes.length) {
  11018. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11019. submesh = this._transparentSubMeshes.data[subIndex];
  11020. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11021. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11022. }
  11023. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11024. sortedArray.sort(function (a, b) {
  11025. // Alpha index first
  11026. if (a._alphaIndex > b._alphaIndex) {
  11027. return 1;
  11028. }
  11029. if (a._alphaIndex < b._alphaIndex) {
  11030. return -1;
  11031. }
  11032. // Then distance to camera
  11033. if (a._distanceToCamera < b._distanceToCamera) {
  11034. return 1;
  11035. }
  11036. if (a._distanceToCamera > b._distanceToCamera) {
  11037. return -1;
  11038. }
  11039. return 0;
  11040. });
  11041. // Rendering
  11042. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11043. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11044. submesh = sortedArray[subIndex];
  11045. submesh.render();
  11046. }
  11047. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11048. }
  11049. return true;
  11050. };
  11051. RenderingGroup.prototype.prepare = function () {
  11052. this._opaqueSubMeshes.reset();
  11053. this._transparentSubMeshes.reset();
  11054. this._alphaTestSubMeshes.reset();
  11055. };
  11056. RenderingGroup.prototype.dispatch = function (subMesh) {
  11057. var material = subMesh.getMaterial();
  11058. var mesh = subMesh.getMesh();
  11059. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11060. this._transparentSubMeshes.push(subMesh);
  11061. } else if (material.needAlphaTesting()) {
  11062. this._alphaTestSubMeshes.push(subMesh);
  11063. } else {
  11064. this._opaqueSubMeshes.push(subMesh); // Opaque
  11065. }
  11066. };
  11067. return RenderingGroup;
  11068. })();
  11069. BABYLON.RenderingGroup = RenderingGroup;
  11070. })(BABYLON || (BABYLON = {}));
  11071. //# sourceMappingURL=babylon.renderingGroup.js.map
  11072. var BABYLON;
  11073. (function (BABYLON) {
  11074. var RenderingManager = (function () {
  11075. function RenderingManager(scene) {
  11076. this._renderingGroups = new Array();
  11077. this._scene = scene;
  11078. }
  11079. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11080. if (this._scene._activeParticleSystems.length === 0) {
  11081. return;
  11082. }
  11083. // Particles
  11084. var beforeParticlesDate = BABYLON.Tools.Now;
  11085. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11086. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11087. if (particleSystem.renderingGroupId !== index) {
  11088. continue;
  11089. }
  11090. this._clearDepthBuffer();
  11091. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11092. this._scene._activeParticles += particleSystem.render();
  11093. }
  11094. }
  11095. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11096. };
  11097. RenderingManager.prototype._renderSprites = function (index) {
  11098. if (this._scene.spriteManagers.length === 0) {
  11099. return;
  11100. }
  11101. // Sprites
  11102. var beforeSpritessDate = BABYLON.Tools.Now;
  11103. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11104. var spriteManager = this._scene.spriteManagers[id];
  11105. if (spriteManager.renderingGroupId === index) {
  11106. this._clearDepthBuffer();
  11107. spriteManager.render();
  11108. }
  11109. }
  11110. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11111. };
  11112. RenderingManager.prototype._clearDepthBuffer = function () {
  11113. if (this._depthBufferAlreadyCleaned) {
  11114. return;
  11115. }
  11116. this._scene.getEngine().clear(0, false, true);
  11117. this._depthBufferAlreadyCleaned = true;
  11118. };
  11119. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11120. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11121. this._depthBufferAlreadyCleaned = false;
  11122. var renderingGroup = this._renderingGroups[index];
  11123. if (renderingGroup) {
  11124. this._clearDepthBuffer();
  11125. if (!renderingGroup.render(customRenderFunction)) {
  11126. this._renderingGroups.splice(index, 1);
  11127. }
  11128. }
  11129. this._renderSprites(index);
  11130. if (renderParticles) {
  11131. this._renderParticles(index, activeMeshes);
  11132. }
  11133. }
  11134. };
  11135. RenderingManager.prototype.reset = function () {
  11136. for (var index in this._renderingGroups) {
  11137. var renderingGroup = this._renderingGroups[index];
  11138. renderingGroup.prepare();
  11139. }
  11140. };
  11141. RenderingManager.prototype.dispatch = function (subMesh) {
  11142. var mesh = subMesh.getMesh();
  11143. var renderingGroupId = mesh.renderingGroupId || 0;
  11144. if (!this._renderingGroups[renderingGroupId]) {
  11145. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11146. }
  11147. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11148. };
  11149. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11150. return RenderingManager;
  11151. })();
  11152. BABYLON.RenderingManager = RenderingManager;
  11153. })(BABYLON || (BABYLON = {}));
  11154. //# sourceMappingURL=babylon.renderingManager.js.map
  11155. var BABYLON;
  11156. (function (BABYLON) {
  11157. var Texture = (function (_super) {
  11158. __extends(Texture, _super);
  11159. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11160. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11161. if (typeof onLoad === "undefined") { onLoad = null; }
  11162. if (typeof onError === "undefined") { onError = null; }
  11163. if (typeof buffer === "undefined") { buffer = null; }
  11164. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  11165. _super.call(this, scene);
  11166. this.uOffset = 0;
  11167. this.vOffset = 0;
  11168. this.uScale = 1.0;
  11169. this.vScale = 1.0;
  11170. this.uAng = 0;
  11171. this.vAng = 0;
  11172. this.wAng = 0;
  11173. this.name = url;
  11174. this.url = url;
  11175. this._noMipmap = noMipmap;
  11176. this._invertY = invertY;
  11177. this._samplingMode = samplingMode;
  11178. this._buffer = buffer;
  11179. this._deleteBuffer = deleteBuffer;
  11180. if (!url) {
  11181. return;
  11182. }
  11183. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11184. if (!this._texture) {
  11185. if (!scene.useDelayedTextureLoading) {
  11186. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11187. if (deleteBuffer) {
  11188. delete this._buffer;
  11189. }
  11190. } else {
  11191. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11192. }
  11193. }
  11194. }
  11195. Texture.prototype.delayLoad = function () {
  11196. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11197. return;
  11198. }
  11199. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11200. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11201. if (!this._texture) {
  11202. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11203. if (this._deleteBuffer) {
  11204. delete this._buffer;
  11205. }
  11206. }
  11207. };
  11208. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11209. x -= this.uOffset + 0.5;
  11210. y -= this.vOffset + 0.5;
  11211. z -= 0.5;
  11212. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11213. t.x *= this.uScale;
  11214. t.y *= this.vScale;
  11215. t.x += 0.5;
  11216. t.y += 0.5;
  11217. t.z += 0.5;
  11218. };
  11219. Texture.prototype.getTextureMatrix = function () {
  11220. 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) {
  11221. return this._cachedTextureMatrix;
  11222. }
  11223. this._cachedUOffset = this.uOffset;
  11224. this._cachedVOffset = this.vOffset;
  11225. this._cachedUScale = this.uScale;
  11226. this._cachedVScale = this.vScale;
  11227. this._cachedUAng = this.uAng;
  11228. this._cachedVAng = this.vAng;
  11229. this._cachedWAng = this.wAng;
  11230. if (!this._cachedTextureMatrix) {
  11231. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11232. this._rowGenerationMatrix = new BABYLON.Matrix();
  11233. this._t0 = BABYLON.Vector3.Zero();
  11234. this._t1 = BABYLON.Vector3.Zero();
  11235. this._t2 = BABYLON.Vector3.Zero();
  11236. }
  11237. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11238. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11239. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11240. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11241. this._t1.subtractInPlace(this._t0);
  11242. this._t2.subtractInPlace(this._t0);
  11243. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11244. this._cachedTextureMatrix.m[0] = this._t1.x;
  11245. this._cachedTextureMatrix.m[1] = this._t1.y;
  11246. this._cachedTextureMatrix.m[2] = this._t1.z;
  11247. this._cachedTextureMatrix.m[4] = this._t2.x;
  11248. this._cachedTextureMatrix.m[5] = this._t2.y;
  11249. this._cachedTextureMatrix.m[6] = this._t2.z;
  11250. this._cachedTextureMatrix.m[8] = this._t0.x;
  11251. this._cachedTextureMatrix.m[9] = this._t0.y;
  11252. this._cachedTextureMatrix.m[10] = this._t0.z;
  11253. return this._cachedTextureMatrix;
  11254. };
  11255. Texture.prototype.getReflectionTextureMatrix = function () {
  11256. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11257. return this._cachedTextureMatrix;
  11258. }
  11259. if (!this._cachedTextureMatrix) {
  11260. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11261. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11262. }
  11263. this._cachedCoordinatesMode = this.coordinatesMode;
  11264. switch (this.coordinatesMode) {
  11265. case BABYLON.Texture.SPHERICAL_MODE:
  11266. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11267. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11268. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11269. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11270. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11271. break;
  11272. case BABYLON.Texture.PLANAR_MODE:
  11273. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11274. this._cachedTextureMatrix[0] = this.uScale;
  11275. this._cachedTextureMatrix[5] = this.vScale;
  11276. this._cachedTextureMatrix[12] = this.uOffset;
  11277. this._cachedTextureMatrix[13] = this.vOffset;
  11278. break;
  11279. case BABYLON.Texture.PROJECTION_MODE:
  11280. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11281. this._projectionModeMatrix.m[0] = 0.5;
  11282. this._projectionModeMatrix.m[5] = -0.5;
  11283. this._projectionModeMatrix.m[10] = 0.0;
  11284. this._projectionModeMatrix.m[12] = 0.5;
  11285. this._projectionModeMatrix.m[13] = 0.5;
  11286. this._projectionModeMatrix.m[14] = 1.0;
  11287. this._projectionModeMatrix.m[15] = 1.0;
  11288. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11289. break;
  11290. default:
  11291. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11292. break;
  11293. }
  11294. return this._cachedTextureMatrix;
  11295. };
  11296. Texture.prototype.clone = function () {
  11297. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11298. // Base texture
  11299. newTexture.hasAlpha = this.hasAlpha;
  11300. newTexture.level = this.level;
  11301. newTexture.wrapU = this.wrapU;
  11302. newTexture.wrapV = this.wrapV;
  11303. newTexture.coordinatesIndex = this.coordinatesIndex;
  11304. newTexture.coordinatesMode = this.coordinatesMode;
  11305. // Texture
  11306. newTexture.uOffset = this.uOffset;
  11307. newTexture.vOffset = this.vOffset;
  11308. newTexture.uScale = this.uScale;
  11309. newTexture.vScale = this.vScale;
  11310. newTexture.uAng = this.uAng;
  11311. newTexture.vAng = this.vAng;
  11312. newTexture.wAng = this.wAng;
  11313. return newTexture;
  11314. };
  11315. // Statics
  11316. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11317. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11318. if (typeof onLoad === "undefined") { onLoad = null; }
  11319. if (typeof onError === "undefined") { onError = null; }
  11320. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11321. };
  11322. Texture.NEAREST_SAMPLINGMODE = 1;
  11323. Texture.BILINEAR_SAMPLINGMODE = 2;
  11324. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11325. Texture.EXPLICIT_MODE = 0;
  11326. Texture.SPHERICAL_MODE = 1;
  11327. Texture.PLANAR_MODE = 2;
  11328. Texture.CUBIC_MODE = 3;
  11329. Texture.PROJECTION_MODE = 4;
  11330. Texture.SKYBOX_MODE = 5;
  11331. Texture.CLAMP_ADDRESSMODE = 0;
  11332. Texture.WRAP_ADDRESSMODE = 1;
  11333. Texture.MIRROR_ADDRESSMODE = 2;
  11334. return Texture;
  11335. })(BABYLON.BaseTexture);
  11336. BABYLON.Texture = Texture;
  11337. })(BABYLON || (BABYLON = {}));
  11338. //# sourceMappingURL=babylon.texture.js.map
  11339. var BABYLON;
  11340. (function (BABYLON) {
  11341. var CubeTexture = (function (_super) {
  11342. __extends(CubeTexture, _super);
  11343. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11344. _super.call(this, scene);
  11345. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11346. this.name = rootUrl;
  11347. this.url = rootUrl;
  11348. this._noMipmap = noMipmap;
  11349. this.hasAlpha = false;
  11350. this._texture = this._getFromCache(rootUrl, noMipmap);
  11351. if (!extensions) {
  11352. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11353. }
  11354. this._extensions = extensions;
  11355. if (!this._texture) {
  11356. if (!scene.useDelayedTextureLoading) {
  11357. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11358. } else {
  11359. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11360. }
  11361. }
  11362. this.isCube = true;
  11363. this._textureMatrix = BABYLON.Matrix.Identity();
  11364. }
  11365. CubeTexture.prototype.clone = function () {
  11366. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11367. // Base texture
  11368. newTexture.level = this.level;
  11369. newTexture.wrapU = this.wrapU;
  11370. newTexture.wrapV = this.wrapV;
  11371. newTexture.coordinatesIndex = this.coordinatesIndex;
  11372. newTexture.coordinatesMode = this.coordinatesMode;
  11373. return newTexture;
  11374. };
  11375. // Methods
  11376. CubeTexture.prototype.delayLoad = function () {
  11377. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11378. return;
  11379. }
  11380. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11381. this._texture = this._getFromCache(this.url, this._noMipmap);
  11382. if (!this._texture) {
  11383. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11384. }
  11385. };
  11386. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11387. return this._textureMatrix;
  11388. };
  11389. return CubeTexture;
  11390. })(BABYLON.BaseTexture);
  11391. BABYLON.CubeTexture = CubeTexture;
  11392. })(BABYLON || (BABYLON = {}));
  11393. //# sourceMappingURL=babylon.cubeTexture.js.map
  11394. var BABYLON;
  11395. (function (BABYLON) {
  11396. var RenderTargetTexture = (function (_super) {
  11397. __extends(RenderTargetTexture, _super);
  11398. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11399. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  11400. if (typeof type === "undefined") { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11401. _super.call(this, null, scene, !generateMipMaps);
  11402. this.renderList = new Array();
  11403. this.renderParticles = true;
  11404. this.renderSprites = false;
  11405. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11406. this._currentRefreshId = -1;
  11407. this._refreshRate = 1;
  11408. this.name = name;
  11409. this.isRenderTarget = true;
  11410. this._size = size;
  11411. this._generateMipMaps = generateMipMaps;
  11412. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11413. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11414. // Rendering groups
  11415. this._renderingManager = new BABYLON.RenderingManager(scene);
  11416. }
  11417. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11418. this._currentRefreshId = -1;
  11419. };
  11420. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11421. get: function () {
  11422. return this._refreshRate;
  11423. },
  11424. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11425. set: function (value) {
  11426. this._refreshRate = value;
  11427. this.resetRefreshCounter();
  11428. },
  11429. enumerable: true,
  11430. configurable: true
  11431. });
  11432. RenderTargetTexture.prototype._shouldRender = function () {
  11433. if (this._currentRefreshId === -1) {
  11434. this._currentRefreshId = 1;
  11435. return true;
  11436. }
  11437. if (this.refreshRate == this._currentRefreshId) {
  11438. this._currentRefreshId = 1;
  11439. return true;
  11440. }
  11441. this._currentRefreshId++;
  11442. return false;
  11443. };
  11444. RenderTargetTexture.prototype.isReady = function () {
  11445. if (!this.getScene().renderTargetsEnabled) {
  11446. return false;
  11447. }
  11448. return _super.prototype.isReady.call(this);
  11449. };
  11450. RenderTargetTexture.prototype.getRenderSize = function () {
  11451. return this._size;
  11452. };
  11453. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11454. get: function () {
  11455. return true;
  11456. },
  11457. enumerable: true,
  11458. configurable: true
  11459. });
  11460. RenderTargetTexture.prototype.scale = function (ratio) {
  11461. var newSize = this._size * ratio;
  11462. this.resize(newSize, this._generateMipMaps);
  11463. };
  11464. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11465. this.releaseInternalTexture();
  11466. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11467. };
  11468. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11469. var scene = this.getScene();
  11470. var engine = scene.getEngine();
  11471. if (this._waitingRenderList) {
  11472. this.renderList = [];
  11473. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11474. var id = this._waitingRenderList[index];
  11475. this.renderList.push(scene.getMeshByID(id));
  11476. }
  11477. delete this._waitingRenderList;
  11478. }
  11479. if (!this.renderList) {
  11480. return;
  11481. }
  11482. // Bind
  11483. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11484. engine.bindFramebuffer(this._texture);
  11485. }
  11486. // Clear
  11487. engine.clear(scene.clearColor, true, true);
  11488. this._renderingManager.reset();
  11489. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11490. var mesh = this.renderList[meshIndex];
  11491. if (mesh) {
  11492. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11493. // Reset _currentRefreshId
  11494. this.resetRefreshCounter();
  11495. continue;
  11496. }
  11497. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11498. mesh._activate(scene.getRenderId());
  11499. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11500. var subMesh = mesh.subMeshes[subIndex];
  11501. scene._activeVertices += subMesh.indexCount;
  11502. this._renderingManager.dispatch(subMesh);
  11503. }
  11504. }
  11505. }
  11506. }
  11507. if (!this._doNotChangeAspectRatio) {
  11508. scene.updateTransformMatrix(true);
  11509. }
  11510. if (this.onBeforeRender) {
  11511. this.onBeforeRender();
  11512. }
  11513. // Render
  11514. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11515. if (useCameraPostProcess) {
  11516. scene.postProcessManager._finalizeFrame(false, this._texture);
  11517. }
  11518. if (this.onAfterRender) {
  11519. this.onAfterRender();
  11520. }
  11521. // Unbind
  11522. engine.unBindFramebuffer(this._texture);
  11523. if (!this._doNotChangeAspectRatio) {
  11524. scene.updateTransformMatrix(true);
  11525. }
  11526. };
  11527. RenderTargetTexture.prototype.clone = function () {
  11528. var textureSize = this.getSize();
  11529. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11530. // Base texture
  11531. newTexture.hasAlpha = this.hasAlpha;
  11532. newTexture.level = this.level;
  11533. // RenderTarget Texture
  11534. newTexture.coordinatesMode = this.coordinatesMode;
  11535. newTexture.renderList = this.renderList.slice(0);
  11536. return newTexture;
  11537. };
  11538. return RenderTargetTexture;
  11539. })(BABYLON.Texture);
  11540. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11541. })(BABYLON || (BABYLON = {}));
  11542. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11543. var BABYLON;
  11544. (function (BABYLON) {
  11545. var ProceduralTexture = (function (_super) {
  11546. __extends(ProceduralTexture, _super);
  11547. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11548. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11549. _super.call(this, null, scene, !generateMipMaps);
  11550. this._currentRefreshId = -1;
  11551. this._refreshRate = 1;
  11552. this._vertexDeclaration = [2];
  11553. this._vertexStrideSize = 2 * 4;
  11554. this._uniforms = new Array();
  11555. this._samplers = new Array();
  11556. this._textures = new Array();
  11557. this._floats = new Array();
  11558. this._floatsArrays = {};
  11559. this._colors3 = new Array();
  11560. this._colors4 = new Array();
  11561. this._vectors2 = new Array();
  11562. this._vectors3 = new Array();
  11563. this._matrices = new Array();
  11564. this._fallbackTextureUsed = false;
  11565. scene._proceduralTextures.push(this);
  11566. this.name = name;
  11567. this.isRenderTarget = true;
  11568. this._size = size;
  11569. this._generateMipMaps = generateMipMaps;
  11570. this.setFragment(fragment);
  11571. this._fallbackTexture = fallbackTexture;
  11572. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11573. // VBO
  11574. var vertices = [];
  11575. vertices.push(1, 1);
  11576. vertices.push(-1, 1);
  11577. vertices.push(-1, -1);
  11578. vertices.push(1, -1);
  11579. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11580. // Indices
  11581. var indices = [];
  11582. indices.push(0);
  11583. indices.push(1);
  11584. indices.push(2);
  11585. indices.push(0);
  11586. indices.push(2);
  11587. indices.push(3);
  11588. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11589. }
  11590. ProceduralTexture.prototype.reset = function () {
  11591. if (this._effect === undefined) {
  11592. return;
  11593. }
  11594. var engine = this.getScene().getEngine();
  11595. engine._releaseEffect(this._effect);
  11596. };
  11597. ProceduralTexture.prototype.isReady = function () {
  11598. var _this = this;
  11599. var engine = this.getScene().getEngine();
  11600. var shaders;
  11601. if (!this._fragment) {
  11602. return false;
  11603. }
  11604. if (this._fallbackTextureUsed) {
  11605. return true;
  11606. }
  11607. if (this._fragment.fragmentElement !== undefined) {
  11608. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11609. } else {
  11610. shaders = { vertex: "procedural", fragment: this._fragment };
  11611. }
  11612. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11613. _this.releaseInternalTexture();
  11614. if (_this._fallbackTexture) {
  11615. _this._texture = _this._fallbackTexture._texture;
  11616. _this._texture.references++;
  11617. }
  11618. _this._fallbackTextureUsed = true;
  11619. });
  11620. return this._effect.isReady();
  11621. };
  11622. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11623. this._currentRefreshId = -1;
  11624. };
  11625. ProceduralTexture.prototype.setFragment = function (fragment) {
  11626. this._fragment = fragment;
  11627. };
  11628. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11629. get: function () {
  11630. return this._refreshRate;
  11631. },
  11632. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11633. set: function (value) {
  11634. this._refreshRate = value;
  11635. this.resetRefreshCounter();
  11636. },
  11637. enumerable: true,
  11638. configurable: true
  11639. });
  11640. ProceduralTexture.prototype._shouldRender = function () {
  11641. if (!this.isReady() || !this._texture) {
  11642. return false;
  11643. }
  11644. if (this._fallbackTextureUsed) {
  11645. return false;
  11646. }
  11647. if (this._currentRefreshId === -1) {
  11648. this._currentRefreshId = 1;
  11649. return true;
  11650. }
  11651. if (this.refreshRate === this._currentRefreshId) {
  11652. this._currentRefreshId = 1;
  11653. return true;
  11654. }
  11655. this._currentRefreshId++;
  11656. return false;
  11657. };
  11658. ProceduralTexture.prototype.getRenderSize = function () {
  11659. return this._size;
  11660. };
  11661. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11662. if (this._fallbackTextureUsed) {
  11663. return;
  11664. }
  11665. this.releaseInternalTexture();
  11666. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11667. };
  11668. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11669. if (this._uniforms.indexOf(uniformName) === -1) {
  11670. this._uniforms.push(uniformName);
  11671. }
  11672. };
  11673. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11674. if (this._samplers.indexOf(name) === -1) {
  11675. this._samplers.push(name);
  11676. }
  11677. this._textures[name] = texture;
  11678. return this;
  11679. };
  11680. ProceduralTexture.prototype.setFloat = function (name, value) {
  11681. this._checkUniform(name);
  11682. this._floats[name] = value;
  11683. return this;
  11684. };
  11685. ProceduralTexture.prototype.setFloats = function (name, value) {
  11686. this._checkUniform(name);
  11687. this._floatsArrays[name] = value;
  11688. return this;
  11689. };
  11690. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11691. this._checkUniform(name);
  11692. this._colors3[name] = value;
  11693. return this;
  11694. };
  11695. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11696. this._checkUniform(name);
  11697. this._colors4[name] = value;
  11698. return this;
  11699. };
  11700. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11701. this._checkUniform(name);
  11702. this._vectors2[name] = value;
  11703. return this;
  11704. };
  11705. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11706. this._checkUniform(name);
  11707. this._vectors3[name] = value;
  11708. return this;
  11709. };
  11710. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11711. this._checkUniform(name);
  11712. this._matrices[name] = value;
  11713. return this;
  11714. };
  11715. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11716. var scene = this.getScene();
  11717. var engine = scene.getEngine();
  11718. engine.bindFramebuffer(this._texture);
  11719. // Clear
  11720. engine.clear(scene.clearColor, true, true);
  11721. // Render
  11722. engine.enableEffect(this._effect);
  11723. engine.setState(false);
  11724. for (var name in this._textures) {
  11725. this._effect.setTexture(name, this._textures[name]);
  11726. }
  11727. for (name in this._floats) {
  11728. this._effect.setFloat(name, this._floats[name]);
  11729. }
  11730. for (name in this._floatsArrays) {
  11731. this._effect.setArray(name, this._floatsArrays[name]);
  11732. }
  11733. for (name in this._colors3) {
  11734. this._effect.setColor3(name, this._colors3[name]);
  11735. }
  11736. for (name in this._colors4) {
  11737. var color = this._colors4[name];
  11738. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11739. }
  11740. for (name in this._vectors2) {
  11741. this._effect.setVector2(name, this._vectors2[name]);
  11742. }
  11743. for (name in this._vectors3) {
  11744. this._effect.setVector3(name, this._vectors3[name]);
  11745. }
  11746. for (name in this._matrices) {
  11747. this._effect.setMatrix(name, this._matrices[name]);
  11748. }
  11749. // VBOs
  11750. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11751. // Draw order
  11752. engine.draw(true, 0, 6);
  11753. // Unbind
  11754. engine.unBindFramebuffer(this._texture);
  11755. };
  11756. ProceduralTexture.prototype.clone = function () {
  11757. var textureSize = this.getSize();
  11758. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11759. // Base texture
  11760. newTexture.hasAlpha = this.hasAlpha;
  11761. newTexture.level = this.level;
  11762. // RenderTarget Texture
  11763. newTexture.coordinatesMode = this.coordinatesMode;
  11764. return newTexture;
  11765. };
  11766. ProceduralTexture.prototype.dispose = function () {
  11767. var index = this.getScene()._proceduralTextures.indexOf(this);
  11768. if (index >= 0) {
  11769. this.getScene()._proceduralTextures.splice(index, 1);
  11770. }
  11771. _super.prototype.dispose.call(this);
  11772. };
  11773. return ProceduralTexture;
  11774. })(BABYLON.Texture);
  11775. BABYLON.ProceduralTexture = ProceduralTexture;
  11776. })(BABYLON || (BABYLON = {}));
  11777. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11778. var BABYLON;
  11779. (function (BABYLON) {
  11780. var WoodProceduralTexture = (function (_super) {
  11781. __extends(WoodProceduralTexture, _super);
  11782. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11783. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11784. this._ampScale = 100.0;
  11785. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11786. this.updateShaderUniforms();
  11787. this.refreshRate = 0;
  11788. }
  11789. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11790. this.setFloat("ampScale", this._ampScale);
  11791. this.setColor3("woodColor", this._woodColor);
  11792. };
  11793. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11794. get: function () {
  11795. return this._ampScale;
  11796. },
  11797. set: function (value) {
  11798. this._ampScale = value;
  11799. this.updateShaderUniforms();
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11805. get: function () {
  11806. return this._woodColor;
  11807. },
  11808. set: function (value) {
  11809. this._woodColor = value;
  11810. this.updateShaderUniforms();
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. return WoodProceduralTexture;
  11816. })(BABYLON.ProceduralTexture);
  11817. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11818. var FireProceduralTexture = (function (_super) {
  11819. __extends(FireProceduralTexture, _super);
  11820. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11821. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11822. this._time = 0.0;
  11823. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11824. this._shift = 1.6;
  11825. this._autoGenerateTime = true;
  11826. this._alphaThreshold = 0.5;
  11827. this._fireColors = FireProceduralTexture.RedFireColors;
  11828. this.updateShaderUniforms();
  11829. this.refreshRate = 1;
  11830. }
  11831. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11832. this.setFloat("time", this._time);
  11833. this.setVector2("speed", this._speed);
  11834. this.setFloat("shift", this._shift);
  11835. this.setColor3("c1", this._fireColors[0]);
  11836. this.setColor3("c2", this._fireColors[1]);
  11837. this.setColor3("c3", this._fireColors[2]);
  11838. this.setColor3("c4", this._fireColors[3]);
  11839. this.setColor3("c5", this._fireColors[4]);
  11840. this.setColor3("c6", this._fireColors[5]);
  11841. this.setFloat("alphaThreshold", this._alphaThreshold);
  11842. };
  11843. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11844. if (this._autoGenerateTime) {
  11845. this._time += this.getScene().getAnimationRatio() * 0.03;
  11846. this.updateShaderUniforms();
  11847. }
  11848. _super.prototype.render.call(this, useCameraPostProcess);
  11849. };
  11850. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11851. get: function () {
  11852. return [
  11853. new BABYLON.Color3(0.5, 0.0, 1.0),
  11854. new BABYLON.Color3(0.9, 0.0, 1.0),
  11855. new BABYLON.Color3(0.2, 0.0, 1.0),
  11856. new BABYLON.Color3(1.0, 0.9, 1.0),
  11857. new BABYLON.Color3(0.1, 0.1, 1.0),
  11858. new BABYLON.Color3(0.9, 0.9, 1.0)
  11859. ];
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11865. get: function () {
  11866. return [
  11867. new BABYLON.Color3(0.5, 1.0, 0.0),
  11868. new BABYLON.Color3(0.5, 1.0, 0.0),
  11869. new BABYLON.Color3(0.3, 0.4, 0.0),
  11870. new BABYLON.Color3(0.5, 1.0, 0.0),
  11871. new BABYLON.Color3(0.2, 0.0, 0.0),
  11872. new BABYLON.Color3(0.5, 1.0, 0.0)
  11873. ];
  11874. },
  11875. enumerable: true,
  11876. configurable: true
  11877. });
  11878. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11879. get: function () {
  11880. return [
  11881. new BABYLON.Color3(0.5, 0.0, 0.1),
  11882. new BABYLON.Color3(0.9, 0.0, 0.0),
  11883. new BABYLON.Color3(0.2, 0.0, 0.0),
  11884. new BABYLON.Color3(1.0, 0.9, 0.0),
  11885. new BABYLON.Color3(0.1, 0.1, 0.1),
  11886. new BABYLON.Color3(0.9, 0.9, 0.9)
  11887. ];
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11893. get: function () {
  11894. return [
  11895. new BABYLON.Color3(0.1, 0.0, 0.5),
  11896. new BABYLON.Color3(0.0, 0.0, 0.5),
  11897. new BABYLON.Color3(0.1, 0.0, 0.2),
  11898. new BABYLON.Color3(0.0, 0.0, 1.0),
  11899. new BABYLON.Color3(0.1, 0.2, 0.3),
  11900. new BABYLON.Color3(0.0, 0.2, 0.9)
  11901. ];
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11907. get: function () {
  11908. return this._fireColors;
  11909. },
  11910. set: function (value) {
  11911. this._fireColors = value;
  11912. this.updateShaderUniforms();
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11918. get: function () {
  11919. return this._time;
  11920. },
  11921. set: function (value) {
  11922. this._time = value;
  11923. this.updateShaderUniforms();
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11929. get: function () {
  11930. return this._speed;
  11931. },
  11932. set: function (value) {
  11933. this._speed = value;
  11934. this.updateShaderUniforms();
  11935. },
  11936. enumerable: true,
  11937. configurable: true
  11938. });
  11939. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11940. get: function () {
  11941. return this._shift;
  11942. },
  11943. set: function (value) {
  11944. this._shift = value;
  11945. this.updateShaderUniforms();
  11946. },
  11947. enumerable: true,
  11948. configurable: true
  11949. });
  11950. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11951. get: function () {
  11952. return this._alphaThreshold;
  11953. },
  11954. set: function (value) {
  11955. this._alphaThreshold = value;
  11956. this.updateShaderUniforms();
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. return FireProceduralTexture;
  11962. })(BABYLON.ProceduralTexture);
  11963. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11964. var CloudProceduralTexture = (function (_super) {
  11965. __extends(CloudProceduralTexture, _super);
  11966. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11967. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11968. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11969. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11970. this.updateShaderUniforms();
  11971. this.refreshRate = 0;
  11972. }
  11973. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11974. this.setColor3("skyColor", this._skyColor);
  11975. this.setColor3("cloudColor", this._cloudColor);
  11976. };
  11977. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11978. get: function () {
  11979. return this._skyColor;
  11980. },
  11981. set: function (value) {
  11982. this._skyColor = value;
  11983. this.updateShaderUniforms();
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11989. get: function () {
  11990. return this._cloudColor;
  11991. },
  11992. set: function (value) {
  11993. this._cloudColor = value;
  11994. this.updateShaderUniforms();
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. return CloudProceduralTexture;
  12000. })(BABYLON.ProceduralTexture);
  12001. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12002. var GrassProceduralTexture = (function (_super) {
  12003. __extends(GrassProceduralTexture, _super);
  12004. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12005. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12006. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12007. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12008. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12009. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12010. this._grassColors = [
  12011. new BABYLON.Color3(0.29, 0.38, 0.02),
  12012. new BABYLON.Color3(0.36, 0.49, 0.09),
  12013. new BABYLON.Color3(0.51, 0.6, 0.28)
  12014. ];
  12015. this.updateShaderUniforms();
  12016. this.refreshRate = 0;
  12017. }
  12018. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12019. this.setColor3("herb1Color", this._grassColors[0]);
  12020. this.setColor3("herb2Color", this._grassColors[1]);
  12021. this.setColor3("herb3Color", this._grassColors[2]);
  12022. this.setColor3("groundColor", this._groundColor);
  12023. };
  12024. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12025. get: function () {
  12026. return this._grassColors;
  12027. },
  12028. set: function (value) {
  12029. this._grassColors = value;
  12030. this.updateShaderUniforms();
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12036. get: function () {
  12037. return this._groundColor;
  12038. },
  12039. set: function (value) {
  12040. this.groundColor = value;
  12041. this.updateShaderUniforms();
  12042. },
  12043. enumerable: true,
  12044. configurable: true
  12045. });
  12046. return GrassProceduralTexture;
  12047. })(BABYLON.ProceduralTexture);
  12048. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12049. var RoadProceduralTexture = (function (_super) {
  12050. __extends(RoadProceduralTexture, _super);
  12051. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12052. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12053. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12054. this.updateShaderUniforms();
  12055. this.refreshRate = 0;
  12056. }
  12057. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12058. this.setColor3("roadColor", this._roadColor);
  12059. };
  12060. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12061. get: function () {
  12062. return this._roadColor;
  12063. },
  12064. set: function (value) {
  12065. this._roadColor = value;
  12066. this.updateShaderUniforms();
  12067. },
  12068. enumerable: true,
  12069. configurable: true
  12070. });
  12071. return RoadProceduralTexture;
  12072. })(BABYLON.ProceduralTexture);
  12073. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12074. var BrickProceduralTexture = (function (_super) {
  12075. __extends(BrickProceduralTexture, _super);
  12076. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12077. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12078. this._numberOfBricksHeight = 15;
  12079. this._numberOfBricksWidth = 5;
  12080. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12081. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12082. this.updateShaderUniforms();
  12083. this.refreshRate = 0;
  12084. }
  12085. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12086. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12087. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12088. this.setColor3("brickColor", this._brickColor);
  12089. this.setColor3("jointColor", this._jointColor);
  12090. };
  12091. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12092. get: function () {
  12093. return this._numberOfBricksHeight;
  12094. },
  12095. enumerable: true,
  12096. configurable: true
  12097. });
  12098. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12099. set: function (value) {
  12100. this._numberOfBricksHeight = value;
  12101. this.updateShaderUniforms();
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12107. get: function () {
  12108. return this._numberOfBricksWidth;
  12109. },
  12110. set: function (value) {
  12111. this._numberOfBricksHeight = value;
  12112. this.updateShaderUniforms();
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12118. get: function () {
  12119. return this._jointColor;
  12120. },
  12121. set: function (value) {
  12122. this._jointColor = value;
  12123. this.updateShaderUniforms();
  12124. },
  12125. enumerable: true,
  12126. configurable: true
  12127. });
  12128. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12129. get: function () {
  12130. return this._brickColor;
  12131. },
  12132. set: function (value) {
  12133. this._brickColor = value;
  12134. this.updateShaderUniforms();
  12135. },
  12136. enumerable: true,
  12137. configurable: true
  12138. });
  12139. return BrickProceduralTexture;
  12140. })(BABYLON.ProceduralTexture);
  12141. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12142. var MarbleProceduralTexture = (function (_super) {
  12143. __extends(MarbleProceduralTexture, _super);
  12144. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12145. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12146. this._numberOfTilesHeight = 3;
  12147. this._numberOfTilesWidth = 3;
  12148. this._amplitude = 9.0;
  12149. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12150. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12151. this.updateShaderUniforms();
  12152. this.refreshRate = 0;
  12153. }
  12154. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12155. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12156. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12157. this.setFloat("amplitude", this._amplitude);
  12158. this.setColor3("marbleColor", this._marbleColor);
  12159. this.setColor3("jointColor", this._jointColor);
  12160. };
  12161. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12162. get: function () {
  12163. return this._numberOfTilesHeight;
  12164. },
  12165. set: function (value) {
  12166. this._numberOfTilesHeight = value;
  12167. this.updateShaderUniforms();
  12168. },
  12169. enumerable: true,
  12170. configurable: true
  12171. });
  12172. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12173. get: function () {
  12174. return this._numberOfTilesWidth;
  12175. },
  12176. set: function (value) {
  12177. this._numberOfTilesWidth = value;
  12178. this.updateShaderUniforms();
  12179. },
  12180. enumerable: true,
  12181. configurable: true
  12182. });
  12183. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12184. get: function () {
  12185. return this._jointColor;
  12186. },
  12187. set: function (value) {
  12188. this._jointColor = value;
  12189. this.updateShaderUniforms();
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12195. get: function () {
  12196. return this._marbleColor;
  12197. },
  12198. set: function (value) {
  12199. this._marbleColor = value;
  12200. this.updateShaderUniforms();
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. return MarbleProceduralTexture;
  12206. })(BABYLON.ProceduralTexture);
  12207. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12208. })(BABYLON || (BABYLON = {}));
  12209. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12210. var BABYLON;
  12211. (function (BABYLON) {
  12212. var CustomProceduralTexture = (function (_super) {
  12213. __extends(CustomProceduralTexture, _super);
  12214. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12215. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12216. this._animate = true;
  12217. this._time = 0;
  12218. this._texturePath = texturePath;
  12219. //Try to load json
  12220. this.loadJson(texturePath);
  12221. this.refreshRate = 1;
  12222. }
  12223. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12224. var _this = this;
  12225. var that = this;
  12226. function noConfigFile() {
  12227. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12228. try {
  12229. that.setFragment(that._texturePath);
  12230. } catch (ex) {
  12231. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12232. }
  12233. }
  12234. var configFileUrl = jsonUrl + "/config.json";
  12235. var xhr = new XMLHttpRequest();
  12236. xhr.open("GET", configFileUrl, true);
  12237. xhr.addEventListener("load", function () {
  12238. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12239. try {
  12240. _this._config = JSON.parse(xhr.response);
  12241. _this.updateShaderUniforms();
  12242. _this.updateTextures();
  12243. _this.setFragment(_this._texturePath + "/custom");
  12244. _this._animate = _this._config.animate;
  12245. _this.refreshRate = _this._config.refreshrate;
  12246. } catch (ex) {
  12247. noConfigFile();
  12248. }
  12249. } else {
  12250. noConfigFile();
  12251. }
  12252. }, false);
  12253. xhr.addEventListener("error", function (event) {
  12254. noConfigFile();
  12255. }, false);
  12256. try {
  12257. xhr.send();
  12258. } catch (ex) {
  12259. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12260. }
  12261. };
  12262. CustomProceduralTexture.prototype.isReady = function () {
  12263. if (!_super.prototype.isReady.call(this)) {
  12264. return false;
  12265. }
  12266. for (var name in this._textures) {
  12267. var texture = this._textures[name];
  12268. if (!texture.isReady()) {
  12269. return false;
  12270. }
  12271. }
  12272. return true;
  12273. };
  12274. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12275. if (this._animate) {
  12276. this._time += this.getScene().getAnimationRatio() * 0.03;
  12277. this.updateShaderUniforms();
  12278. }
  12279. _super.prototype.render.call(this, useCameraPostProcess);
  12280. };
  12281. CustomProceduralTexture.prototype.updateTextures = function () {
  12282. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12283. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12284. }
  12285. };
  12286. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12287. if (this._config) {
  12288. for (var j = 0; j < this._config.uniforms.length; j++) {
  12289. var uniform = this._config.uniforms[j];
  12290. switch (uniform.type) {
  12291. case "float":
  12292. this.setFloat(uniform.name, uniform.value);
  12293. break;
  12294. case "color3":
  12295. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12296. break;
  12297. case "color4":
  12298. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12299. break;
  12300. case "vector2":
  12301. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12302. break;
  12303. case "vector3":
  12304. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12305. break;
  12306. }
  12307. }
  12308. }
  12309. this.setFloat("time", this._time);
  12310. };
  12311. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12312. get: function () {
  12313. return this._animate;
  12314. },
  12315. set: function (value) {
  12316. this._animate = value;
  12317. },
  12318. enumerable: true,
  12319. configurable: true
  12320. });
  12321. return CustomProceduralTexture;
  12322. })(BABYLON.ProceduralTexture);
  12323. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12324. })(BABYLON || (BABYLON = {}));
  12325. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12326. var BABYLON;
  12327. (function (BABYLON) {
  12328. var MirrorTexture = (function (_super) {
  12329. __extends(MirrorTexture, _super);
  12330. function MirrorTexture(name, size, scene, generateMipMaps) {
  12331. var _this = this;
  12332. _super.call(this, name, size, scene, generateMipMaps, true);
  12333. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12334. this._transformMatrix = BABYLON.Matrix.Zero();
  12335. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12336. this.onBeforeRender = function () {
  12337. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12338. _this._savedViewMatrix = scene.getViewMatrix();
  12339. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12340. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12341. scene.clipPlane = _this.mirrorPlane;
  12342. scene.getEngine().cullBackFaces = false;
  12343. };
  12344. this.onAfterRender = function () {
  12345. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12346. scene.getEngine().cullBackFaces = true;
  12347. delete scene.clipPlane;
  12348. };
  12349. }
  12350. MirrorTexture.prototype.clone = function () {
  12351. var textureSize = this.getSize();
  12352. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12353. // Base texture
  12354. newTexture.hasAlpha = this.hasAlpha;
  12355. newTexture.level = this.level;
  12356. // Mirror Texture
  12357. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12358. newTexture.renderList = this.renderList.slice(0);
  12359. return newTexture;
  12360. };
  12361. return MirrorTexture;
  12362. })(BABYLON.RenderTargetTexture);
  12363. BABYLON.MirrorTexture = MirrorTexture;
  12364. })(BABYLON || (BABYLON = {}));
  12365. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12366. var BABYLON;
  12367. (function (BABYLON) {
  12368. var DynamicTexture = (function (_super) {
  12369. __extends(DynamicTexture, _super);
  12370. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12371. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12372. _super.call(this, null, scene, !generateMipMaps);
  12373. this.name = name;
  12374. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12375. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12376. this._generateMipMaps = generateMipMaps;
  12377. if (options.getContext) {
  12378. this._canvas = options;
  12379. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12380. } else {
  12381. this._canvas = document.createElement("canvas");
  12382. if (options.width) {
  12383. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12384. } else {
  12385. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12386. }
  12387. }
  12388. var textureSize = this.getSize();
  12389. this._canvas.width = textureSize.width;
  12390. this._canvas.height = textureSize.height;
  12391. this._context = this._canvas.getContext("2d");
  12392. }
  12393. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12394. get: function () {
  12395. return true;
  12396. },
  12397. enumerable: true,
  12398. configurable: true
  12399. });
  12400. DynamicTexture.prototype.scale = function (ratio) {
  12401. var textureSize = this.getSize();
  12402. textureSize.width *= ratio;
  12403. textureSize.height *= ratio;
  12404. this._canvas.width = textureSize.width;
  12405. this._canvas.height = textureSize.height;
  12406. this.releaseInternalTexture();
  12407. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12408. };
  12409. DynamicTexture.prototype.getContext = function () {
  12410. return this._context;
  12411. };
  12412. DynamicTexture.prototype.clear = function () {
  12413. var size = this.getSize();
  12414. this._context.fillRect(0, 0, size.width, size.height);
  12415. };
  12416. DynamicTexture.prototype.update = function (invertY) {
  12417. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12418. };
  12419. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12420. if (typeof update === "undefined") { update = true; }
  12421. var size = this.getSize();
  12422. if (clearColor) {
  12423. this._context.fillStyle = clearColor;
  12424. this._context.fillRect(0, 0, size.width, size.height);
  12425. }
  12426. this._context.font = font;
  12427. if (x === null) {
  12428. var textSize = this._context.measureText(text);
  12429. x = (size.width - textSize.width) / 2;
  12430. }
  12431. this._context.fillStyle = color;
  12432. this._context.fillText(text, x, y);
  12433. if (update) {
  12434. this.update(invertY);
  12435. }
  12436. };
  12437. DynamicTexture.prototype.clone = function () {
  12438. var textureSize = this.getSize();
  12439. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12440. // Base texture
  12441. newTexture.hasAlpha = this.hasAlpha;
  12442. newTexture.level = this.level;
  12443. // Dynamic Texture
  12444. newTexture.wrapU = this.wrapU;
  12445. newTexture.wrapV = this.wrapV;
  12446. return newTexture;
  12447. };
  12448. return DynamicTexture;
  12449. })(BABYLON.Texture);
  12450. BABYLON.DynamicTexture = DynamicTexture;
  12451. })(BABYLON || (BABYLON = {}));
  12452. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12453. var BABYLON;
  12454. (function (BABYLON) {
  12455. var VideoTexture = (function (_super) {
  12456. __extends(VideoTexture, _super);
  12457. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12458. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12459. var _this = this;
  12460. _super.call(this, null, scene, !generateMipMaps, invertY);
  12461. this._autoLaunch = true;
  12462. this.name = name;
  12463. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12464. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12465. var requiredWidth = size.width || size;
  12466. var requiredHeight = size.height || size;
  12467. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12468. var textureSize = this.getSize();
  12469. this.video = document.createElement("video");
  12470. this.video.width = textureSize.width;
  12471. this.video.height = textureSize.height;
  12472. this.video.autoplay = false;
  12473. this.video.loop = true;
  12474. this.video.addEventListener("canplaythrough", function () {
  12475. if (_this._texture) {
  12476. _this._texture.isReady = true;
  12477. }
  12478. });
  12479. urls.forEach(function (url) {
  12480. var source = document.createElement("source");
  12481. source.src = url;
  12482. _this.video.appendChild(source);
  12483. });
  12484. this._lastUpdate = BABYLON.Tools.Now;
  12485. }
  12486. VideoTexture.prototype.update = function () {
  12487. if (this._autoLaunch) {
  12488. this._autoLaunch = false;
  12489. this.video.play();
  12490. }
  12491. var now = BABYLON.Tools.Now;
  12492. if (now - this._lastUpdate < 15) {
  12493. return false;
  12494. }
  12495. this._lastUpdate = now;
  12496. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12497. return true;
  12498. };
  12499. return VideoTexture;
  12500. })(BABYLON.Texture);
  12501. BABYLON.VideoTexture = VideoTexture;
  12502. })(BABYLON || (BABYLON = {}));
  12503. //# sourceMappingURL=babylon.videoTexture.js.map
  12504. var BABYLON;
  12505. (function (BABYLON) {
  12506. var EffectFallbacks = (function () {
  12507. function EffectFallbacks() {
  12508. this._defines = {};
  12509. this._currentRank = 32;
  12510. this._maxRank = -1;
  12511. }
  12512. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12513. if (!this._defines[rank]) {
  12514. if (rank < this._currentRank) {
  12515. this._currentRank = rank;
  12516. }
  12517. if (rank > this._maxRank) {
  12518. this._maxRank = rank;
  12519. }
  12520. this._defines[rank] = new Array();
  12521. }
  12522. this._defines[rank].push(define);
  12523. };
  12524. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12525. get: function () {
  12526. return this._currentRank <= this._maxRank;
  12527. },
  12528. enumerable: true,
  12529. configurable: true
  12530. });
  12531. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12532. var currentFallbacks = this._defines[this._currentRank];
  12533. for (var index = 0; index < currentFallbacks.length; index++) {
  12534. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12535. }
  12536. this._currentRank++;
  12537. return currentDefines;
  12538. };
  12539. return EffectFallbacks;
  12540. })();
  12541. BABYLON.EffectFallbacks = EffectFallbacks;
  12542. var Effect = (function () {
  12543. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12544. var _this = this;
  12545. this._isReady = false;
  12546. this._compilationError = "";
  12547. this._valueCache = [];
  12548. this._engine = engine;
  12549. this.name = baseName;
  12550. this.defines = defines;
  12551. this._uniformsNames = uniformsNames.concat(samplers);
  12552. this._samplers = samplers;
  12553. this._attributesNames = attributesNames;
  12554. this.onError = onError;
  12555. this.onCompiled = onCompiled;
  12556. var vertexSource;
  12557. var fragmentSource;
  12558. if (baseName.vertexElement) {
  12559. vertexSource = document.getElementById(baseName.vertexElement);
  12560. if (!vertexSource) {
  12561. vertexSource = baseName.vertexElement;
  12562. }
  12563. } else {
  12564. vertexSource = baseName.vertex || baseName;
  12565. }
  12566. if (baseName.fragmentElement) {
  12567. fragmentSource = document.getElementById(baseName.fragmentElement);
  12568. if (!fragmentSource) {
  12569. fragmentSource = baseName.fragmentElement;
  12570. }
  12571. } else {
  12572. fragmentSource = baseName.fragment || baseName;
  12573. }
  12574. this._loadVertexShader(vertexSource, function (vertexCode) {
  12575. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12576. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12577. });
  12578. });
  12579. }
  12580. // Properties
  12581. Effect.prototype.isReady = function () {
  12582. return this._isReady;
  12583. };
  12584. Effect.prototype.getProgram = function () {
  12585. return this._program;
  12586. };
  12587. Effect.prototype.getAttributesNames = function () {
  12588. return this._attributesNames;
  12589. };
  12590. Effect.prototype.getAttributeLocation = function (index) {
  12591. return this._attributes[index];
  12592. };
  12593. Effect.prototype.getAttributeLocationByName = function (name) {
  12594. var index = this._attributesNames.indexOf(name);
  12595. return this._attributes[index];
  12596. };
  12597. Effect.prototype.getAttributesCount = function () {
  12598. return this._attributes.length;
  12599. };
  12600. Effect.prototype.getUniformIndex = function (uniformName) {
  12601. return this._uniformsNames.indexOf(uniformName);
  12602. };
  12603. Effect.prototype.getUniform = function (uniformName) {
  12604. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12605. };
  12606. Effect.prototype.getSamplers = function () {
  12607. return this._samplers;
  12608. };
  12609. Effect.prototype.getCompilationError = function () {
  12610. return this._compilationError;
  12611. };
  12612. // Methods
  12613. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12614. // DOM element ?
  12615. if (vertex instanceof HTMLElement) {
  12616. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12617. callback(vertexCode);
  12618. return;
  12619. }
  12620. // Is in local store ?
  12621. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12622. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12623. return;
  12624. }
  12625. var vertexShaderUrl;
  12626. if (vertex[0] === ".") {
  12627. vertexShaderUrl = vertex;
  12628. } else {
  12629. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12630. }
  12631. // Vertex shader
  12632. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12633. };
  12634. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12635. // DOM element ?
  12636. if (fragment instanceof HTMLElement) {
  12637. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12638. callback(fragmentCode);
  12639. return;
  12640. }
  12641. // Is in local store ?
  12642. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12643. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12644. return;
  12645. }
  12646. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12647. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12648. return;
  12649. }
  12650. var fragmentShaderUrl;
  12651. if (fragment[0] === ".") {
  12652. fragmentShaderUrl = fragment;
  12653. } else {
  12654. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12655. }
  12656. // Fragment shader
  12657. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12658. };
  12659. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12660. try {
  12661. var engine = this._engine;
  12662. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12663. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12664. this._attributes = engine.getAttributes(this._program, attributesNames);
  12665. for (var index = 0; index < this._samplers.length; index++) {
  12666. var sampler = this.getUniform(this._samplers[index]);
  12667. if (sampler == null) {
  12668. this._samplers.splice(index, 1);
  12669. index--;
  12670. }
  12671. }
  12672. engine.bindSamplers(this);
  12673. this._isReady = true;
  12674. if (this.onCompiled) {
  12675. this.onCompiled(this);
  12676. }
  12677. } catch (e) {
  12678. // Is it a problem with precision?
  12679. if (e.message.indexOf("highp") !== -1) {
  12680. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12681. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12682. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12683. return;
  12684. }
  12685. // Let's go through fallbacks then
  12686. if (fallbacks && fallbacks.isMoreFallbacks) {
  12687. defines = fallbacks.reduce(defines);
  12688. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12689. } else {
  12690. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12691. BABYLON.Tools.Error("Defines: " + defines);
  12692. BABYLON.Tools.Error("Error: " + e.message);
  12693. this._compilationError = e.message;
  12694. if (this.onError) {
  12695. this.onError(this, this._compilationError);
  12696. }
  12697. }
  12698. }
  12699. };
  12700. Effect.prototype._bindTexture = function (channel, texture) {
  12701. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12702. };
  12703. Effect.prototype.setTexture = function (channel, texture) {
  12704. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12705. };
  12706. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12707. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12708. };
  12709. //public _cacheMatrix(uniformName, matrix) {
  12710. // if (!this._valueCache[uniformName]) {
  12711. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12712. // }
  12713. // for (var index = 0; index < 16; index++) {
  12714. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12715. // }
  12716. //};
  12717. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12718. if (!this._valueCache[uniformName]) {
  12719. this._valueCache[uniformName] = [x, y];
  12720. return;
  12721. }
  12722. this._valueCache[uniformName][0] = x;
  12723. this._valueCache[uniformName][1] = y;
  12724. };
  12725. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12726. if (!this._valueCache[uniformName]) {
  12727. this._valueCache[uniformName] = [x, y, z];
  12728. return;
  12729. }
  12730. this._valueCache[uniformName][0] = x;
  12731. this._valueCache[uniformName][1] = y;
  12732. this._valueCache[uniformName][2] = z;
  12733. };
  12734. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12735. if (!this._valueCache[uniformName]) {
  12736. this._valueCache[uniformName] = [x, y, z, w];
  12737. return;
  12738. }
  12739. this._valueCache[uniformName][0] = x;
  12740. this._valueCache[uniformName][1] = y;
  12741. this._valueCache[uniformName][2] = z;
  12742. this._valueCache[uniformName][3] = w;
  12743. };
  12744. Effect.prototype.setArray = function (uniformName, array) {
  12745. this._engine.setArray(this.getUniform(uniformName), array);
  12746. return this;
  12747. };
  12748. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12749. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12750. return this;
  12751. };
  12752. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12753. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12754. // return;
  12755. //this._cacheMatrix(uniformName, matrix);
  12756. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12757. return this;
  12758. };
  12759. Effect.prototype.setFloat = function (uniformName, value) {
  12760. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12761. return this;
  12762. this._valueCache[uniformName] = value;
  12763. this._engine.setFloat(this.getUniform(uniformName), value);
  12764. return this;
  12765. };
  12766. Effect.prototype.setBool = function (uniformName, bool) {
  12767. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12768. return this;
  12769. this._valueCache[uniformName] = bool;
  12770. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12771. return this;
  12772. };
  12773. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12774. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12775. return this;
  12776. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12777. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12778. return this;
  12779. };
  12780. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12781. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12782. return this;
  12783. this._cacheFloat2(uniformName, x, y);
  12784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12785. return this;
  12786. };
  12787. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12788. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12789. return this;
  12790. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12791. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12792. return this;
  12793. };
  12794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12795. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12796. return this;
  12797. this._cacheFloat3(uniformName, x, y, z);
  12798. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12799. return this;
  12800. };
  12801. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12802. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12803. return this;
  12804. this._cacheFloat4(uniformName, x, y, z, w);
  12805. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12806. return this;
  12807. };
  12808. Effect.prototype.setColor3 = function (uniformName, color3) {
  12809. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12810. return this;
  12811. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12812. this._engine.setColor3(this.getUniform(uniformName), color3);
  12813. return this;
  12814. };
  12815. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12816. 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)
  12817. return this;
  12818. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12819. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12820. return this;
  12821. };
  12822. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  12823. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  12824. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  12825. 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) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return 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) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  12826. 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) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return 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) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  12827. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12828. colorVertexShader:"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  12829. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  12830. 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\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\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 float darkness1;\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 float darkness2;\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 float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\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// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return 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// Reflection\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{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\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{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  12831. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\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\n// Uniforms\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\n// Output\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\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  12832. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  12833. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  12834. 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) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return 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) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  12835. 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(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  12836. 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) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return 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) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  12837. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  12838. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  12839. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\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// Samplers\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// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return 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// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\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{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  12840. 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\n// Attributes\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\n// Uniforms\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\n// Output\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{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  12841. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  12842. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  12843. 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) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return 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{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  12844. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  12845. 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\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  12846. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\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\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  12847. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\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\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  12848. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\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) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  12849. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  12850. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  12851. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n vPosition = position;\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  12852. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  12853. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return 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) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  12854. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  12855. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\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#ifndef VSM\nvarying vec4 vPosition;\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\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  12856. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\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{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  12857. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  12858. 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) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return 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) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  12859. };
  12860. return Effect;
  12861. })();
  12862. BABYLON.Effect = Effect;
  12863. })(BABYLON || (BABYLON = {}));
  12864. //# sourceMappingURL=babylon.effect.js.map
  12865. var BABYLON;
  12866. (function (BABYLON) {
  12867. var Material = (function () {
  12868. function Material(name, scene, doNotAdd) {
  12869. this.name = name;
  12870. this.checkReadyOnEveryCall = true;
  12871. this.checkReadyOnlyOnce = false;
  12872. this.state = "";
  12873. this.alpha = 1.0;
  12874. this.backFaceCulling = true;
  12875. this._wasPreviouslyReady = false;
  12876. this._fillMode = Material.TriangleFillMode;
  12877. this.pointSize = 1.0;
  12878. this.id = name;
  12879. this._scene = scene;
  12880. if (!doNotAdd) {
  12881. scene.materials.push(this);
  12882. }
  12883. }
  12884. Object.defineProperty(Material, "TriangleFillMode", {
  12885. get: function () {
  12886. return Material._TriangleFillMode;
  12887. },
  12888. enumerable: true,
  12889. configurable: true
  12890. });
  12891. Object.defineProperty(Material, "WireFrameFillMode", {
  12892. get: function () {
  12893. return Material._WireFrameFillMode;
  12894. },
  12895. enumerable: true,
  12896. configurable: true
  12897. });
  12898. Object.defineProperty(Material, "PointFillMode", {
  12899. get: function () {
  12900. return Material._PointFillMode;
  12901. },
  12902. enumerable: true,
  12903. configurable: true
  12904. });
  12905. Object.defineProperty(Material.prototype, "wireframe", {
  12906. get: function () {
  12907. return this._fillMode === Material.WireFrameFillMode;
  12908. },
  12909. set: function (value) {
  12910. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12911. },
  12912. enumerable: true,
  12913. configurable: true
  12914. });
  12915. Object.defineProperty(Material.prototype, "pointsCloud", {
  12916. get: function () {
  12917. return this._fillMode === Material.PointFillMode;
  12918. },
  12919. set: function (value) {
  12920. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12921. },
  12922. enumerable: true,
  12923. configurable: true
  12924. });
  12925. Object.defineProperty(Material.prototype, "fillMode", {
  12926. get: function () {
  12927. return this._fillMode;
  12928. },
  12929. set: function (value) {
  12930. this._fillMode = value;
  12931. },
  12932. enumerable: true,
  12933. configurable: true
  12934. });
  12935. Material.prototype.isReady = function (mesh, useInstances) {
  12936. return true;
  12937. };
  12938. Material.prototype.getEffect = function () {
  12939. return this._effect;
  12940. };
  12941. Material.prototype.getScene = function () {
  12942. return this._scene;
  12943. };
  12944. Material.prototype.needAlphaBlending = function () {
  12945. return (this.alpha < 1.0);
  12946. };
  12947. Material.prototype.needAlphaTesting = function () {
  12948. return false;
  12949. };
  12950. Material.prototype.getAlphaTestTexture = function () {
  12951. return null;
  12952. };
  12953. Material.prototype.trackCreation = function (onCompiled, onError) {
  12954. };
  12955. Material.prototype._preBind = function () {
  12956. var engine = this._scene.getEngine();
  12957. engine.enableEffect(this._effect);
  12958. engine.setState(this.backFaceCulling);
  12959. };
  12960. Material.prototype.bind = function (world, mesh) {
  12961. this._scene._cachedMaterial = this;
  12962. if (this.onBind) {
  12963. this.onBind(this);
  12964. }
  12965. };
  12966. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12967. };
  12968. Material.prototype.unbind = function () {
  12969. };
  12970. Material.prototype.dispose = function (forceDisposeEffect) {
  12971. // Remove from scene
  12972. var index = this._scene.materials.indexOf(this);
  12973. this._scene.materials.splice(index, 1);
  12974. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12975. if (forceDisposeEffect && this._effect) {
  12976. this._scene.getEngine()._releaseEffect(this._effect);
  12977. this._effect = null;
  12978. }
  12979. // Callback
  12980. if (this.onDispose) {
  12981. this.onDispose();
  12982. }
  12983. };
  12984. Material._TriangleFillMode = 0;
  12985. Material._WireFrameFillMode = 1;
  12986. Material._PointFillMode = 2;
  12987. return Material;
  12988. })();
  12989. BABYLON.Material = Material;
  12990. })(BABYLON || (BABYLON = {}));
  12991. //# sourceMappingURL=babylon.material.js.map
  12992. var BABYLON;
  12993. (function (BABYLON) {
  12994. var maxSimultaneousLights = 4;
  12995. var FresnelParameters = (function () {
  12996. function FresnelParameters() {
  12997. this.isEnabled = true;
  12998. this.leftColor = BABYLON.Color3.White();
  12999. this.rightColor = BABYLON.Color3.Black();
  13000. this.bias = 0;
  13001. this.power = 1;
  13002. }
  13003. return FresnelParameters;
  13004. })();
  13005. BABYLON.FresnelParameters = FresnelParameters;
  13006. var StandardMaterial = (function (_super) {
  13007. __extends(StandardMaterial, _super);
  13008. function StandardMaterial(name, scene) {
  13009. var _this = this;
  13010. _super.call(this, name, scene);
  13011. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13012. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13013. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13014. this.specularPower = 64;
  13015. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13016. this.useAlphaFromDiffuseTexture = false;
  13017. this.useSpecularOverAlpha = true;
  13018. this.fogEnabled = true;
  13019. this._cachedDefines = null;
  13020. this._renderTargets = new BABYLON.SmartArray(16);
  13021. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13022. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13023. this._scaledDiffuse = new BABYLON.Color3();
  13024. this._scaledSpecular = new BABYLON.Color3();
  13025. this.getRenderTargetTextures = function () {
  13026. _this._renderTargets.reset();
  13027. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13028. _this._renderTargets.push(_this.reflectionTexture);
  13029. }
  13030. return _this._renderTargets;
  13031. };
  13032. }
  13033. StandardMaterial.prototype.needAlphaBlending = function () {
  13034. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13035. };
  13036. StandardMaterial.prototype.needAlphaTesting = function () {
  13037. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13038. };
  13039. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13040. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13041. };
  13042. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13043. return this.diffuseTexture;
  13044. };
  13045. // Methods
  13046. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13047. if (this.checkReadyOnlyOnce) {
  13048. if (this._wasPreviouslyReady) {
  13049. return true;
  13050. }
  13051. }
  13052. var scene = this.getScene();
  13053. if (!this.checkReadyOnEveryCall) {
  13054. if (this._renderId === scene.getRenderId()) {
  13055. return true;
  13056. }
  13057. }
  13058. var engine = scene.getEngine();
  13059. var defines = [];
  13060. var fallbacks = new BABYLON.EffectFallbacks();
  13061. // Textures
  13062. if (scene.texturesEnabled) {
  13063. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13064. if (!this.diffuseTexture.isReady()) {
  13065. return false;
  13066. } else {
  13067. defines.push("#define DIFFUSE");
  13068. }
  13069. }
  13070. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13071. if (!this.ambientTexture.isReady()) {
  13072. return false;
  13073. } else {
  13074. defines.push("#define AMBIENT");
  13075. }
  13076. }
  13077. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13078. if (!this.opacityTexture.isReady()) {
  13079. return false;
  13080. } else {
  13081. defines.push("#define OPACITY");
  13082. if (this.opacityTexture.getAlphaFromRGB) {
  13083. defines.push("#define OPACITYRGB");
  13084. }
  13085. }
  13086. }
  13087. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13088. if (!this.reflectionTexture.isReady()) {
  13089. return false;
  13090. } else {
  13091. defines.push("#define REFLECTION");
  13092. fallbacks.addFallback(0, "REFLECTION");
  13093. }
  13094. }
  13095. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13096. if (!this.emissiveTexture.isReady()) {
  13097. return false;
  13098. } else {
  13099. defines.push("#define EMISSIVE");
  13100. }
  13101. }
  13102. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13103. if (!this.specularTexture.isReady()) {
  13104. return false;
  13105. } else {
  13106. defines.push("#define SPECULAR");
  13107. fallbacks.addFallback(0, "SPECULAR");
  13108. }
  13109. }
  13110. }
  13111. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13112. if (!this.bumpTexture.isReady()) {
  13113. return false;
  13114. } else {
  13115. defines.push("#define BUMP");
  13116. fallbacks.addFallback(0, "BUMP");
  13117. }
  13118. }
  13119. // Effect
  13120. if (this.useSpecularOverAlpha) {
  13121. defines.push("#define SPECULAROVERALPHA");
  13122. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13123. }
  13124. if (scene.clipPlane) {
  13125. defines.push("#define CLIPPLANE");
  13126. }
  13127. if (engine.getAlphaTesting()) {
  13128. defines.push("#define ALPHATEST");
  13129. }
  13130. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13131. defines.push("#define ALPHAFROMDIFFUSE");
  13132. }
  13133. // Point size
  13134. if (this.pointsCloud || scene.forcePointsCloud) {
  13135. defines.push("#define POINTSIZE");
  13136. }
  13137. // Fog
  13138. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13139. defines.push("#define FOG");
  13140. fallbacks.addFallback(1, "FOG");
  13141. }
  13142. var shadowsActivated = false;
  13143. var lightIndex = 0;
  13144. if (scene.lightsEnabled) {
  13145. for (var index = 0; index < scene.lights.length; index++) {
  13146. var light = scene.lights[index];
  13147. if (!light.isEnabled()) {
  13148. continue;
  13149. }
  13150. // Excluded check
  13151. if (light._excludedMeshesIds.length > 0) {
  13152. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13153. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13154. if (excludedMesh) {
  13155. light.excludedMeshes.push(excludedMesh);
  13156. }
  13157. }
  13158. light._excludedMeshesIds = [];
  13159. }
  13160. // Included check
  13161. if (light._includedOnlyMeshesIds.length > 0) {
  13162. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13163. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13164. if (includedOnlyMesh) {
  13165. light.includedOnlyMeshes.push(includedOnlyMesh);
  13166. }
  13167. }
  13168. light._includedOnlyMeshesIds = [];
  13169. }
  13170. if (!light.canAffectMesh(mesh)) {
  13171. continue;
  13172. }
  13173. defines.push("#define LIGHT" + lightIndex);
  13174. if (lightIndex > 0) {
  13175. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13176. }
  13177. var type;
  13178. if (light instanceof BABYLON.SpotLight) {
  13179. type = "#define SPOTLIGHT" + lightIndex;
  13180. } else if (light instanceof BABYLON.HemisphericLight) {
  13181. type = "#define HEMILIGHT" + lightIndex;
  13182. } else {
  13183. type = "#define POINTDIRLIGHT" + lightIndex;
  13184. }
  13185. defines.push(type);
  13186. if (lightIndex > 0) {
  13187. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13188. }
  13189. // Shadows
  13190. if (scene.shadowsEnabled) {
  13191. var shadowGenerator = light.getShadowGenerator();
  13192. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13193. defines.push("#define SHADOW" + lightIndex);
  13194. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13195. if (!shadowsActivated) {
  13196. defines.push("#define SHADOWS");
  13197. shadowsActivated = true;
  13198. }
  13199. if (shadowGenerator.useVarianceShadowMap) {
  13200. defines.push("#define SHADOWVSM" + lightIndex);
  13201. if (lightIndex > 0) {
  13202. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13203. }
  13204. }
  13205. if (shadowGenerator.usePoissonSampling) {
  13206. defines.push("#define SHADOWPCF" + lightIndex);
  13207. if (lightIndex > 0) {
  13208. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13209. }
  13210. }
  13211. }
  13212. }
  13213. lightIndex++;
  13214. if (lightIndex === maxSimultaneousLights)
  13215. break;
  13216. }
  13217. }
  13218. if (StandardMaterial.FresnelEnabled) {
  13219. // Fresnel
  13220. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13221. var fresnelRank = 1;
  13222. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13223. defines.push("#define DIFFUSEFRESNEL");
  13224. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13225. fresnelRank++;
  13226. }
  13227. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13228. defines.push("#define OPACITYFRESNEL");
  13229. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13230. fresnelRank++;
  13231. }
  13232. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13233. defines.push("#define REFLECTIONFRESNEL");
  13234. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13235. fresnelRank++;
  13236. }
  13237. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13238. defines.push("#define EMISSIVEFRESNEL");
  13239. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13240. fresnelRank++;
  13241. }
  13242. defines.push("#define FRESNEL");
  13243. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13244. }
  13245. }
  13246. // Attribs
  13247. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13248. if (mesh) {
  13249. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13250. attribs.push(BABYLON.VertexBuffer.UVKind);
  13251. defines.push("#define UV1");
  13252. }
  13253. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13254. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13255. defines.push("#define UV2");
  13256. }
  13257. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13258. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13259. defines.push("#define VERTEXCOLOR");
  13260. if (mesh.hasVertexAlpha) {
  13261. defines.push("#define VERTEXALPHA");
  13262. }
  13263. }
  13264. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13265. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13266. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13267. defines.push("#define BONES");
  13268. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13269. defines.push("#define BONES4");
  13270. fallbacks.addFallback(0, "BONES4");
  13271. }
  13272. // Instances
  13273. if (useInstances) {
  13274. defines.push("#define INSTANCES");
  13275. attribs.push("world0");
  13276. attribs.push("world1");
  13277. attribs.push("world2");
  13278. attribs.push("world3");
  13279. }
  13280. }
  13281. // Get correct effect
  13282. var join = defines.join("\n");
  13283. if (this._cachedDefines !== join) {
  13284. this._cachedDefines = join;
  13285. scene.resetCachedMaterial();
  13286. // Legacy browser patch
  13287. var shaderName = "default";
  13288. if (!scene.getEngine().getCaps().standardDerivatives) {
  13289. shaderName = "legacydefault";
  13290. }
  13291. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  13292. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  13293. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  13294. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  13295. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  13296. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  13297. "vFogInfos", "vFogColor", "pointSize",
  13298. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  13299. "mBones",
  13300. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  13301. "darkness0", "darkness1", "darkness2", "darkness3",
  13302. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  13303. ], [
  13304. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  13305. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  13306. ], join, fallbacks, this.onCompiled, this.onError);
  13307. }
  13308. if (!this._effect.isReady()) {
  13309. return false;
  13310. }
  13311. this._renderId = scene.getRenderId();
  13312. this._wasPreviouslyReady = true;
  13313. return true;
  13314. };
  13315. StandardMaterial.prototype.unbind = function () {
  13316. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13317. this._effect.setTexture("reflection2DSampler", null);
  13318. }
  13319. };
  13320. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13321. this._effect.setMatrix("world", world);
  13322. };
  13323. StandardMaterial.prototype.bind = function (world, mesh) {
  13324. var scene = this.getScene();
  13325. // Matrices
  13326. this.bindOnlyWorldMatrix(world);
  13327. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13328. // Bones
  13329. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13330. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13331. }
  13332. if (scene.getCachedMaterial() !== this) {
  13333. if (StandardMaterial.FresnelEnabled) {
  13334. // Fresnel
  13335. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13336. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13337. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13338. }
  13339. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13340. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13341. }
  13342. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13343. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13344. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13345. }
  13346. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13347. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13348. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13349. }
  13350. }
  13351. // Textures
  13352. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13353. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13354. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13355. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13356. }
  13357. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13358. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13359. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13360. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13361. }
  13362. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13363. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13364. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13365. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13366. }
  13367. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13368. if (this.reflectionTexture.isCube) {
  13369. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13370. } else {
  13371. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13372. }
  13373. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13374. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13375. }
  13376. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13377. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13378. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13379. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13380. }
  13381. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13382. this._effect.setTexture("specularSampler", this.specularTexture);
  13383. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13384. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13385. }
  13386. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13387. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13388. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13389. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13390. }
  13391. // Clip plane
  13392. if (scene.clipPlane) {
  13393. var clipPlane = scene.clipPlane;
  13394. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13395. }
  13396. // Point size
  13397. if (this.pointsCloud) {
  13398. this._effect.setFloat("pointSize", this.pointSize);
  13399. }
  13400. // Colors
  13401. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13402. // Scaling down color according to emissive
  13403. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13404. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13405. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13406. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13407. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13408. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13409. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13410. }
  13411. // Scaling down color according to emissive
  13412. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13413. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13414. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13415. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13416. if (scene.lightsEnabled) {
  13417. var lightIndex = 0;
  13418. for (var index = 0; index < scene.lights.length; index++) {
  13419. var light = scene.lights[index];
  13420. if (!light.isEnabled()) {
  13421. continue;
  13422. }
  13423. if (!light.canAffectMesh(mesh)) {
  13424. continue;
  13425. }
  13426. if (light instanceof BABYLON.PointLight) {
  13427. // Point Light
  13428. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13429. } else if (light instanceof BABYLON.DirectionalLight) {
  13430. // Directional Light
  13431. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13432. } else if (light instanceof BABYLON.SpotLight) {
  13433. // Spot Light
  13434. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13435. } else if (light instanceof BABYLON.HemisphericLight) {
  13436. // Hemispheric Light
  13437. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13438. }
  13439. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13440. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13441. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13442. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13443. // Shadows
  13444. if (scene.shadowsEnabled) {
  13445. var shadowGenerator = light.getShadowGenerator();
  13446. if (mesh.receiveShadows && shadowGenerator) {
  13447. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13448. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13449. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13450. }
  13451. }
  13452. lightIndex++;
  13453. if (lightIndex === maxSimultaneousLights)
  13454. break;
  13455. }
  13456. }
  13457. // View
  13458. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13459. this._effect.setMatrix("view", scene.getViewMatrix());
  13460. }
  13461. // Fog
  13462. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13463. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13464. this._effect.setColor3("vFogColor", scene.fogColor);
  13465. }
  13466. _super.prototype.bind.call(this, world, mesh);
  13467. };
  13468. StandardMaterial.prototype.getAnimatables = function () {
  13469. var results = [];
  13470. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13471. results.push(this.diffuseTexture);
  13472. }
  13473. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13474. results.push(this.ambientTexture);
  13475. }
  13476. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13477. results.push(this.opacityTexture);
  13478. }
  13479. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13480. results.push(this.reflectionTexture);
  13481. }
  13482. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13483. results.push(this.emissiveTexture);
  13484. }
  13485. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13486. results.push(this.specularTexture);
  13487. }
  13488. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13489. results.push(this.bumpTexture);
  13490. }
  13491. return results;
  13492. };
  13493. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13494. if (this.diffuseTexture) {
  13495. this.diffuseTexture.dispose();
  13496. }
  13497. if (this.ambientTexture) {
  13498. this.ambientTexture.dispose();
  13499. }
  13500. if (this.opacityTexture) {
  13501. this.opacityTexture.dispose();
  13502. }
  13503. if (this.reflectionTexture) {
  13504. this.reflectionTexture.dispose();
  13505. }
  13506. if (this.emissiveTexture) {
  13507. this.emissiveTexture.dispose();
  13508. }
  13509. if (this.specularTexture) {
  13510. this.specularTexture.dispose();
  13511. }
  13512. if (this.bumpTexture) {
  13513. this.bumpTexture.dispose();
  13514. }
  13515. _super.prototype.dispose.call(this, forceDisposeEffect);
  13516. };
  13517. StandardMaterial.prototype.clone = function (name) {
  13518. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13519. // Base material
  13520. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13521. newStandardMaterial.alpha = this.alpha;
  13522. newStandardMaterial.fillMode = this.fillMode;
  13523. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13524. // Standard material
  13525. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13526. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13527. }
  13528. if (this.ambientTexture && this.ambientTexture.clone) {
  13529. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13530. }
  13531. if (this.opacityTexture && this.opacityTexture.clone) {
  13532. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13533. }
  13534. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13535. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13536. }
  13537. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13538. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13539. }
  13540. if (this.specularTexture && this.specularTexture.clone) {
  13541. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13542. }
  13543. if (this.bumpTexture && this.bumpTexture.clone) {
  13544. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13545. }
  13546. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13547. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13548. newStandardMaterial.specularColor = this.specularColor.clone();
  13549. newStandardMaterial.specularPower = this.specularPower;
  13550. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13551. return newStandardMaterial;
  13552. };
  13553. StandardMaterial.DiffuseTextureEnabled = true;
  13554. StandardMaterial.AmbientTextureEnabled = true;
  13555. StandardMaterial.OpacityTextureEnabled = true;
  13556. StandardMaterial.ReflectionTextureEnabled = true;
  13557. StandardMaterial.EmissiveTextureEnabled = true;
  13558. StandardMaterial.SpecularTextureEnabled = true;
  13559. StandardMaterial.BumpTextureEnabled = true;
  13560. StandardMaterial.FresnelEnabled = true;
  13561. return StandardMaterial;
  13562. })(BABYLON.Material);
  13563. BABYLON.StandardMaterial = StandardMaterial;
  13564. })(BABYLON || (BABYLON = {}));
  13565. //# sourceMappingURL=babylon.standardMaterial.js.map
  13566. var BABYLON;
  13567. (function (BABYLON) {
  13568. var MultiMaterial = (function (_super) {
  13569. __extends(MultiMaterial, _super);
  13570. function MultiMaterial(name, scene) {
  13571. _super.call(this, name, scene, true);
  13572. this.subMaterials = new Array();
  13573. scene.multiMaterials.push(this);
  13574. }
  13575. // Properties
  13576. MultiMaterial.prototype.getSubMaterial = function (index) {
  13577. if (index < 0 || index >= this.subMaterials.length) {
  13578. return this.getScene().defaultMaterial;
  13579. }
  13580. return this.subMaterials[index];
  13581. };
  13582. // Methods
  13583. MultiMaterial.prototype.isReady = function (mesh) {
  13584. for (var index = 0; index < this.subMaterials.length; index++) {
  13585. var subMaterial = this.subMaterials[index];
  13586. if (subMaterial) {
  13587. if (!this.subMaterials[index].isReady(mesh)) {
  13588. return false;
  13589. }
  13590. }
  13591. }
  13592. return true;
  13593. };
  13594. return MultiMaterial;
  13595. })(BABYLON.Material);
  13596. BABYLON.MultiMaterial = MultiMaterial;
  13597. })(BABYLON || (BABYLON = {}));
  13598. //# sourceMappingURL=babylon.multiMaterial.js.map
  13599. var BABYLON;
  13600. (function (BABYLON) {
  13601. var Database = (function () {
  13602. function Database(urlToScene, callbackManifestChecked) {
  13603. // Handling various flavors of prefixed version of IndexedDB
  13604. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13605. this.callbackManifestChecked = callbackManifestChecked;
  13606. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13607. this.db = null;
  13608. this.enableSceneOffline = false;
  13609. this.enableTexturesOffline = false;
  13610. this.manifestVersionFound = 0;
  13611. this.mustUpdateRessources = false;
  13612. this.hasReachedQuota = false;
  13613. this.checkManifestFile();
  13614. }
  13615. Database.prototype.checkManifestFile = function () {
  13616. var _this = this;
  13617. function noManifestFile() {
  13618. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13619. that.enableSceneOffline = false;
  13620. that.enableTexturesOffline = false;
  13621. that.callbackManifestChecked(false);
  13622. }
  13623. var that = this;
  13624. var manifestURL = this.currentSceneUrl + ".manifest";
  13625. var xhr = new XMLHttpRequest();
  13626. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13627. xhr.open("GET", manifestURLTimeStamped, true);
  13628. xhr.addEventListener("load", function () {
  13629. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13630. try {
  13631. var manifestFile = JSON.parse(xhr.response);
  13632. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13633. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13634. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13635. _this.manifestVersionFound = manifestFile.version;
  13636. }
  13637. if (_this.callbackManifestChecked) {
  13638. _this.callbackManifestChecked(true);
  13639. }
  13640. } catch (ex) {
  13641. noManifestFile();
  13642. }
  13643. } else {
  13644. noManifestFile();
  13645. }
  13646. }, false);
  13647. xhr.addEventListener("error", function (event) {
  13648. noManifestFile();
  13649. }, false);
  13650. try {
  13651. xhr.send();
  13652. } catch (ex) {
  13653. BABYLON.Tools.Error("Error on XHR send request.");
  13654. that.callbackManifestChecked(false);
  13655. }
  13656. };
  13657. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13658. var _this = this;
  13659. function handleError() {
  13660. that.isSupported = false;
  13661. if (errorCallback)
  13662. errorCallback();
  13663. }
  13664. var that = this;
  13665. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13666. // Your browser doesn't support IndexedDB
  13667. this.isSupported = false;
  13668. if (errorCallback)
  13669. errorCallback();
  13670. } else {
  13671. // If the DB hasn't been opened or created yet
  13672. if (!this.db) {
  13673. this.hasReachedQuota = false;
  13674. this.isSupported = true;
  13675. var request = this.idbFactory.open("babylonjs", 1);
  13676. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13677. request.onerror = function (event) {
  13678. handleError();
  13679. };
  13680. // executes when a version change transaction cannot complete due to other active transactions
  13681. request.onblocked = function (event) {
  13682. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13683. handleError();
  13684. };
  13685. // DB has been opened successfully
  13686. request.onsuccess = function (event) {
  13687. _this.db = request.result;
  13688. successCallback();
  13689. };
  13690. // Initialization of the DB. Creating Scenes & Textures stores
  13691. request.onupgradeneeded = function (event) {
  13692. _this.db = (event.target).result;
  13693. try {
  13694. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13695. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13696. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13697. } catch (ex) {
  13698. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13699. handleError();
  13700. }
  13701. };
  13702. } else {
  13703. if (successCallback)
  13704. successCallback();
  13705. }
  13706. }
  13707. };
  13708. Database.prototype.loadImageFromDB = function (url, image) {
  13709. var _this = this;
  13710. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13711. var saveAndLoadImage = function () {
  13712. if (!_this.hasReachedQuota && _this.db !== null) {
  13713. // the texture is not yet in the DB, let's try to save it
  13714. _this._saveImageIntoDBAsync(completeURL, image);
  13715. } else {
  13716. image.src = url;
  13717. }
  13718. };
  13719. if (!this.mustUpdateRessources) {
  13720. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13721. } else {
  13722. saveAndLoadImage();
  13723. }
  13724. };
  13725. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13726. if (this.isSupported && this.db !== null) {
  13727. var texture;
  13728. var transaction = this.db.transaction(["textures"]);
  13729. transaction.onabort = function (event) {
  13730. image.src = url;
  13731. };
  13732. transaction.oncomplete = function (event) {
  13733. var blobTextureURL;
  13734. if (texture) {
  13735. var URL = window.URL || window.webkitURL;
  13736. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13737. image.onerror = function () {
  13738. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13739. image.src = url;
  13740. };
  13741. image.src = blobTextureURL;
  13742. } else {
  13743. notInDBCallback();
  13744. }
  13745. };
  13746. var getRequest = transaction.objectStore("textures").get(url);
  13747. getRequest.onsuccess = function (event) {
  13748. texture = (event.target).result;
  13749. };
  13750. getRequest.onerror = function (event) {
  13751. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13752. image.src = url;
  13753. };
  13754. } else {
  13755. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13756. image.src = url;
  13757. }
  13758. };
  13759. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13760. var _this = this;
  13761. if (this.isSupported) {
  13762. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13763. var generateBlobUrl = function () {
  13764. var blobTextureURL;
  13765. if (blob) {
  13766. var URL = window.URL || window.webkitURL;
  13767. try {
  13768. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13769. } catch (ex) {
  13770. blobTextureURL = URL.createObjectURL(blob);
  13771. }
  13772. }
  13773. image.src = blobTextureURL;
  13774. };
  13775. if (BABYLON.Database.isUASupportingBlobStorage) {
  13776. var xhr = new XMLHttpRequest(), blob;
  13777. xhr.open("GET", url, true);
  13778. xhr.responseType = "blob";
  13779. xhr.addEventListener("load", function () {
  13780. if (xhr.status === 200) {
  13781. // Blob as response (XHR2)
  13782. blob = xhr.response;
  13783. var transaction = _this.db.transaction(["textures"], "readwrite");
  13784. // the transaction could abort because of a QuotaExceededError error
  13785. transaction.onabort = function (event) {
  13786. try {
  13787. if (event.srcElement.error.name === "QuotaExceededError") {
  13788. this.hasReachedQuota = true;
  13789. }
  13790. } catch (ex) {
  13791. }
  13792. generateBlobUrl();
  13793. };
  13794. transaction.oncomplete = function (event) {
  13795. generateBlobUrl();
  13796. };
  13797. var newTexture = { textureUrl: url, data: blob };
  13798. try {
  13799. // Put the blob into the dabase
  13800. var addRequest = transaction.objectStore("textures").put(newTexture);
  13801. addRequest.onsuccess = function (event) {
  13802. };
  13803. addRequest.onerror = function (event) {
  13804. generateBlobUrl();
  13805. };
  13806. } catch (ex) {
  13807. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13808. if (ex.code === 25) {
  13809. BABYLON.Database.isUASupportingBlobStorage = false;
  13810. }
  13811. image.src = url;
  13812. }
  13813. } else {
  13814. image.src = url;
  13815. }
  13816. }, false);
  13817. xhr.addEventListener("error", function (event) {
  13818. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13819. image.src = url;
  13820. }, false);
  13821. xhr.send();
  13822. } else {
  13823. image.src = url;
  13824. }
  13825. } else {
  13826. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13827. image.src = url;
  13828. }
  13829. };
  13830. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13831. var _this = this;
  13832. var updateVersion = function (event) {
  13833. // the version is not yet in the DB or we need to update it
  13834. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13835. };
  13836. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13837. };
  13838. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13839. var _this = this;
  13840. if (this.isSupported) {
  13841. var version;
  13842. try {
  13843. var transaction = this.db.transaction(["versions"]);
  13844. transaction.oncomplete = function (event) {
  13845. if (version) {
  13846. // If the version in the JSON file is > than the version in DB
  13847. if (_this.manifestVersionFound > version.data) {
  13848. _this.mustUpdateRessources = true;
  13849. updateInDBCallback();
  13850. } else {
  13851. callback(version.data);
  13852. }
  13853. } else {
  13854. _this.mustUpdateRessources = true;
  13855. updateInDBCallback();
  13856. }
  13857. };
  13858. transaction.onabort = function (event) {
  13859. callback(-1);
  13860. };
  13861. var getRequest = transaction.objectStore("versions").get(url);
  13862. getRequest.onsuccess = function (event) {
  13863. version = (event.target).result;
  13864. };
  13865. getRequest.onerror = function (event) {
  13866. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13867. callback(-1);
  13868. };
  13869. } catch (ex) {
  13870. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13871. callback(-1);
  13872. }
  13873. } else {
  13874. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13875. callback(-1);
  13876. }
  13877. };
  13878. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13879. var _this = this;
  13880. if (this.isSupported && !this.hasReachedQuota) {
  13881. try {
  13882. // Open a transaction to the database
  13883. var transaction = this.db.transaction(["versions"], "readwrite");
  13884. // the transaction could abort because of a QuotaExceededError error
  13885. transaction.onabort = function (event) {
  13886. try {
  13887. if (event.srcElement.error.name === "QuotaExceededError") {
  13888. _this.hasReachedQuota = true;
  13889. }
  13890. } catch (ex) {
  13891. }
  13892. callback(-1);
  13893. };
  13894. transaction.oncomplete = function (event) {
  13895. callback(_this.manifestVersionFound);
  13896. };
  13897. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13898. // Put the scene into the database
  13899. var addRequest = transaction.objectStore("versions").put(newVersion);
  13900. addRequest.onsuccess = function (event) {
  13901. };
  13902. addRequest.onerror = function (event) {
  13903. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13904. };
  13905. } catch (ex) {
  13906. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13907. callback(-1);
  13908. }
  13909. } else {
  13910. callback(-1);
  13911. }
  13912. };
  13913. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13914. var _this = this;
  13915. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13916. var saveAndLoadFile = function (event) {
  13917. // the scene is not yet in the DB, let's try to save it
  13918. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13919. };
  13920. this._checkVersionFromDB(completeUrl, function (version) {
  13921. if (version !== -1) {
  13922. if (!_this.mustUpdateRessources) {
  13923. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13924. } else {
  13925. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13926. }
  13927. } else {
  13928. errorCallback();
  13929. }
  13930. });
  13931. };
  13932. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13933. if (this.isSupported) {
  13934. var targetStore;
  13935. if (url.indexOf(".babylon") !== -1) {
  13936. targetStore = "scenes";
  13937. } else {
  13938. targetStore = "textures";
  13939. }
  13940. var file;
  13941. var transaction = this.db.transaction([targetStore]);
  13942. transaction.oncomplete = function (event) {
  13943. if (file) {
  13944. callback(file.data);
  13945. } else {
  13946. notInDBCallback();
  13947. }
  13948. };
  13949. transaction.onabort = function (event) {
  13950. notInDBCallback();
  13951. };
  13952. var getRequest = transaction.objectStore(targetStore).get(url);
  13953. getRequest.onsuccess = function (event) {
  13954. file = (event.target).result;
  13955. };
  13956. getRequest.onerror = function (event) {
  13957. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13958. notInDBCallback();
  13959. };
  13960. } else {
  13961. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13962. callback();
  13963. }
  13964. };
  13965. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13966. var _this = this;
  13967. if (this.isSupported) {
  13968. var targetStore;
  13969. if (url.indexOf(".babylon") !== -1) {
  13970. targetStore = "scenes";
  13971. } else {
  13972. targetStore = "textures";
  13973. }
  13974. // Create XHR
  13975. var xhr = new XMLHttpRequest(), fileData;
  13976. xhr.open("GET", url, true);
  13977. if (useArrayBuffer) {
  13978. xhr.responseType = "arraybuffer";
  13979. }
  13980. xhr.onprogress = progressCallback;
  13981. xhr.addEventListener("load", function () {
  13982. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13983. // Blob as response (XHR2)
  13984. //fileData = xhr.responseText;
  13985. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13986. if (!_this.hasReachedQuota) {
  13987. // Open a transaction to the database
  13988. var transaction = _this.db.transaction([targetStore], "readwrite");
  13989. // the transaction could abort because of a QuotaExceededError error
  13990. transaction.onabort = function (event) {
  13991. try {
  13992. if (event.srcElement.error.name === "QuotaExceededError") {
  13993. this.hasReachedQuota = true;
  13994. }
  13995. } catch (ex) {
  13996. }
  13997. callback(fileData);
  13998. };
  13999. transaction.oncomplete = function (event) {
  14000. callback(fileData);
  14001. };
  14002. var newFile;
  14003. if (targetStore === "scenes") {
  14004. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14005. } else {
  14006. newFile = { textureUrl: url, data: fileData };
  14007. }
  14008. try {
  14009. // Put the scene into the database
  14010. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14011. addRequest.onsuccess = function (event) {
  14012. };
  14013. addRequest.onerror = function (event) {
  14014. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14015. };
  14016. } catch (ex) {
  14017. callback(fileData);
  14018. }
  14019. } else {
  14020. callback(fileData);
  14021. }
  14022. } else {
  14023. callback();
  14024. }
  14025. }, false);
  14026. xhr.addEventListener("error", function (event) {
  14027. BABYLON.Tools.Error("error on XHR request.");
  14028. callback();
  14029. }, false);
  14030. xhr.send();
  14031. } else {
  14032. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14033. callback();
  14034. }
  14035. };
  14036. Database.isUASupportingBlobStorage = true;
  14037. Database.parseURL = function (url) {
  14038. var a = document.createElement('a');
  14039. a.href = url;
  14040. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14041. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14042. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14043. return absLocation;
  14044. };
  14045. Database.ReturnFullUrlLocation = function (url) {
  14046. if (url.indexOf("http:/") === -1) {
  14047. return (BABYLON.Database.parseURL(window.location.href) + url);
  14048. } else {
  14049. return url;
  14050. }
  14051. };
  14052. return Database;
  14053. })();
  14054. BABYLON.Database = Database;
  14055. })(BABYLON || (BABYLON = {}));
  14056. //# sourceMappingURL=babylon.database.js.map
  14057. var BABYLON;
  14058. (function (BABYLON) {
  14059. var SpriteManager = (function () {
  14060. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14061. this.name = name;
  14062. this.cellSize = cellSize;
  14063. this.sprites = new Array();
  14064. this.renderingGroupId = 0;
  14065. this.fogEnabled = true;
  14066. this._vertexDeclaration = [3, 4, 4, 4];
  14067. this._vertexStrideSize = 15 * 4;
  14068. this._capacity = capacity;
  14069. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14070. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14071. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14072. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14073. this._scene = scene;
  14074. this._scene.spriteManagers.push(this);
  14075. // VBO
  14076. this._vertexDeclaration = [3, 4, 4, 4];
  14077. this._vertexStrideSize = 15 * 4;
  14078. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14079. var indices = [];
  14080. var index = 0;
  14081. for (var count = 0; count < capacity; count++) {
  14082. indices.push(index);
  14083. indices.push(index + 1);
  14084. indices.push(index + 2);
  14085. indices.push(index);
  14086. indices.push(index + 2);
  14087. indices.push(index + 3);
  14088. index += 4;
  14089. }
  14090. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14091. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14092. // Effects
  14093. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14094. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14095. }
  14096. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14097. var arrayOffset = index * 15;
  14098. if (offsetX == 0)
  14099. offsetX = this._epsilon;
  14100. else if (offsetX == 1)
  14101. offsetX = 1 - this._epsilon;
  14102. if (offsetY == 0)
  14103. offsetY = this._epsilon;
  14104. else if (offsetY == 1)
  14105. offsetY = 1 - this._epsilon;
  14106. this._vertices[arrayOffset] = sprite.position.x;
  14107. this._vertices[arrayOffset + 1] = sprite.position.y;
  14108. this._vertices[arrayOffset + 2] = sprite.position.z;
  14109. this._vertices[arrayOffset + 3] = sprite.angle;
  14110. this._vertices[arrayOffset + 4] = sprite.size;
  14111. this._vertices[arrayOffset + 5] = offsetX;
  14112. this._vertices[arrayOffset + 6] = offsetY;
  14113. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14114. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14115. var offset = (sprite.cellIndex / rowSize) >> 0;
  14116. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14117. this._vertices[arrayOffset + 10] = offset;
  14118. // Color
  14119. this._vertices[arrayOffset + 11] = sprite.color.r;
  14120. this._vertices[arrayOffset + 12] = sprite.color.g;
  14121. this._vertices[arrayOffset + 13] = sprite.color.b;
  14122. this._vertices[arrayOffset + 14] = sprite.color.a;
  14123. };
  14124. SpriteManager.prototype.render = function () {
  14125. // Check
  14126. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14127. return;
  14128. var engine = this._scene.getEngine();
  14129. var baseSize = this._spriteTexture.getBaseSize();
  14130. // Sprites
  14131. var deltaTime = engine.getDeltaTime();
  14132. var max = Math.min(this._capacity, this.sprites.length);
  14133. var rowSize = baseSize.width / this.cellSize;
  14134. var offset = 0;
  14135. for (var index = 0; index < max; index++) {
  14136. var sprite = this.sprites[index];
  14137. if (!sprite) {
  14138. continue;
  14139. }
  14140. sprite._animate(deltaTime);
  14141. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14142. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14143. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14144. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14145. }
  14146. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14147. // Render
  14148. var effect = this._effectBase;
  14149. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14150. effect = this._effectFog;
  14151. }
  14152. engine.enableEffect(effect);
  14153. var viewMatrix = this._scene.getViewMatrix();
  14154. effect.setTexture("diffuseSampler", this._spriteTexture);
  14155. effect.setMatrix("view", viewMatrix);
  14156. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14157. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14158. // Fog
  14159. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14160. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14161. effect.setColor3("vFogColor", this._scene.fogColor);
  14162. }
  14163. // VBOs
  14164. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14165. // Draw order
  14166. effect.setBool("alphaTest", true);
  14167. engine.setColorWrite(false);
  14168. engine.draw(true, 0, max * 6);
  14169. engine.setColorWrite(true);
  14170. effect.setBool("alphaTest", false);
  14171. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14172. engine.draw(true, 0, max * 6);
  14173. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14174. };
  14175. SpriteManager.prototype.dispose = function () {
  14176. if (this._vertexBuffer) {
  14177. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14178. this._vertexBuffer = null;
  14179. }
  14180. if (this._indexBuffer) {
  14181. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14182. this._indexBuffer = null;
  14183. }
  14184. if (this._spriteTexture) {
  14185. this._spriteTexture.dispose();
  14186. this._spriteTexture = null;
  14187. }
  14188. // Remove from scene
  14189. var index = this._scene.spriteManagers.indexOf(this);
  14190. this._scene.spriteManagers.splice(index, 1);
  14191. // Callback
  14192. if (this.onDispose) {
  14193. this.onDispose();
  14194. }
  14195. };
  14196. return SpriteManager;
  14197. })();
  14198. BABYLON.SpriteManager = SpriteManager;
  14199. })(BABYLON || (BABYLON = {}));
  14200. //# sourceMappingURL=babylon.spriteManager.js.map
  14201. var BABYLON;
  14202. (function (BABYLON) {
  14203. var Sprite = (function () {
  14204. function Sprite(name, manager) {
  14205. this.name = name;
  14206. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14207. this.size = 1.0;
  14208. this.angle = 0;
  14209. this.cellIndex = 0;
  14210. this.invertU = 0;
  14211. this.invertV = 0;
  14212. this.animations = new Array();
  14213. this._animationStarted = false;
  14214. this._loopAnimation = false;
  14215. this._fromIndex = 0;
  14216. this._toIndex = 0;
  14217. this._delay = 0;
  14218. this._direction = 1;
  14219. this._frameCount = 0;
  14220. this._time = 0;
  14221. this._manager = manager;
  14222. this._manager.sprites.push(this);
  14223. this.position = BABYLON.Vector3.Zero();
  14224. }
  14225. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14226. this._fromIndex = from;
  14227. this._toIndex = to;
  14228. this._loopAnimation = loop;
  14229. this._delay = delay;
  14230. this._animationStarted = true;
  14231. this._direction = from < to ? 1 : -1;
  14232. this.cellIndex = from;
  14233. this._time = 0;
  14234. };
  14235. Sprite.prototype.stopAnimation = function () {
  14236. this._animationStarted = false;
  14237. };
  14238. Sprite.prototype._animate = function (deltaTime) {
  14239. if (!this._animationStarted)
  14240. return;
  14241. this._time += deltaTime;
  14242. if (this._time > this._delay) {
  14243. this._time = this._time % this._delay;
  14244. this.cellIndex += this._direction;
  14245. if (this.cellIndex == this._toIndex) {
  14246. if (this._loopAnimation) {
  14247. this.cellIndex = this._fromIndex;
  14248. } else {
  14249. this._animationStarted = false;
  14250. if (this.disposeWhenFinishedAnimating) {
  14251. this.dispose();
  14252. }
  14253. }
  14254. }
  14255. }
  14256. };
  14257. Sprite.prototype.dispose = function () {
  14258. for (var i = 0; i < this._manager.sprites.length; i++) {
  14259. if (this._manager.sprites[i] == this) {
  14260. this._manager.sprites.splice(i, 1);
  14261. }
  14262. }
  14263. };
  14264. return Sprite;
  14265. })();
  14266. BABYLON.Sprite = Sprite;
  14267. })(BABYLON || (BABYLON = {}));
  14268. //# sourceMappingURL=babylon.sprite.js.map
  14269. var BABYLON;
  14270. (function (BABYLON) {
  14271. var Layer = (function () {
  14272. function Layer(name, imgUrl, scene, isBackground, color) {
  14273. this.name = name;
  14274. this._vertexDeclaration = [2];
  14275. this._vertexStrideSize = 2 * 4;
  14276. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14277. this.isBackground = isBackground === undefined ? true : isBackground;
  14278. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14279. this._scene = scene;
  14280. this._scene.layers.push(this);
  14281. // VBO
  14282. var vertices = [];
  14283. vertices.push(1, 1);
  14284. vertices.push(-1, 1);
  14285. vertices.push(-1, -1);
  14286. vertices.push(1, -1);
  14287. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14288. // Indices
  14289. var indices = [];
  14290. indices.push(0);
  14291. indices.push(1);
  14292. indices.push(2);
  14293. indices.push(0);
  14294. indices.push(2);
  14295. indices.push(3);
  14296. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14297. // Effects
  14298. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14299. }
  14300. Layer.prototype.render = function () {
  14301. // Check
  14302. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14303. return;
  14304. var engine = this._scene.getEngine();
  14305. // Render
  14306. engine.enableEffect(this._effect);
  14307. engine.setState(false);
  14308. // Texture
  14309. this._effect.setTexture("textureSampler", this.texture);
  14310. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14311. // Color
  14312. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14313. // VBOs
  14314. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14315. // Draw order
  14316. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14317. engine.draw(true, 0, 6);
  14318. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14319. };
  14320. Layer.prototype.dispose = function () {
  14321. if (this._vertexBuffer) {
  14322. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14323. this._vertexBuffer = null;
  14324. }
  14325. if (this._indexBuffer) {
  14326. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14327. this._indexBuffer = null;
  14328. }
  14329. if (this.texture) {
  14330. this.texture.dispose();
  14331. this.texture = null;
  14332. }
  14333. // Remove from scene
  14334. var index = this._scene.layers.indexOf(this);
  14335. this._scene.layers.splice(index, 1);
  14336. // Callback
  14337. if (this.onDispose) {
  14338. this.onDispose();
  14339. }
  14340. };
  14341. return Layer;
  14342. })();
  14343. BABYLON.Layer = Layer;
  14344. })(BABYLON || (BABYLON = {}));
  14345. //# sourceMappingURL=babylon.layer.js.map
  14346. var BABYLON;
  14347. (function (BABYLON) {
  14348. var Particle = (function () {
  14349. function Particle() {
  14350. this.position = BABYLON.Vector3.Zero();
  14351. this.direction = BABYLON.Vector3.Zero();
  14352. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14353. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14354. this.lifeTime = 1.0;
  14355. this.age = 0;
  14356. this.size = 0;
  14357. this.angle = 0;
  14358. this.angularSpeed = 0;
  14359. }
  14360. Particle.prototype.copyTo = function (other) {
  14361. other.position.copyFrom(this.position);
  14362. other.direction.copyFrom(this.direction);
  14363. other.color.copyFrom(this.color);
  14364. other.colorStep.copyFrom(this.colorStep);
  14365. other.lifeTime = this.lifeTime;
  14366. other.age = this.age;
  14367. other.size = this.size;
  14368. other.angle = this.angle;
  14369. other.angularSpeed = this.angularSpeed;
  14370. };
  14371. return Particle;
  14372. })();
  14373. BABYLON.Particle = Particle;
  14374. })(BABYLON || (BABYLON = {}));
  14375. //# sourceMappingURL=babylon.particle.js.map
  14376. var BABYLON;
  14377. (function (BABYLON) {
  14378. var randomNumber = function (min, max) {
  14379. if (min === max) {
  14380. return (min);
  14381. }
  14382. var random = Math.random();
  14383. return ((random * (max - min)) + min);
  14384. };
  14385. var ParticleSystem = (function () {
  14386. function ParticleSystem(name, capacity, scene, customEffect) {
  14387. var _this = this;
  14388. this.name = name;
  14389. this.renderingGroupId = 0;
  14390. this.emitter = null;
  14391. this.emitRate = 10;
  14392. this.manualEmitCount = -1;
  14393. this.updateSpeed = 0.01;
  14394. this.targetStopDuration = 0;
  14395. this.disposeOnStop = false;
  14396. this.minEmitPower = 1;
  14397. this.maxEmitPower = 1;
  14398. this.minLifeTime = 1;
  14399. this.maxLifeTime = 1;
  14400. this.minSize = 1;
  14401. this.maxSize = 1;
  14402. this.minAngularSpeed = 0;
  14403. this.maxAngularSpeed = 0;
  14404. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14405. this.forceDepthWrite = false;
  14406. this.gravity = BABYLON.Vector3.Zero();
  14407. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14408. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14409. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14410. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14411. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14412. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14413. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14414. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14415. this.particles = new Array();
  14416. this._vertexDeclaration = [3, 4, 4];
  14417. this._vertexStrideSize = 11 * 4;
  14418. this._stockParticles = new Array();
  14419. this._newPartsExcess = 0;
  14420. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14421. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14422. this._scaledDirection = BABYLON.Vector3.Zero();
  14423. this._scaledGravity = BABYLON.Vector3.Zero();
  14424. this._currentRenderId = -1;
  14425. this._started = false;
  14426. this._stopped = false;
  14427. this._actualFrame = 0;
  14428. this.id = name;
  14429. this._capacity = capacity;
  14430. this._scene = scene;
  14431. this._customEffect = customEffect;
  14432. scene.particleSystems.push(this);
  14433. // VBO
  14434. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14435. var indices = [];
  14436. var index = 0;
  14437. for (var count = 0; count < capacity; count++) {
  14438. indices.push(index);
  14439. indices.push(index + 1);
  14440. indices.push(index + 2);
  14441. indices.push(index);
  14442. indices.push(index + 2);
  14443. indices.push(index + 3);
  14444. index += 4;
  14445. }
  14446. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14447. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14448. // Default behaviors
  14449. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14450. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14451. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14452. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14453. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14454. };
  14455. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14456. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14457. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14458. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14459. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14460. };
  14461. this.updateFunction = function (particles) {
  14462. for (var index = 0; index < particles.length; index++) {
  14463. var particle = particles[index];
  14464. particle.age += _this._scaledUpdateSpeed;
  14465. if (particle.age >= particle.lifeTime) {
  14466. _this.recycleParticle(particle);
  14467. index--;
  14468. continue;
  14469. } else {
  14470. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14471. particle.color.addInPlace(_this._scaledColorStep);
  14472. if (particle.color.a < 0)
  14473. particle.color.a = 0;
  14474. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14475. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14476. particle.position.addInPlace(_this._scaledDirection);
  14477. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14478. particle.direction.addInPlace(_this._scaledGravity);
  14479. }
  14480. }
  14481. };
  14482. }
  14483. ParticleSystem.prototype.recycleParticle = function (particle) {
  14484. var lastParticle = this.particles.pop();
  14485. if (lastParticle !== particle) {
  14486. lastParticle.copyTo(particle);
  14487. this._stockParticles.push(lastParticle);
  14488. }
  14489. };
  14490. ParticleSystem.prototype.getCapacity = function () {
  14491. return this._capacity;
  14492. };
  14493. ParticleSystem.prototype.isAlive = function () {
  14494. return this._alive;
  14495. };
  14496. ParticleSystem.prototype.isStarted = function () {
  14497. return this._started;
  14498. };
  14499. ParticleSystem.prototype.start = function () {
  14500. this._started = true;
  14501. this._stopped = false;
  14502. this._actualFrame = 0;
  14503. };
  14504. ParticleSystem.prototype.stop = function () {
  14505. this._stopped = true;
  14506. };
  14507. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14508. var offset = index * 11;
  14509. this._vertices[offset] = particle.position.x;
  14510. this._vertices[offset + 1] = particle.position.y;
  14511. this._vertices[offset + 2] = particle.position.z;
  14512. this._vertices[offset + 3] = particle.color.r;
  14513. this._vertices[offset + 4] = particle.color.g;
  14514. this._vertices[offset + 5] = particle.color.b;
  14515. this._vertices[offset + 6] = particle.color.a;
  14516. this._vertices[offset + 7] = particle.angle;
  14517. this._vertices[offset + 8] = particle.size;
  14518. this._vertices[offset + 9] = offsetX;
  14519. this._vertices[offset + 10] = offsetY;
  14520. };
  14521. ParticleSystem.prototype._update = function (newParticles) {
  14522. // Update current
  14523. this._alive = this.particles.length > 0;
  14524. this.updateFunction(this.particles);
  14525. // Add new ones
  14526. var worldMatrix;
  14527. if (this.emitter.position) {
  14528. worldMatrix = this.emitter.getWorldMatrix();
  14529. } else {
  14530. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14531. }
  14532. for (var index = 0; index < newParticles; index++) {
  14533. if (this.particles.length === this._capacity) {
  14534. break;
  14535. }
  14536. if (this._stockParticles.length !== 0) {
  14537. var particle = this._stockParticles.pop();
  14538. particle.age = 0;
  14539. } else {
  14540. particle = new BABYLON.Particle();
  14541. }
  14542. this.particles.push(particle);
  14543. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14544. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14545. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14546. particle.size = randomNumber(this.minSize, this.maxSize);
  14547. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14548. this.startPositionFunction(worldMatrix, particle.position);
  14549. var step = randomNumber(0, 1.0);
  14550. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14551. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14552. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14553. }
  14554. };
  14555. ParticleSystem.prototype._getEffect = function () {
  14556. if (this._customEffect) {
  14557. return this._customEffect;
  14558. }
  14559. ;
  14560. var defines = [];
  14561. if (this._scene.clipPlane) {
  14562. defines.push("#define CLIPPLANE");
  14563. }
  14564. // Effect
  14565. var join = defines.join("\n");
  14566. if (this._cachedDefines !== join) {
  14567. this._cachedDefines = join;
  14568. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14569. }
  14570. return this._effect;
  14571. };
  14572. ParticleSystem.prototype.animate = function () {
  14573. if (!this._started)
  14574. return;
  14575. var effect = this._getEffect();
  14576. // Check
  14577. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14578. return;
  14579. if (this._currentRenderId === this._scene.getRenderId()) {
  14580. return;
  14581. }
  14582. this._currentRenderId = this._scene.getRenderId();
  14583. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14584. // determine the number of particles we need to create
  14585. var emitCout;
  14586. if (this.manualEmitCount > -1) {
  14587. emitCout = this.manualEmitCount;
  14588. this.manualEmitCount = 0;
  14589. } else {
  14590. emitCout = this.emitRate;
  14591. }
  14592. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14593. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14594. if (this._newPartsExcess > 1.0) {
  14595. newParticles += this._newPartsExcess >> 0;
  14596. this._newPartsExcess -= this._newPartsExcess >> 0;
  14597. }
  14598. this._alive = false;
  14599. if (!this._stopped) {
  14600. this._actualFrame += this._scaledUpdateSpeed;
  14601. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14602. this.stop();
  14603. } else {
  14604. newParticles = 0;
  14605. }
  14606. this._update(newParticles);
  14607. // Stopped?
  14608. if (this._stopped) {
  14609. if (!this._alive) {
  14610. this._started = false;
  14611. if (this.disposeOnStop) {
  14612. this._scene._toBeDisposed.push(this);
  14613. }
  14614. }
  14615. }
  14616. // Update VBO
  14617. var offset = 0;
  14618. for (var index = 0; index < this.particles.length; index++) {
  14619. var particle = this.particles[index];
  14620. this._appendParticleVertex(offset++, particle, 0, 0);
  14621. this._appendParticleVertex(offset++, particle, 1, 0);
  14622. this._appendParticleVertex(offset++, particle, 1, 1);
  14623. this._appendParticleVertex(offset++, particle, 0, 1);
  14624. }
  14625. var engine = this._scene.getEngine();
  14626. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14627. };
  14628. ParticleSystem.prototype.render = function () {
  14629. var effect = this._getEffect();
  14630. // Check
  14631. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14632. return 0;
  14633. var engine = this._scene.getEngine();
  14634. // Render
  14635. engine.enableEffect(effect);
  14636. engine.setState(false);
  14637. var viewMatrix = this._scene.getViewMatrix();
  14638. effect.setTexture("diffuseSampler", this.particleTexture);
  14639. effect.setMatrix("view", viewMatrix);
  14640. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14641. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14642. if (this._scene.clipPlane) {
  14643. var clipPlane = this._scene.clipPlane;
  14644. var invView = viewMatrix.clone();
  14645. invView.invert();
  14646. effect.setMatrix("invView", invView);
  14647. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14648. }
  14649. // VBOs
  14650. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14651. // Draw order
  14652. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14653. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14654. } else {
  14655. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14656. }
  14657. if (this.forceDepthWrite) {
  14658. engine.setDepthWrite(true);
  14659. }
  14660. engine.draw(true, 0, this.particles.length * 6);
  14661. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14662. return this.particles.length;
  14663. };
  14664. ParticleSystem.prototype.dispose = function () {
  14665. if (this._vertexBuffer) {
  14666. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14667. this._vertexBuffer = null;
  14668. }
  14669. if (this._indexBuffer) {
  14670. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14671. this._indexBuffer = null;
  14672. }
  14673. if (this.particleTexture) {
  14674. this.particleTexture.dispose();
  14675. this.particleTexture = null;
  14676. }
  14677. // Remove from scene
  14678. var index = this._scene.particleSystems.indexOf(this);
  14679. this._scene.particleSystems.splice(index, 1);
  14680. // Callback
  14681. if (this.onDispose) {
  14682. this.onDispose();
  14683. }
  14684. };
  14685. // Clone
  14686. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14687. var result = new ParticleSystem(name, this._capacity, this._scene);
  14688. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14689. if (newEmitter === undefined) {
  14690. newEmitter = this.emitter;
  14691. }
  14692. result.emitter = newEmitter;
  14693. if (this.particleTexture) {
  14694. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14695. }
  14696. result.start();
  14697. return result;
  14698. };
  14699. ParticleSystem.BLENDMODE_ONEONE = 0;
  14700. ParticleSystem.BLENDMODE_STANDARD = 1;
  14701. return ParticleSystem;
  14702. })();
  14703. BABYLON.ParticleSystem = ParticleSystem;
  14704. })(BABYLON || (BABYLON = {}));
  14705. //# sourceMappingURL=babylon.particleSystem.js.map
  14706. var BABYLON;
  14707. (function (BABYLON) {
  14708. var Animation = (function () {
  14709. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14710. this.name = name;
  14711. this.targetProperty = targetProperty;
  14712. this.framePerSecond = framePerSecond;
  14713. this.dataType = dataType;
  14714. this.loopMode = loopMode;
  14715. this._offsetsCache = {};
  14716. this._highLimitsCache = {};
  14717. this._stopped = false;
  14718. this.targetPropertyPath = targetProperty.split(".");
  14719. this.dataType = dataType;
  14720. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14721. }
  14722. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14723. var dataType = undefined;
  14724. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14725. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14726. } else if (from instanceof BABYLON.Quaternion) {
  14727. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14728. } else if (from instanceof BABYLON.Vector3) {
  14729. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14730. } else if (from instanceof BABYLON.Vector2) {
  14731. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14732. } else if (from instanceof BABYLON.Color3) {
  14733. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14734. }
  14735. if (dataType == undefined) {
  14736. return;
  14737. }
  14738. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14739. var keys = [];
  14740. keys.push({ frame: 0, value: from });
  14741. keys.push({ frame: totalFrame, value: to });
  14742. animation.setKeys(keys);
  14743. mesh.animations.push(animation);
  14744. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14745. };
  14746. // Methods
  14747. Animation.prototype.isStopped = function () {
  14748. return this._stopped;
  14749. };
  14750. Animation.prototype.getKeys = function () {
  14751. return this._keys;
  14752. };
  14753. Animation.prototype.getEasingFunction = function () {
  14754. return this._easingFunction;
  14755. };
  14756. Animation.prototype.setEasingFunction = function (easingFunction) {
  14757. this._easingFunction = easingFunction;
  14758. };
  14759. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14760. return startValue + (endValue - startValue) * gradient;
  14761. };
  14762. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14763. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14764. };
  14765. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14766. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14767. };
  14768. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14769. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14770. };
  14771. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14772. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14773. };
  14774. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  14775. var startScale = new BABYLON.Vector3(0, 0, 0);
  14776. var startRotation = new BABYLON.Quaternion();
  14777. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  14778. startValue.decompose(startScale, startRotation, startTranslation);
  14779. var endScale = new BABYLON.Vector3(0, 0, 0);
  14780. var endRotation = new BABYLON.Quaternion();
  14781. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  14782. endValue.decompose(endScale, endRotation, endTranslation);
  14783. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  14784. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  14785. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  14786. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  14787. return result;
  14788. };
  14789. Animation.prototype.clone = function () {
  14790. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14791. clone.setKeys(this._keys);
  14792. return clone;
  14793. };
  14794. Animation.prototype.setKeys = function (values) {
  14795. this._keys = values.slice(0);
  14796. this._offsetsCache = {};
  14797. this._highLimitsCache = {};
  14798. };
  14799. Animation.prototype._getKeyValue = function (value) {
  14800. if (typeof value === "function") {
  14801. return value();
  14802. }
  14803. return value;
  14804. };
  14805. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14806. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14807. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14808. }
  14809. this.currentFrame = currentFrame;
  14810. for (var key = 0; key < this._keys.length; key++) {
  14811. // for each frame, we need the key just before the frame superior
  14812. if (this._keys[key + 1].frame >= currentFrame) {
  14813. var startValue = this._getKeyValue(this._keys[key].value);
  14814. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14815. // gradient : percent of currentFrame between the frame inf and the frame sup
  14816. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14817. // check for easingFunction and correction of gradient
  14818. if (this._easingFunction != null) {
  14819. gradient = this._easingFunction.ease(gradient);
  14820. }
  14821. switch (this.dataType) {
  14822. case Animation.ANIMATIONTYPE_FLOAT:
  14823. switch (loopMode) {
  14824. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14825. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14826. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14827. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14828. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14829. }
  14830. break;
  14831. case Animation.ANIMATIONTYPE_QUATERNION:
  14832. var quaternion = null;
  14833. switch (loopMode) {
  14834. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14835. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14836. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14837. break;
  14838. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14839. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14840. break;
  14841. }
  14842. return quaternion;
  14843. case Animation.ANIMATIONTYPE_VECTOR3:
  14844. switch (loopMode) {
  14845. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14846. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14847. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14848. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14849. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14850. }
  14851. case Animation.ANIMATIONTYPE_VECTOR2:
  14852. switch (loopMode) {
  14853. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14854. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14855. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14856. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14857. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14858. }
  14859. case Animation.ANIMATIONTYPE_COLOR3:
  14860. switch (loopMode) {
  14861. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14862. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14863. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14864. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14865. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14866. }
  14867. case Animation.ANIMATIONTYPE_MATRIX:
  14868. switch (loopMode) {
  14869. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14870. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14871. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  14872. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14873. return startValue;
  14874. }
  14875. default:
  14876. break;
  14877. }
  14878. break;
  14879. }
  14880. }
  14881. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  14882. };
  14883. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14884. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14885. this._stopped = true;
  14886. return false;
  14887. }
  14888. var returnValue = true;
  14889. // Adding a start key at frame 0 if missing
  14890. if (this._keys[0].frame !== 0) {
  14891. var newKey = { frame: 0, value: this._keys[0].value };
  14892. this._keys.splice(0, 0, newKey);
  14893. }
  14894. // Check limits
  14895. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14896. from = this._keys[0].frame;
  14897. }
  14898. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14899. to = this._keys[this._keys.length - 1].frame;
  14900. }
  14901. // Compute ratio
  14902. var range = to - from;
  14903. var offsetValue;
  14904. // ratio represents the frame delta between from and to
  14905. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14906. var highLimitValue = 0;
  14907. if (ratio > range && !loop) {
  14908. returnValue = false;
  14909. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  14910. } else {
  14911. // Get max value if required
  14912. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  14913. var keyOffset = to.toString() + from.toString();
  14914. if (!this._offsetsCache[keyOffset]) {
  14915. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14916. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14917. switch (this.dataType) {
  14918. case Animation.ANIMATIONTYPE_FLOAT:
  14919. this._offsetsCache[keyOffset] = toValue - fromValue;
  14920. break;
  14921. case Animation.ANIMATIONTYPE_QUATERNION:
  14922. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14923. break;
  14924. case Animation.ANIMATIONTYPE_VECTOR3:
  14925. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14926. case Animation.ANIMATIONTYPE_VECTOR2:
  14927. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14928. case Animation.ANIMATIONTYPE_COLOR3:
  14929. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14930. default:
  14931. break;
  14932. }
  14933. this._highLimitsCache[keyOffset] = toValue;
  14934. }
  14935. highLimitValue = this._highLimitsCache[keyOffset];
  14936. offsetValue = this._offsetsCache[keyOffset];
  14937. }
  14938. }
  14939. if (offsetValue === undefined) {
  14940. switch (this.dataType) {
  14941. case Animation.ANIMATIONTYPE_FLOAT:
  14942. offsetValue = 0;
  14943. break;
  14944. case Animation.ANIMATIONTYPE_QUATERNION:
  14945. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14946. break;
  14947. case Animation.ANIMATIONTYPE_VECTOR3:
  14948. offsetValue = BABYLON.Vector3.Zero();
  14949. break;
  14950. case Animation.ANIMATIONTYPE_VECTOR2:
  14951. offsetValue = BABYLON.Vector2.Zero();
  14952. break;
  14953. case Animation.ANIMATIONTYPE_COLOR3:
  14954. offsetValue = BABYLON.Color3.Black();
  14955. }
  14956. }
  14957. // Compute value
  14958. var repeatCount = (ratio / range) >> 0;
  14959. var currentFrame = returnValue ? from + ratio % range : to;
  14960. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14961. // Set value
  14962. if (this.targetPropertyPath.length > 1) {
  14963. var property = this._target[this.targetPropertyPath[0]];
  14964. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14965. property = property[this.targetPropertyPath[index]];
  14966. }
  14967. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14968. } else {
  14969. this._target[this.targetPropertyPath[0]] = currentValue;
  14970. }
  14971. if (this._target.markAsDirty) {
  14972. this._target.markAsDirty(this.targetProperty);
  14973. }
  14974. if (!returnValue) {
  14975. this._stopped = true;
  14976. }
  14977. return returnValue;
  14978. };
  14979. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14980. get: function () {
  14981. return Animation._ANIMATIONTYPE_FLOAT;
  14982. },
  14983. enumerable: true,
  14984. configurable: true
  14985. });
  14986. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14987. get: function () {
  14988. return Animation._ANIMATIONTYPE_VECTOR3;
  14989. },
  14990. enumerable: true,
  14991. configurable: true
  14992. });
  14993. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14994. get: function () {
  14995. return Animation._ANIMATIONTYPE_VECTOR2;
  14996. },
  14997. enumerable: true,
  14998. configurable: true
  14999. });
  15000. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15001. get: function () {
  15002. return Animation._ANIMATIONTYPE_QUATERNION;
  15003. },
  15004. enumerable: true,
  15005. configurable: true
  15006. });
  15007. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15008. get: function () {
  15009. return Animation._ANIMATIONTYPE_MATRIX;
  15010. },
  15011. enumerable: true,
  15012. configurable: true
  15013. });
  15014. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15015. get: function () {
  15016. return Animation._ANIMATIONTYPE_COLOR3;
  15017. },
  15018. enumerable: true,
  15019. configurable: true
  15020. });
  15021. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15022. get: function () {
  15023. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15024. },
  15025. enumerable: true,
  15026. configurable: true
  15027. });
  15028. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15029. get: function () {
  15030. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15031. },
  15032. enumerable: true,
  15033. configurable: true
  15034. });
  15035. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15036. get: function () {
  15037. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15038. },
  15039. enumerable: true,
  15040. configurable: true
  15041. });
  15042. Animation._ANIMATIONTYPE_FLOAT = 0;
  15043. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15044. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15045. Animation._ANIMATIONTYPE_MATRIX = 3;
  15046. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15047. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15048. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15049. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15050. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15051. return Animation;
  15052. })();
  15053. BABYLON.Animation = Animation;
  15054. })(BABYLON || (BABYLON = {}));
  15055. //# sourceMappingURL=babylon.animation.js.map
  15056. var BABYLON;
  15057. (function (BABYLON) {
  15058. var Animatable = (function () {
  15059. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15060. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  15061. if (typeof toFrame === "undefined") { toFrame = 100; }
  15062. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  15063. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  15064. this.target = target;
  15065. this.fromFrame = fromFrame;
  15066. this.toFrame = toFrame;
  15067. this.loopAnimation = loopAnimation;
  15068. this.speedRatio = speedRatio;
  15069. this.onAnimationEnd = onAnimationEnd;
  15070. this._animations = new Array();
  15071. this._paused = false;
  15072. this.animationStarted = false;
  15073. if (animations) {
  15074. this.appendAnimations(target, animations);
  15075. }
  15076. this._scene = scene;
  15077. scene._activeAnimatables.push(this);
  15078. }
  15079. // Methods
  15080. Animatable.prototype.appendAnimations = function (target, animations) {
  15081. for (var index = 0; index < animations.length; index++) {
  15082. var animation = animations[index];
  15083. animation._target = target;
  15084. this._animations.push(animation);
  15085. }
  15086. };
  15087. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15088. var animations = this._animations;
  15089. for (var index = 0; index < animations.length; index++) {
  15090. if (animations[index].targetProperty === property) {
  15091. return animations[index];
  15092. }
  15093. }
  15094. return null;
  15095. };
  15096. Animatable.prototype.pause = function () {
  15097. if (this._paused) {
  15098. return;
  15099. }
  15100. this._paused = true;
  15101. };
  15102. Animatable.prototype.restart = function () {
  15103. this._paused = false;
  15104. };
  15105. Animatable.prototype.stop = function () {
  15106. var index = this._scene._activeAnimatables.indexOf(this);
  15107. if (index > -1) {
  15108. this._scene._activeAnimatables.splice(index, 1);
  15109. }
  15110. if (this.onAnimationEnd) {
  15111. this.onAnimationEnd();
  15112. }
  15113. };
  15114. Animatable.prototype._animate = function (delay) {
  15115. if (this._paused) {
  15116. if (!this._pausedDelay) {
  15117. this._pausedDelay = delay;
  15118. }
  15119. return true;
  15120. }
  15121. if (!this._localDelayOffset) {
  15122. this._localDelayOffset = delay;
  15123. } else if (this._pausedDelay) {
  15124. this._localDelayOffset += delay - this._pausedDelay;
  15125. this._pausedDelay = null;
  15126. }
  15127. // Animating
  15128. var running = false;
  15129. var animations = this._animations;
  15130. for (var index = 0; index < animations.length; index++) {
  15131. var animation = animations[index];
  15132. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15133. running = running || isRunning;
  15134. }
  15135. if (!running && this.onAnimationEnd) {
  15136. this.onAnimationEnd();
  15137. }
  15138. return running;
  15139. };
  15140. return Animatable;
  15141. })();
  15142. BABYLON.Animatable = Animatable;
  15143. })(BABYLON || (BABYLON = {}));
  15144. //# sourceMappingURL=babylon.animatable.js.map
  15145. var BABYLON;
  15146. (function (BABYLON) {
  15147. var EasingFunction = (function () {
  15148. function EasingFunction() {
  15149. // Properties
  15150. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15151. }
  15152. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15153. get: function () {
  15154. return EasingFunction._EASINGMODE_EASEIN;
  15155. },
  15156. enumerable: true,
  15157. configurable: true
  15158. });
  15159. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15160. get: function () {
  15161. return EasingFunction._EASINGMODE_EASEOUT;
  15162. },
  15163. enumerable: true,
  15164. configurable: true
  15165. });
  15166. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15167. get: function () {
  15168. return EasingFunction._EASINGMODE_EASEINOUT;
  15169. },
  15170. enumerable: true,
  15171. configurable: true
  15172. });
  15173. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15174. var n = Math.min(Math.max(easingMode, 0), 2);
  15175. this._easingMode = n;
  15176. };
  15177. EasingFunction.prototype.getEasingMode = function () {
  15178. return this._easingMode;
  15179. };
  15180. EasingFunction.prototype.easeInCore = function (gradient) {
  15181. throw new Error('You must implement this method');
  15182. };
  15183. EasingFunction.prototype.ease = function (gradient) {
  15184. switch (this._easingMode) {
  15185. case EasingFunction.EASINGMODE_EASEIN:
  15186. return this.easeInCore(gradient);
  15187. case EasingFunction.EASINGMODE_EASEOUT:
  15188. return (1 - this.easeInCore(1 - gradient));
  15189. }
  15190. if (gradient >= 0.5) {
  15191. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15192. }
  15193. return (this.easeInCore(gradient * 2) * 0.5);
  15194. };
  15195. EasingFunction._EASINGMODE_EASEIN = 0;
  15196. EasingFunction._EASINGMODE_EASEOUT = 1;
  15197. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15198. return EasingFunction;
  15199. })();
  15200. BABYLON.EasingFunction = EasingFunction;
  15201. var CircleEase = (function (_super) {
  15202. __extends(CircleEase, _super);
  15203. function CircleEase() {
  15204. _super.apply(this, arguments);
  15205. }
  15206. CircleEase.prototype.easeInCore = function (gradient) {
  15207. gradient = Math.max(0, Math.min(1, gradient));
  15208. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15209. };
  15210. return CircleEase;
  15211. })(EasingFunction);
  15212. BABYLON.CircleEase = CircleEase;
  15213. var BackEase = (function (_super) {
  15214. __extends(BackEase, _super);
  15215. function BackEase(amplitude) {
  15216. if (typeof amplitude === "undefined") { amplitude = 1; }
  15217. _super.call(this);
  15218. this.amplitude = amplitude;
  15219. }
  15220. BackEase.prototype.easeInCore = function (gradient) {
  15221. var num = Math.max(0, this.amplitude);
  15222. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15223. };
  15224. return BackEase;
  15225. })(EasingFunction);
  15226. BABYLON.BackEase = BackEase;
  15227. var BounceEase = (function (_super) {
  15228. __extends(BounceEase, _super);
  15229. function BounceEase(bounces, bounciness) {
  15230. if (typeof bounces === "undefined") { bounces = 3; }
  15231. if (typeof bounciness === "undefined") { bounciness = 2; }
  15232. _super.call(this);
  15233. this.bounces = bounces;
  15234. this.bounciness = bounciness;
  15235. }
  15236. BounceEase.prototype.easeInCore = function (gradient) {
  15237. var y = Math.max(0.0, this.bounces);
  15238. var bounciness = this.bounciness;
  15239. if (bounciness <= 1.0) {
  15240. bounciness = 1.001;
  15241. }
  15242. var num9 = Math.pow(bounciness, y);
  15243. var num5 = 1.0 - bounciness;
  15244. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15245. var num15 = gradient * num4;
  15246. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15247. var num3 = Math.floor(num65);
  15248. var num13 = num3 + 1.0;
  15249. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15250. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15251. var num7 = (num8 + num12) * 0.5;
  15252. var num6 = gradient - num7;
  15253. var num2 = num7 - num8;
  15254. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15255. };
  15256. return BounceEase;
  15257. })(EasingFunction);
  15258. BABYLON.BounceEase = BounceEase;
  15259. var CubicEase = (function (_super) {
  15260. __extends(CubicEase, _super);
  15261. function CubicEase() {
  15262. _super.apply(this, arguments);
  15263. }
  15264. CubicEase.prototype.easeInCore = function (gradient) {
  15265. return (gradient * gradient * gradient);
  15266. };
  15267. return CubicEase;
  15268. })(EasingFunction);
  15269. BABYLON.CubicEase = CubicEase;
  15270. var ElasticEase = (function (_super) {
  15271. __extends(ElasticEase, _super);
  15272. function ElasticEase(oscillations, springiness) {
  15273. if (typeof oscillations === "undefined") { oscillations = 3; }
  15274. if (typeof springiness === "undefined") { springiness = 3; }
  15275. _super.call(this);
  15276. this.oscillations = oscillations;
  15277. this.springiness = springiness;
  15278. }
  15279. ElasticEase.prototype.easeInCore = function (gradient) {
  15280. var num2;
  15281. var num3 = Math.max(0.0, this.oscillations);
  15282. var num = Math.max(0.0, this.springiness);
  15283. if (num == 0) {
  15284. num2 = gradient;
  15285. } else {
  15286. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15287. }
  15288. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15289. };
  15290. return ElasticEase;
  15291. })(EasingFunction);
  15292. BABYLON.ElasticEase = ElasticEase;
  15293. var ExponentialEase = (function (_super) {
  15294. __extends(ExponentialEase, _super);
  15295. function ExponentialEase(exponent) {
  15296. if (typeof exponent === "undefined") { exponent = 2; }
  15297. _super.call(this);
  15298. this.exponent = exponent;
  15299. }
  15300. ExponentialEase.prototype.easeInCore = function (gradient) {
  15301. if (this.exponent <= 0) {
  15302. return gradient;
  15303. }
  15304. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15305. };
  15306. return ExponentialEase;
  15307. })(EasingFunction);
  15308. BABYLON.ExponentialEase = ExponentialEase;
  15309. var PowerEase = (function (_super) {
  15310. __extends(PowerEase, _super);
  15311. function PowerEase(power) {
  15312. if (typeof power === "undefined") { power = 2; }
  15313. _super.call(this);
  15314. this.power = power;
  15315. }
  15316. PowerEase.prototype.easeInCore = function (gradient) {
  15317. var y = Math.max(0.0, this.power);
  15318. return Math.pow(gradient, y);
  15319. };
  15320. return PowerEase;
  15321. })(EasingFunction);
  15322. BABYLON.PowerEase = PowerEase;
  15323. var QuadraticEase = (function (_super) {
  15324. __extends(QuadraticEase, _super);
  15325. function QuadraticEase() {
  15326. _super.apply(this, arguments);
  15327. }
  15328. QuadraticEase.prototype.easeInCore = function (gradient) {
  15329. return (gradient * gradient);
  15330. };
  15331. return QuadraticEase;
  15332. })(EasingFunction);
  15333. BABYLON.QuadraticEase = QuadraticEase;
  15334. var QuarticEase = (function (_super) {
  15335. __extends(QuarticEase, _super);
  15336. function QuarticEase() {
  15337. _super.apply(this, arguments);
  15338. }
  15339. QuarticEase.prototype.easeInCore = function (gradient) {
  15340. return (gradient * gradient * gradient * gradient);
  15341. };
  15342. return QuarticEase;
  15343. })(EasingFunction);
  15344. BABYLON.QuarticEase = QuarticEase;
  15345. var QuinticEase = (function (_super) {
  15346. __extends(QuinticEase, _super);
  15347. function QuinticEase() {
  15348. _super.apply(this, arguments);
  15349. }
  15350. QuinticEase.prototype.easeInCore = function (gradient) {
  15351. return (gradient * gradient * gradient * gradient * gradient);
  15352. };
  15353. return QuinticEase;
  15354. })(EasingFunction);
  15355. BABYLON.QuinticEase = QuinticEase;
  15356. var SineEase = (function (_super) {
  15357. __extends(SineEase, _super);
  15358. function SineEase() {
  15359. _super.apply(this, arguments);
  15360. }
  15361. SineEase.prototype.easeInCore = function (gradient) {
  15362. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15363. };
  15364. return SineEase;
  15365. })(EasingFunction);
  15366. BABYLON.SineEase = SineEase;
  15367. var BezierCurveEase = (function (_super) {
  15368. __extends(BezierCurveEase, _super);
  15369. function BezierCurveEase(x1, y1, x2, y2) {
  15370. if (typeof x1 === "undefined") { x1 = 0; }
  15371. if (typeof y1 === "undefined") { y1 = 0; }
  15372. if (typeof x2 === "undefined") { x2 = 1; }
  15373. if (typeof y2 === "undefined") { y2 = 1; }
  15374. _super.call(this);
  15375. this.x1 = x1;
  15376. this.y1 = y1;
  15377. this.x2 = x2;
  15378. this.y2 = y2;
  15379. }
  15380. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15381. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15382. };
  15383. return BezierCurveEase;
  15384. })(EasingFunction);
  15385. BABYLON.BezierCurveEase = BezierCurveEase;
  15386. })(BABYLON || (BABYLON = {}));
  15387. //# sourceMappingURL=babylon.easing.js.map
  15388. var BABYLON;
  15389. (function (BABYLON) {
  15390. var Octree = (function () {
  15391. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15392. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  15393. this.maxDepth = maxDepth;
  15394. this.dynamicContent = new Array();
  15395. this._maxBlockCapacity = maxBlockCapacity || 64;
  15396. this._selectionContent = new BABYLON.SmartArray(1024);
  15397. this._creationFunc = creationFunc;
  15398. }
  15399. // Methods
  15400. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15401. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15402. };
  15403. Octree.prototype.addMesh = function (entry) {
  15404. for (var index = 0; index < this.blocks.length; index++) {
  15405. var block = this.blocks[index];
  15406. block.addEntry(entry);
  15407. }
  15408. };
  15409. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15410. this._selectionContent.reset();
  15411. for (var index = 0; index < this.blocks.length; index++) {
  15412. var block = this.blocks[index];
  15413. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15414. }
  15415. if (allowDuplicate) {
  15416. this._selectionContent.concat(this.dynamicContent);
  15417. } else {
  15418. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15419. }
  15420. return this._selectionContent;
  15421. };
  15422. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15423. this._selectionContent.reset();
  15424. for (var index = 0; index < this.blocks.length; index++) {
  15425. var block = this.blocks[index];
  15426. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15427. }
  15428. if (allowDuplicate) {
  15429. this._selectionContent.concat(this.dynamicContent);
  15430. } else {
  15431. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15432. }
  15433. return this._selectionContent;
  15434. };
  15435. Octree.prototype.intersectsRay = function (ray) {
  15436. this._selectionContent.reset();
  15437. for (var index = 0; index < this.blocks.length; index++) {
  15438. var block = this.blocks[index];
  15439. block.intersectsRay(ray, this._selectionContent);
  15440. }
  15441. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15442. return this._selectionContent;
  15443. };
  15444. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15445. target.blocks = new Array();
  15446. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15447. for (var x = 0; x < 2; x++) {
  15448. for (var y = 0; y < 2; y++) {
  15449. for (var z = 0; z < 2; z++) {
  15450. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15451. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15452. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15453. block.addEntries(entries);
  15454. target.blocks.push(block);
  15455. }
  15456. }
  15457. }
  15458. };
  15459. Octree.CreationFuncForMeshes = function (entry, block) {
  15460. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15461. block.entries.push(entry);
  15462. }
  15463. };
  15464. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15465. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15466. block.entries.push(entry);
  15467. }
  15468. };
  15469. return Octree;
  15470. })();
  15471. BABYLON.Octree = Octree;
  15472. })(BABYLON || (BABYLON = {}));
  15473. //# sourceMappingURL=babylon.octree.js.map
  15474. var BABYLON;
  15475. (function (BABYLON) {
  15476. var OctreeBlock = (function () {
  15477. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15478. this.entries = new Array();
  15479. this._boundingVectors = new Array();
  15480. this._capacity = capacity;
  15481. this._depth = depth;
  15482. this._maxDepth = maxDepth;
  15483. this._creationFunc = creationFunc;
  15484. this._minPoint = minPoint;
  15485. this._maxPoint = maxPoint;
  15486. this._boundingVectors.push(minPoint.clone());
  15487. this._boundingVectors.push(maxPoint.clone());
  15488. this._boundingVectors.push(minPoint.clone());
  15489. this._boundingVectors[2].x = maxPoint.x;
  15490. this._boundingVectors.push(minPoint.clone());
  15491. this._boundingVectors[3].y = maxPoint.y;
  15492. this._boundingVectors.push(minPoint.clone());
  15493. this._boundingVectors[4].z = maxPoint.z;
  15494. this._boundingVectors.push(maxPoint.clone());
  15495. this._boundingVectors[5].z = minPoint.z;
  15496. this._boundingVectors.push(maxPoint.clone());
  15497. this._boundingVectors[6].x = minPoint.x;
  15498. this._boundingVectors.push(maxPoint.clone());
  15499. this._boundingVectors[7].y = minPoint.y;
  15500. }
  15501. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15502. // Property
  15503. get: function () {
  15504. return this._capacity;
  15505. },
  15506. enumerable: true,
  15507. configurable: true
  15508. });
  15509. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15510. get: function () {
  15511. return this._minPoint;
  15512. },
  15513. enumerable: true,
  15514. configurable: true
  15515. });
  15516. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15517. get: function () {
  15518. return this._maxPoint;
  15519. },
  15520. enumerable: true,
  15521. configurable: true
  15522. });
  15523. // Methods
  15524. OctreeBlock.prototype.addEntry = function (entry) {
  15525. if (this.blocks) {
  15526. for (var index = 0; index < this.blocks.length; index++) {
  15527. var block = this.blocks[index];
  15528. block.addEntry(entry);
  15529. }
  15530. return;
  15531. }
  15532. this._creationFunc(entry, this);
  15533. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15534. this.createInnerBlocks();
  15535. }
  15536. };
  15537. OctreeBlock.prototype.addEntries = function (entries) {
  15538. for (var index = 0; index < entries.length; index++) {
  15539. var mesh = entries[index];
  15540. this.addEntry(mesh);
  15541. }
  15542. };
  15543. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15544. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15545. if (this.blocks) {
  15546. for (var index = 0; index < this.blocks.length; index++) {
  15547. var block = this.blocks[index];
  15548. block.select(frustumPlanes, selection, allowDuplicate);
  15549. }
  15550. return;
  15551. }
  15552. if (allowDuplicate) {
  15553. selection.concat(this.entries);
  15554. } else {
  15555. selection.concatWithNoDuplicate(this.entries);
  15556. }
  15557. }
  15558. };
  15559. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15560. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15561. if (this.blocks) {
  15562. for (var index = 0; index < this.blocks.length; index++) {
  15563. var block = this.blocks[index];
  15564. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15565. }
  15566. return;
  15567. }
  15568. if (allowDuplicate) {
  15569. selection.concat(this.entries);
  15570. } else {
  15571. selection.concatWithNoDuplicate(this.entries);
  15572. }
  15573. }
  15574. };
  15575. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15576. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15577. if (this.blocks) {
  15578. for (var index = 0; index < this.blocks.length; index++) {
  15579. var block = this.blocks[index];
  15580. block.intersectsRay(ray, selection);
  15581. }
  15582. return;
  15583. }
  15584. selection.concatWithNoDuplicate(this.entries);
  15585. }
  15586. };
  15587. OctreeBlock.prototype.createInnerBlocks = function () {
  15588. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15589. };
  15590. return OctreeBlock;
  15591. })();
  15592. BABYLON.OctreeBlock = OctreeBlock;
  15593. })(BABYLON || (BABYLON = {}));
  15594. //# sourceMappingURL=babylon.octreeBlock.js.map
  15595. var BABYLON;
  15596. (function (BABYLON) {
  15597. var Bone = (function () {
  15598. function Bone(name, skeleton, parentBone, matrix) {
  15599. this.name = name;
  15600. this.children = new Array();
  15601. this.animations = new Array();
  15602. this._worldTransform = new BABYLON.Matrix();
  15603. this._absoluteTransform = new BABYLON.Matrix();
  15604. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15605. this._skeleton = skeleton;
  15606. this._matrix = matrix;
  15607. this._baseMatrix = matrix;
  15608. skeleton.bones.push(this);
  15609. if (parentBone) {
  15610. this._parent = parentBone;
  15611. parentBone.children.push(this);
  15612. } else {
  15613. this._parent = null;
  15614. }
  15615. this._updateDifferenceMatrix();
  15616. }
  15617. // Members
  15618. Bone.prototype.getParent = function () {
  15619. return this._parent;
  15620. };
  15621. Bone.prototype.getLocalMatrix = function () {
  15622. return this._matrix;
  15623. };
  15624. Bone.prototype.getBaseMatrix = function () {
  15625. return this._baseMatrix;
  15626. };
  15627. Bone.prototype.getWorldMatrix = function () {
  15628. return this._worldTransform;
  15629. };
  15630. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15631. return this._invertedAbsoluteTransform;
  15632. };
  15633. Bone.prototype.getAbsoluteMatrix = function () {
  15634. var matrix = this._matrix.clone();
  15635. var parent = this._parent;
  15636. while (parent) {
  15637. matrix = matrix.multiply(parent.getLocalMatrix());
  15638. parent = parent.getParent();
  15639. }
  15640. return matrix;
  15641. };
  15642. // Methods
  15643. Bone.prototype.updateMatrix = function (matrix) {
  15644. this._matrix = matrix;
  15645. this._skeleton._markAsDirty();
  15646. this._updateDifferenceMatrix();
  15647. };
  15648. Bone.prototype._updateDifferenceMatrix = function () {
  15649. if (this._parent) {
  15650. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15651. } else {
  15652. this._absoluteTransform.copyFrom(this._matrix);
  15653. }
  15654. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15655. for (var index = 0; index < this.children.length; index++) {
  15656. this.children[index]._updateDifferenceMatrix();
  15657. }
  15658. };
  15659. Bone.prototype.markAsDirty = function () {
  15660. this._skeleton._markAsDirty();
  15661. };
  15662. return Bone;
  15663. })();
  15664. BABYLON.Bone = Bone;
  15665. })(BABYLON || (BABYLON = {}));
  15666. //# sourceMappingURL=babylon.bone.js.map
  15667. var BABYLON;
  15668. (function (BABYLON) {
  15669. var Skeleton = (function () {
  15670. function Skeleton(name, id, scene) {
  15671. this.name = name;
  15672. this.id = id;
  15673. this.bones = new Array();
  15674. this._isDirty = true;
  15675. this._identity = BABYLON.Matrix.Identity();
  15676. this.bones = [];
  15677. this._scene = scene;
  15678. scene.skeletons.push(this);
  15679. }
  15680. // Members
  15681. Skeleton.prototype.getTransformMatrices = function () {
  15682. return this._transformMatrices;
  15683. };
  15684. // Methods
  15685. Skeleton.prototype._markAsDirty = function () {
  15686. this._isDirty = true;
  15687. };
  15688. Skeleton.prototype.prepare = function () {
  15689. if (!this._isDirty) {
  15690. return;
  15691. }
  15692. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15693. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15694. }
  15695. for (var index = 0; index < this.bones.length; index++) {
  15696. var bone = this.bones[index];
  15697. var parentBone = bone.getParent();
  15698. if (parentBone) {
  15699. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15700. } else {
  15701. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15702. }
  15703. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15704. }
  15705. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15706. this._isDirty = false;
  15707. };
  15708. Skeleton.prototype.getAnimatables = function () {
  15709. if (!this._animatables || this._animatables.length != this.bones.length) {
  15710. this._animatables = [];
  15711. for (var index = 0; index < this.bones.length; index++) {
  15712. this._animatables.push(this.bones[index]);
  15713. }
  15714. }
  15715. return this._animatables;
  15716. };
  15717. Skeleton.prototype.clone = function (name, id) {
  15718. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15719. for (var index = 0; index < this.bones.length; index++) {
  15720. var source = this.bones[index];
  15721. var parentBone = null;
  15722. if (source.getParent()) {
  15723. var parentIndex = this.bones.indexOf(source.getParent());
  15724. parentBone = result.bones[parentIndex];
  15725. }
  15726. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15727. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15728. }
  15729. return result;
  15730. };
  15731. return Skeleton;
  15732. })();
  15733. BABYLON.Skeleton = Skeleton;
  15734. })(BABYLON || (BABYLON = {}));
  15735. //# sourceMappingURL=babylon.skeleton.js.map
  15736. var BABYLON;
  15737. (function (BABYLON) {
  15738. var PostProcess = (function () {
  15739. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15740. this.name = name;
  15741. this.width = -1;
  15742. this.height = -1;
  15743. this._reusable = false;
  15744. this._textures = new BABYLON.SmartArray(2);
  15745. this._currentRenderTextureInd = 0;
  15746. if (camera != null) {
  15747. this._camera = camera;
  15748. this._scene = camera.getScene();
  15749. camera.attachPostProcess(this);
  15750. this._engine = this._scene.getEngine();
  15751. } else {
  15752. this._engine = engine;
  15753. }
  15754. this._renderRatio = ratio;
  15755. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15756. this._reusable = reusable || false;
  15757. samplers = samplers || [];
  15758. samplers.push("textureSampler");
  15759. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15760. }
  15761. PostProcess.prototype.isReusable = function () {
  15762. return this._reusable;
  15763. };
  15764. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15765. camera = camera || this._camera;
  15766. var scene = camera.getScene();
  15767. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15768. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15769. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15770. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15771. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15772. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15773. if (this._textures.length > 0) {
  15774. for (var i = 0; i < this._textures.length; i++) {
  15775. this._engine._releaseTexture(this._textures.data[i]);
  15776. }
  15777. this._textures.reset();
  15778. }
  15779. this.width = desiredWidth;
  15780. this.height = desiredHeight;
  15781. 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 }));
  15782. if (this._reusable) {
  15783. 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 }));
  15784. }
  15785. if (this.onSizeChanged) {
  15786. this.onSizeChanged();
  15787. }
  15788. }
  15789. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15790. if (this.onActivate) {
  15791. this.onActivate(camera);
  15792. }
  15793. // Clear
  15794. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15795. if (this._reusable) {
  15796. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15797. }
  15798. };
  15799. PostProcess.prototype.apply = function () {
  15800. // Check
  15801. if (!this._effect.isReady())
  15802. return null;
  15803. // States
  15804. this._engine.enableEffect(this._effect);
  15805. this._engine.setState(false);
  15806. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15807. this._engine.setDepthBuffer(false);
  15808. this._engine.setDepthWrite(false);
  15809. // Texture
  15810. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15811. // Parameters
  15812. if (this.onApply) {
  15813. this.onApply(this._effect);
  15814. }
  15815. return this._effect;
  15816. };
  15817. PostProcess.prototype.dispose = function (camera) {
  15818. camera = camera || this._camera;
  15819. if (this._textures.length > 0) {
  15820. for (var i = 0; i < this._textures.length; i++) {
  15821. this._engine._releaseTexture(this._textures.data[i]);
  15822. }
  15823. this._textures.reset();
  15824. }
  15825. camera.detachPostProcess(this);
  15826. var index = camera._postProcesses.indexOf(this);
  15827. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15828. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15829. }
  15830. };
  15831. return PostProcess;
  15832. })();
  15833. BABYLON.PostProcess = PostProcess;
  15834. })(BABYLON || (BABYLON = {}));
  15835. //# sourceMappingURL=babylon.postProcess.js.map
  15836. var BABYLON;
  15837. (function (BABYLON) {
  15838. var PostProcessManager = (function () {
  15839. function PostProcessManager(scene) {
  15840. this._vertexDeclaration = [2];
  15841. this._vertexStrideSize = 2 * 4;
  15842. this._scene = scene;
  15843. // VBO
  15844. var vertices = [];
  15845. vertices.push(1, 1);
  15846. vertices.push(-1, 1);
  15847. vertices.push(-1, -1);
  15848. vertices.push(1, -1);
  15849. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15850. // Indices
  15851. var indices = [];
  15852. indices.push(0);
  15853. indices.push(1);
  15854. indices.push(2);
  15855. indices.push(0);
  15856. indices.push(2);
  15857. indices.push(3);
  15858. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15859. }
  15860. // Methods
  15861. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15862. var postProcesses = this._scene.activeCamera._postProcesses;
  15863. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15864. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15865. return false;
  15866. }
  15867. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15868. return true;
  15869. };
  15870. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15871. var postProcesses = this._scene.activeCamera._postProcesses;
  15872. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15873. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15874. return;
  15875. }
  15876. var engine = this._scene.getEngine();
  15877. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15878. if (index < postProcessesTakenIndices.length - 1) {
  15879. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15880. } else {
  15881. if (targetTexture) {
  15882. engine.bindFramebuffer(targetTexture);
  15883. } else {
  15884. engine.restoreDefaultFramebuffer();
  15885. }
  15886. }
  15887. if (doNotPresent) {
  15888. break;
  15889. }
  15890. var pp = postProcesses[postProcessesTakenIndices[index]];
  15891. var effect = pp.apply();
  15892. if (effect) {
  15893. if (pp.onBeforeRender) {
  15894. pp.onBeforeRender(effect);
  15895. }
  15896. // VBOs
  15897. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15898. // Draw order
  15899. engine.draw(true, 0, 6);
  15900. }
  15901. }
  15902. // Restore depth buffer
  15903. engine.setDepthBuffer(true);
  15904. engine.setDepthWrite(true);
  15905. };
  15906. PostProcessManager.prototype.dispose = function () {
  15907. if (this._vertexBuffer) {
  15908. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15909. this._vertexBuffer = null;
  15910. }
  15911. if (this._indexBuffer) {
  15912. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15913. this._indexBuffer = null;
  15914. }
  15915. };
  15916. return PostProcessManager;
  15917. })();
  15918. BABYLON.PostProcessManager = PostProcessManager;
  15919. })(BABYLON || (BABYLON = {}));
  15920. //# sourceMappingURL=babylon.postProcessManager.js.map
  15921. var BABYLON;
  15922. (function (BABYLON) {
  15923. var PassPostProcess = (function (_super) {
  15924. __extends(PassPostProcess, _super);
  15925. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15926. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15927. }
  15928. return PassPostProcess;
  15929. })(BABYLON.PostProcess);
  15930. BABYLON.PassPostProcess = PassPostProcess;
  15931. })(BABYLON || (BABYLON = {}));
  15932. //# sourceMappingURL=babylon.passPostProcess.js.map
  15933. var BABYLON;
  15934. (function (BABYLON) {
  15935. var BlurPostProcess = (function (_super) {
  15936. __extends(BlurPostProcess, _super);
  15937. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15938. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15939. var _this = this;
  15940. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15941. this.direction = direction;
  15942. this.blurWidth = blurWidth;
  15943. this.onApply = function (effect) {
  15944. effect.setFloat2("screenSize", _this.width, _this.height);
  15945. effect.setVector2("direction", _this.direction);
  15946. effect.setFloat("blurWidth", _this.blurWidth);
  15947. };
  15948. }
  15949. return BlurPostProcess;
  15950. })(BABYLON.PostProcess);
  15951. BABYLON.BlurPostProcess = BlurPostProcess;
  15952. })(BABYLON || (BABYLON = {}));
  15953. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15954. var BABYLON;
  15955. (function (BABYLON) {
  15956. var FilterPostProcess = (function (_super) {
  15957. __extends(FilterPostProcess, _super);
  15958. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15959. var _this = this;
  15960. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15961. this.kernelMatrix = kernelMatrix;
  15962. this.onApply = function (effect) {
  15963. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15964. };
  15965. }
  15966. return FilterPostProcess;
  15967. })(BABYLON.PostProcess);
  15968. BABYLON.FilterPostProcess = FilterPostProcess;
  15969. })(BABYLON || (BABYLON = {}));
  15970. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15971. var BABYLON;
  15972. (function (BABYLON) {
  15973. var RefractionPostProcess = (function (_super) {
  15974. __extends(RefractionPostProcess, _super);
  15975. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15976. var _this = this;
  15977. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15978. this.color = color;
  15979. this.depth = depth;
  15980. this.colorLevel = colorLevel;
  15981. this.onActivate = function (cam) {
  15982. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15983. };
  15984. this.onApply = function (effect) {
  15985. effect.setColor3("baseColor", _this.color);
  15986. effect.setFloat("depth", _this.depth);
  15987. effect.setFloat("colorLevel", _this.colorLevel);
  15988. effect.setTexture("refractionSampler", _this._refRexture);
  15989. };
  15990. }
  15991. // Methods
  15992. RefractionPostProcess.prototype.dispose = function (camera) {
  15993. if (this._refRexture) {
  15994. this._refRexture.dispose();
  15995. }
  15996. _super.prototype.dispose.call(this, camera);
  15997. };
  15998. return RefractionPostProcess;
  15999. })(BABYLON.PostProcess);
  16000. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16001. })(BABYLON || (BABYLON = {}));
  16002. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16003. var BABYLON;
  16004. (function (BABYLON) {
  16005. var BlackAndWhitePostProcess = (function (_super) {
  16006. __extends(BlackAndWhitePostProcess, _super);
  16007. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16008. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16009. }
  16010. return BlackAndWhitePostProcess;
  16011. })(BABYLON.PostProcess);
  16012. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16013. })(BABYLON || (BABYLON = {}));
  16014. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16015. var BABYLON;
  16016. (function (BABYLON) {
  16017. var ConvolutionPostProcess = (function (_super) {
  16018. __extends(ConvolutionPostProcess, _super);
  16019. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16020. var _this = this;
  16021. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16022. this.kernel = kernel;
  16023. this.onApply = function (effect) {
  16024. effect.setFloat2("screenSize", _this.width, _this.height);
  16025. effect.setArray("kernel", _this.kernel);
  16026. };
  16027. }
  16028. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16029. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16030. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16031. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16032. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16033. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16034. return ConvolutionPostProcess;
  16035. })(BABYLON.PostProcess);
  16036. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16037. })(BABYLON || (BABYLON = {}));
  16038. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16039. var BABYLON;
  16040. (function (BABYLON) {
  16041. var FxaaPostProcess = (function (_super) {
  16042. __extends(FxaaPostProcess, _super);
  16043. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16044. var _this = this;
  16045. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16046. this.onSizeChanged = function () {
  16047. _this.texelWidth = 1.0 / _this.width;
  16048. _this.texelHeight = 1.0 / _this.height;
  16049. };
  16050. this.onApply = function (effect) {
  16051. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16052. };
  16053. }
  16054. return FxaaPostProcess;
  16055. })(BABYLON.PostProcess);
  16056. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16057. })(BABYLON || (BABYLON = {}));
  16058. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  16059. var BABYLON;
  16060. (function (BABYLON) {
  16061. var LensFlare = (function () {
  16062. function LensFlare(size, position, color, imgUrl, system) {
  16063. this.size = size;
  16064. this.position = position;
  16065. this.dispose = function () {
  16066. if (this.texture) {
  16067. this.texture.dispose();
  16068. }
  16069. // Remove from scene
  16070. var index = this._system.lensFlares.indexOf(this);
  16071. this._system.lensFlares.splice(index, 1);
  16072. };
  16073. this.color = color || new BABYLON.Color3(1, 1, 1);
  16074. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16075. this._system = system;
  16076. system.lensFlares.push(this);
  16077. }
  16078. return LensFlare;
  16079. })();
  16080. BABYLON.LensFlare = LensFlare;
  16081. })(BABYLON || (BABYLON = {}));
  16082. //# sourceMappingURL=babylon.lensFlare.js.map
  16083. var BABYLON;
  16084. (function (BABYLON) {
  16085. var LensFlareSystem = (function () {
  16086. function LensFlareSystem(name, emitter, scene) {
  16087. this.name = name;
  16088. this.lensFlares = new Array();
  16089. this.borderLimit = 300;
  16090. this._vertexDeclaration = [2];
  16091. this._vertexStrideSize = 2 * 4;
  16092. this._isEnabled = true;
  16093. this._scene = scene;
  16094. this._emitter = emitter;
  16095. scene.lensFlareSystems.push(this);
  16096. this.meshesSelectionPredicate = function (m) {
  16097. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  16098. };
  16099. // VBO
  16100. var vertices = [];
  16101. vertices.push(1, 1);
  16102. vertices.push(-1, 1);
  16103. vertices.push(-1, -1);
  16104. vertices.push(1, -1);
  16105. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16106. // Indices
  16107. var indices = [];
  16108. indices.push(0);
  16109. indices.push(1);
  16110. indices.push(2);
  16111. indices.push(0);
  16112. indices.push(2);
  16113. indices.push(3);
  16114. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16115. // Effects
  16116. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16117. }
  16118. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16119. get: function () {
  16120. return this._isEnabled;
  16121. },
  16122. set: function (value) {
  16123. this._isEnabled = value;
  16124. },
  16125. enumerable: true,
  16126. configurable: true
  16127. });
  16128. LensFlareSystem.prototype.getScene = function () {
  16129. return this._scene;
  16130. };
  16131. LensFlareSystem.prototype.getEmitter = function () {
  16132. return this._emitter;
  16133. };
  16134. LensFlareSystem.prototype.getEmitterPosition = function () {
  16135. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16136. };
  16137. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16138. var position = this.getEmitterPosition();
  16139. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16140. this._positionX = position.x;
  16141. this._positionY = position.y;
  16142. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16143. if (position.z > 0) {
  16144. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16145. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16146. return true;
  16147. }
  16148. }
  16149. return false;
  16150. };
  16151. LensFlareSystem.prototype._isVisible = function () {
  16152. if (!this._isEnabled) {
  16153. return false;
  16154. }
  16155. var emitterPosition = this.getEmitterPosition();
  16156. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16157. var distance = direction.length();
  16158. direction.normalize();
  16159. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16160. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16161. return !pickInfo.hit || pickInfo.distance > distance;
  16162. };
  16163. LensFlareSystem.prototype.render = function () {
  16164. if (!this._effect.isReady())
  16165. return false;
  16166. var engine = this._scene.getEngine();
  16167. var viewport = this._scene.activeCamera.viewport;
  16168. var globalViewport = viewport.toGlobal(engine);
  16169. // Position
  16170. if (!this.computeEffectivePosition(globalViewport)) {
  16171. return false;
  16172. }
  16173. // Visibility
  16174. if (!this._isVisible()) {
  16175. return false;
  16176. }
  16177. // Intensity
  16178. var awayX;
  16179. var awayY;
  16180. if (this._positionX < this.borderLimit + globalViewport.x) {
  16181. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16182. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16183. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16184. } else {
  16185. awayX = 0;
  16186. }
  16187. if (this._positionY < this.borderLimit + globalViewport.y) {
  16188. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16189. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16190. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16191. } else {
  16192. awayY = 0;
  16193. }
  16194. var away = (awayX > awayY) ? awayX : awayY;
  16195. if (away > this.borderLimit) {
  16196. away = this.borderLimit;
  16197. }
  16198. var intensity = 1.0 - (away / this.borderLimit);
  16199. if (intensity < 0) {
  16200. return false;
  16201. }
  16202. if (intensity > 1.0) {
  16203. intensity = 1.0;
  16204. }
  16205. // Position
  16206. var centerX = globalViewport.x + globalViewport.width / 2;
  16207. var centerY = globalViewport.y + globalViewport.height / 2;
  16208. var distX = centerX - this._positionX;
  16209. var distY = centerY - this._positionY;
  16210. // Effects
  16211. engine.enableEffect(this._effect);
  16212. engine.setState(false);
  16213. engine.setDepthBuffer(false);
  16214. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16215. // VBOs
  16216. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16217. for (var index = 0; index < this.lensFlares.length; index++) {
  16218. var flare = this.lensFlares[index];
  16219. var x = centerX - (distX * flare.position);
  16220. var y = centerY - (distY * flare.position);
  16221. var cw = flare.size;
  16222. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16223. var cx = 2 * (x / globalViewport.width) - 1.0;
  16224. var cy = 1.0 - 2 * (y / globalViewport.height);
  16225. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16226. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16227. // Texture
  16228. this._effect.setTexture("textureSampler", flare.texture);
  16229. // Color
  16230. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16231. // Draw order
  16232. engine.draw(true, 0, 6);
  16233. }
  16234. engine.setDepthBuffer(true);
  16235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16236. return true;
  16237. };
  16238. LensFlareSystem.prototype.dispose = function () {
  16239. if (this._vertexBuffer) {
  16240. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16241. this._vertexBuffer = null;
  16242. }
  16243. if (this._indexBuffer) {
  16244. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16245. this._indexBuffer = null;
  16246. }
  16247. while (this.lensFlares.length) {
  16248. this.lensFlares[0].dispose();
  16249. }
  16250. // Remove from scene
  16251. var index = this._scene.lensFlareSystems.indexOf(this);
  16252. this._scene.lensFlareSystems.splice(index, 1);
  16253. };
  16254. return LensFlareSystem;
  16255. })();
  16256. BABYLON.LensFlareSystem = LensFlareSystem;
  16257. })(BABYLON || (BABYLON = {}));
  16258. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  16259. var BABYLON;
  16260. (function (BABYLON) {
  16261. var IntersectionInfo = (function () {
  16262. function IntersectionInfo(bu, bv, distance) {
  16263. this.bu = bu;
  16264. this.bv = bv;
  16265. this.distance = distance;
  16266. this.faceId = 0;
  16267. }
  16268. return IntersectionInfo;
  16269. })();
  16270. BABYLON.IntersectionInfo = IntersectionInfo;
  16271. var PickingInfo = (function () {
  16272. function PickingInfo() {
  16273. this.hit = false;
  16274. this.distance = 0;
  16275. this.pickedPoint = null;
  16276. this.pickedMesh = null;
  16277. this.bu = 0;
  16278. this.bv = 0;
  16279. this.faceId = -1;
  16280. }
  16281. // Methods
  16282. PickingInfo.prototype.getNormal = function () {
  16283. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16284. return null;
  16285. }
  16286. var indices = this.pickedMesh.getIndices();
  16287. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16288. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16289. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16290. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16291. normal0 = normal0.scale(this.bu);
  16292. normal1 = normal1.scale(this.bv);
  16293. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16294. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16295. };
  16296. PickingInfo.prototype.getTextureCoordinates = function () {
  16297. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16298. return null;
  16299. }
  16300. var indices = this.pickedMesh.getIndices();
  16301. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16302. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16303. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16304. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16305. uv0 = uv0.scale(this.bu);
  16306. uv1 = uv1.scale(this.bv);
  16307. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16308. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16309. };
  16310. return PickingInfo;
  16311. })();
  16312. BABYLON.PickingInfo = PickingInfo;
  16313. })(BABYLON || (BABYLON = {}));
  16314. //# sourceMappingURL=babylon.pickingInfo.js.map
  16315. var BABYLON;
  16316. (function (BABYLON) {
  16317. var FilesInput = (function () {
  16318. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16319. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16320. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16321. this.engine = p_engine;
  16322. this.canvas = p_canvas;
  16323. this.currentScene = p_scene;
  16324. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16325. this.progressCallback = p_progressCallback;
  16326. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16327. this.textureLoadingCallback = p_textureLoadingCallback;
  16328. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16329. }
  16330. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16331. var _this = this;
  16332. if (p_elementToMonitor) {
  16333. this.elementToMonitor = p_elementToMonitor;
  16334. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16335. _this.drag(e);
  16336. }, false);
  16337. this.elementToMonitor.addEventListener("dragover", function (e) {
  16338. _this.drag(e);
  16339. }, false);
  16340. this.elementToMonitor.addEventListener("drop", function (e) {
  16341. _this.drop(e);
  16342. }, false);
  16343. }
  16344. };
  16345. FilesInput.prototype.renderFunction = function () {
  16346. if (this.additionnalRenderLoopLogicCallback) {
  16347. this.additionnalRenderLoopLogicCallback();
  16348. }
  16349. if (this.currentScene) {
  16350. if (this.textureLoadingCallback) {
  16351. var remaining = this.currentScene.getWaitingItemsCount();
  16352. if (remaining > 0) {
  16353. this.textureLoadingCallback(remaining);
  16354. }
  16355. }
  16356. this.currentScene.render();
  16357. }
  16358. };
  16359. FilesInput.prototype.drag = function (e) {
  16360. e.stopPropagation();
  16361. e.preventDefault();
  16362. };
  16363. FilesInput.prototype.drop = function (eventDrop) {
  16364. eventDrop.stopPropagation();
  16365. eventDrop.preventDefault();
  16366. this.loadFiles(eventDrop);
  16367. };
  16368. FilesInput.prototype.loadFiles = function (event) {
  16369. var _this = this;
  16370. var that = this;
  16371. if (this.startingProcessingFilesCallback)
  16372. this.startingProcessingFilesCallback();
  16373. var sceneFileToLoad;
  16374. var filesToLoad;
  16375. // Handling data transfer via drag'n'drop
  16376. if (event && event.dataTransfer && event.dataTransfer.files) {
  16377. filesToLoad = event.dataTransfer.files;
  16378. }
  16379. // Handling files from input files
  16380. if (event && event.target && event.target.files) {
  16381. filesToLoad = event.target.files;
  16382. }
  16383. if (filesToLoad && filesToLoad.length > 0) {
  16384. for (var i = 0; i < filesToLoad.length; i++) {
  16385. switch (filesToLoad[i].type) {
  16386. case "image/jpeg":
  16387. case "image/png":
  16388. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16389. break;
  16390. case "image/targa":
  16391. case "image/vnd.ms-dds":
  16392. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16393. break;
  16394. default:
  16395. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  16396. sceneFileToLoad = filesToLoad[i];
  16397. }
  16398. break;
  16399. }
  16400. }
  16401. // If a ".babylon" file has been provided
  16402. if (sceneFileToLoad) {
  16403. if (this.currentScene) {
  16404. this.engine.stopRenderLoop();
  16405. this.currentScene.dispose();
  16406. }
  16407. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16408. that.currentScene = newScene;
  16409. // Wait for textures and shaders to be ready
  16410. that.currentScene.executeWhenReady(function () {
  16411. // Attach camera to canvas inputs
  16412. if (that.currentScene.activeCamera) {
  16413. that.currentScene.activeCamera.attachControl(that.canvas);
  16414. }
  16415. if (that.sceneLoadedCallback) {
  16416. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16417. }
  16418. that.engine.runRenderLoop(function () {
  16419. that.renderFunction();
  16420. });
  16421. });
  16422. }, function (progress) {
  16423. if (_this.progressCallback) {
  16424. _this.progressCallback(progress);
  16425. }
  16426. });
  16427. } else {
  16428. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16429. }
  16430. }
  16431. };
  16432. FilesInput.FilesTextures = new Array();
  16433. FilesInput.FilesToLoad = new Array();
  16434. return FilesInput;
  16435. })();
  16436. BABYLON.FilesInput = FilesInput;
  16437. })(BABYLON || (BABYLON = {}));
  16438. //# sourceMappingURL=babylon.filesInput.js.map
  16439. var BABYLON;
  16440. (function (BABYLON) {
  16441. var OimoJSPlugin = (function () {
  16442. function OimoJSPlugin() {
  16443. this._registeredMeshes = [];
  16444. /**
  16445. * Update the body position according to the mesh position
  16446. * @param mesh
  16447. */
  16448. this.updateBodyPosition = function (mesh) {
  16449. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16450. var registeredMesh = this._registeredMeshes[index];
  16451. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16452. var body = registeredMesh.body.body;
  16453. mesh.computeWorldMatrix(true);
  16454. var center = mesh.getBoundingInfo().boundingBox.center;
  16455. body.setPosition(center.x, center.y, center.z);
  16456. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16457. return;
  16458. }
  16459. // Case where the parent has been updated
  16460. if (registeredMesh.mesh.parent === mesh) {
  16461. mesh.computeWorldMatrix(true);
  16462. registeredMesh.mesh.computeWorldMatrix(true);
  16463. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16464. var absoluteRotation = mesh.rotation;
  16465. body = registeredMesh.body.body;
  16466. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16467. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16468. return;
  16469. }
  16470. }
  16471. };
  16472. }
  16473. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16474. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16475. };
  16476. OimoJSPlugin.prototype.initialize = function (iterations) {
  16477. this._world = new OIMO.World();
  16478. this._world.clear();
  16479. };
  16480. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16481. this._world.gravity = gravity;
  16482. };
  16483. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16484. var body = null;
  16485. this.unregisterMesh(mesh);
  16486. mesh.computeWorldMatrix(true);
  16487. switch (impostor) {
  16488. case BABYLON.PhysicsEngine.SphereImpostor:
  16489. var initialRotation = null;
  16490. if (mesh.rotationQuaternion) {
  16491. initialRotation = mesh.rotationQuaternion.clone();
  16492. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16493. mesh.computeWorldMatrix(true);
  16494. }
  16495. var bbox = mesh.getBoundingInfo().boundingBox;
  16496. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16497. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16498. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16499. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16500. // The delta between the mesh position and the mesh bounding box center
  16501. var deltaPosition = mesh.position.subtract(bbox.center);
  16502. // Transform delta position with the rotation
  16503. if (initialRotation) {
  16504. var m = new BABYLON.Matrix();
  16505. initialRotation.toRotationMatrix(m);
  16506. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16507. }
  16508. body = new OIMO.Body({
  16509. type: 'sphere',
  16510. size: [size],
  16511. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16512. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16513. move: options.mass != 0,
  16514. config: [options.mass, options.friction, options.restitution],
  16515. world: this._world
  16516. });
  16517. // Restore rotation
  16518. if (initialRotation) {
  16519. body.setQuaternion(initialRotation);
  16520. }
  16521. this._registeredMeshes.push({
  16522. mesh: mesh,
  16523. body: body,
  16524. delta: deltaPosition
  16525. });
  16526. break;
  16527. case BABYLON.PhysicsEngine.PlaneImpostor:
  16528. case BABYLON.PhysicsEngine.BoxImpostor:
  16529. initialRotation = null;
  16530. if (mesh.rotationQuaternion) {
  16531. initialRotation = mesh.rotationQuaternion.clone();
  16532. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16533. mesh.computeWorldMatrix(true);
  16534. }
  16535. bbox = mesh.getBoundingInfo().boundingBox;
  16536. var min = bbox.minimumWorld;
  16537. var max = bbox.maximumWorld;
  16538. var box = max.subtract(min);
  16539. var sizeX = this._checkWithEpsilon(box.x);
  16540. var sizeY = this._checkWithEpsilon(box.y);
  16541. var sizeZ = this._checkWithEpsilon(box.z);
  16542. // The delta between the mesh position and the mesh boudning box center
  16543. deltaPosition = mesh.position.subtract(bbox.center);
  16544. // Transform delta position with the rotation
  16545. if (initialRotation) {
  16546. m = new BABYLON.Matrix();
  16547. initialRotation.toRotationMatrix(m);
  16548. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16549. }
  16550. body = new OIMO.Body({
  16551. type: 'box',
  16552. size: [sizeX, sizeY, sizeZ],
  16553. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16554. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16555. move: options.mass != 0,
  16556. config: [options.mass, options.friction, options.restitution],
  16557. world: this._world
  16558. });
  16559. if (initialRotation) {
  16560. body.setQuaternion(initialRotation);
  16561. }
  16562. this._registeredMeshes.push({
  16563. mesh: mesh,
  16564. body: body,
  16565. delta: deltaPosition
  16566. });
  16567. break;
  16568. }
  16569. return body;
  16570. };
  16571. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16572. var types = [], sizes = [], positions = [], rotations = [];
  16573. var initialMesh = parts[0].mesh;
  16574. for (var index = 0; index < parts.length; index++) {
  16575. var part = parts[index];
  16576. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16577. types.push(bodyParameters.type);
  16578. sizes.push.apply(sizes, bodyParameters.size);
  16579. positions.push.apply(positions, bodyParameters.pos);
  16580. rotations.push.apply(rotations, bodyParameters.rot);
  16581. }
  16582. var body = new OIMO.Body({
  16583. type: types,
  16584. size: sizes,
  16585. pos: positions,
  16586. rot: rotations,
  16587. move: options.mass != 0,
  16588. config: [options.mass, options.friction, options.restitution],
  16589. world: this._world
  16590. });
  16591. this._registeredMeshes.push({
  16592. mesh: initialMesh,
  16593. body: body
  16594. });
  16595. return body;
  16596. };
  16597. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16598. var bodyParameters = null;
  16599. var mesh = part.mesh;
  16600. switch (part.impostor) {
  16601. case BABYLON.PhysicsEngine.SphereImpostor:
  16602. var bbox = mesh.getBoundingInfo().boundingBox;
  16603. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16604. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16605. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16606. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16607. bodyParameters = {
  16608. type: 'sphere',
  16609. /* bug with oimo : sphere needs 3 sizes in this case */
  16610. size: [size, -1, -1],
  16611. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16612. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16613. };
  16614. break;
  16615. case BABYLON.PhysicsEngine.PlaneImpostor:
  16616. case BABYLON.PhysicsEngine.BoxImpostor:
  16617. bbox = mesh.getBoundingInfo().boundingBox;
  16618. var min = bbox.minimumWorld;
  16619. var max = bbox.maximumWorld;
  16620. var box = max.subtract(min);
  16621. var sizeX = this._checkWithEpsilon(box.x);
  16622. var sizeY = this._checkWithEpsilon(box.y);
  16623. var sizeZ = this._checkWithEpsilon(box.z);
  16624. var relativePosition = mesh.position;
  16625. bodyParameters = {
  16626. type: 'box',
  16627. size: [sizeX, sizeY, sizeZ],
  16628. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16629. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16630. };
  16631. break;
  16632. }
  16633. return bodyParameters;
  16634. };
  16635. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16636. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16637. var registeredMesh = this._registeredMeshes[index];
  16638. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16639. if (registeredMesh.body) {
  16640. this._world.removeRigidBody(registeredMesh.body.body);
  16641. this._unbindBody(registeredMesh.body);
  16642. }
  16643. this._registeredMeshes.splice(index, 1);
  16644. return;
  16645. }
  16646. }
  16647. };
  16648. OimoJSPlugin.prototype._unbindBody = function (body) {
  16649. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16650. var registeredMesh = this._registeredMeshes[index];
  16651. if (registeredMesh.body === body) {
  16652. registeredMesh.body = null;
  16653. }
  16654. }
  16655. };
  16656. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16657. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16658. var registeredMesh = this._registeredMeshes[index];
  16659. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16660. // Get object mass to have a behaviour similar to cannon.js
  16661. var mass = registeredMesh.body.body.massInfo.mass;
  16662. // The force is scaled with the mass of object
  16663. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16664. return;
  16665. }
  16666. }
  16667. };
  16668. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16669. var body1 = null, body2 = null;
  16670. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16671. var registeredMesh = this._registeredMeshes[index];
  16672. if (registeredMesh.mesh === mesh1) {
  16673. body1 = registeredMesh.body.body;
  16674. } else if (registeredMesh.mesh === mesh2) {
  16675. body2 = registeredMesh.body.body;
  16676. }
  16677. }
  16678. if (!body1 || !body2) {
  16679. return false;
  16680. }
  16681. if (!options) {
  16682. options = {};
  16683. }
  16684. new OIMO.Link({
  16685. type: options.type,
  16686. body1: body1,
  16687. body2: body2,
  16688. min: options.min,
  16689. max: options.max,
  16690. axe1: options.axe1,
  16691. axe2: options.axe2,
  16692. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16693. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16694. collision: options.collision,
  16695. spring: options.spring,
  16696. world: this._world
  16697. });
  16698. return true;
  16699. };
  16700. OimoJSPlugin.prototype.dispose = function () {
  16701. this._world.clear();
  16702. while (this._registeredMeshes.length) {
  16703. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16704. }
  16705. };
  16706. OimoJSPlugin.prototype.isSupported = function () {
  16707. return OIMO !== undefined;
  16708. };
  16709. OimoJSPlugin.prototype._getLastShape = function (body) {
  16710. var lastShape = body.shapes;
  16711. while (lastShape.next) {
  16712. lastShape = lastShape.next;
  16713. }
  16714. return lastShape;
  16715. };
  16716. OimoJSPlugin.prototype.runOneStep = function (time) {
  16717. this._world.step();
  16718. // Update the position of all registered meshes
  16719. var i = this._registeredMeshes.length;
  16720. var m;
  16721. while (i--) {
  16722. var body = this._registeredMeshes[i].body.body;
  16723. var mesh = this._registeredMeshes[i].mesh;
  16724. var delta = this._registeredMeshes[i].delta;
  16725. if (!body.sleeping) {
  16726. if (body.shapes.next) {
  16727. var parentShape = this._getLastShape(body);
  16728. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16729. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16730. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16731. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16732. if (!mesh.rotationQuaternion) {
  16733. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16734. }
  16735. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16736. mesh.computeWorldMatrix();
  16737. } else {
  16738. m = body.getMatrix();
  16739. mtx = BABYLON.Matrix.FromArray(m);
  16740. // Body position
  16741. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16742. if (!delta) {
  16743. mesh.position.x = bodyX;
  16744. mesh.position.y = bodyY;
  16745. mesh.position.z = bodyZ;
  16746. } else {
  16747. mesh.position.x = bodyX + delta.x;
  16748. mesh.position.y = bodyY + delta.y;
  16749. mesh.position.z = bodyZ + delta.z;
  16750. }
  16751. if (!mesh.rotationQuaternion) {
  16752. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16753. }
  16754. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16755. mesh.computeWorldMatrix();
  16756. }
  16757. }
  16758. }
  16759. };
  16760. return OimoJSPlugin;
  16761. })();
  16762. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16763. })(BABYLON || (BABYLON = {}));
  16764. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16765. var BABYLON;
  16766. (function (BABYLON) {
  16767. var PhysicsEngine = (function () {
  16768. function PhysicsEngine(plugin) {
  16769. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16770. }
  16771. PhysicsEngine.prototype._initialize = function (gravity) {
  16772. this._currentPlugin.initialize();
  16773. this._setGravity(gravity);
  16774. };
  16775. PhysicsEngine.prototype._runOneStep = function (delta) {
  16776. if (delta > 0.1) {
  16777. delta = 0.1;
  16778. } else if (delta <= 0) {
  16779. delta = 1.0 / 60.0;
  16780. }
  16781. this._currentPlugin.runOneStep(delta);
  16782. };
  16783. PhysicsEngine.prototype._setGravity = function (gravity) {
  16784. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16785. this._currentPlugin.setGravity(this.gravity);
  16786. };
  16787. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16788. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16789. };
  16790. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16791. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16792. };
  16793. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16794. this._currentPlugin.unregisterMesh(mesh);
  16795. };
  16796. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16797. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16798. };
  16799. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16800. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16801. };
  16802. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16803. this._currentPlugin.updateBodyPosition(mesh);
  16804. };
  16805. PhysicsEngine.prototype.dispose = function () {
  16806. this._currentPlugin.dispose();
  16807. };
  16808. PhysicsEngine.prototype.isSupported = function () {
  16809. return this._currentPlugin.isSupported();
  16810. };
  16811. PhysicsEngine.NoImpostor = 0;
  16812. PhysicsEngine.SphereImpostor = 1;
  16813. PhysicsEngine.BoxImpostor = 2;
  16814. PhysicsEngine.PlaneImpostor = 3;
  16815. PhysicsEngine.MeshImpostor = 4;
  16816. PhysicsEngine.CapsuleImpostor = 5;
  16817. PhysicsEngine.ConeImpostor = 6;
  16818. PhysicsEngine.CylinderImpostor = 7;
  16819. PhysicsEngine.ConvexHullImpostor = 8;
  16820. PhysicsEngine.Epsilon = 0.001;
  16821. return PhysicsEngine;
  16822. })();
  16823. BABYLON.PhysicsEngine = PhysicsEngine;
  16824. })(BABYLON || (BABYLON = {}));
  16825. //# sourceMappingURL=babylon.physicsEngine.js.map
  16826. var BABYLON;
  16827. (function (BABYLON) {
  16828. var serializeLight = function (light) {
  16829. var serializationObject = {};
  16830. serializationObject.name = light.name;
  16831. serializationObject.id = light.id;
  16832. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16833. if (light instanceof BABYLON.PointLight) {
  16834. serializationObject.type = 0;
  16835. serializationObject.position = light.position.asArray();
  16836. } else if (light instanceof BABYLON.DirectionalLight) {
  16837. serializationObject.type = 1;
  16838. var directionalLight = light;
  16839. serializationObject.position = directionalLight.position.asArray();
  16840. serializationObject.direction = directionalLight.direction.asArray();
  16841. } else if (light instanceof BABYLON.SpotLight) {
  16842. serializationObject.type = 2;
  16843. var spotLight = light;
  16844. serializationObject.position = spotLight.position.asArray();
  16845. serializationObject.direction = spotLight.position.asArray();
  16846. serializationObject.angle = spotLight.angle;
  16847. serializationObject.exponent = spotLight.exponent;
  16848. } else if (light instanceof BABYLON.HemisphericLight) {
  16849. serializationObject.type = 3;
  16850. var hemisphericLight = light;
  16851. serializationObject.direction = hemisphericLight.direction.asArray();
  16852. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16853. }
  16854. if (light.intensity) {
  16855. serializationObject.intensity = light.intensity;
  16856. }
  16857. serializationObject.range = light.range;
  16858. serializationObject.diffuse = light.diffuse.asArray();
  16859. serializationObject.specular = light.specular.asArray();
  16860. return serializationObject;
  16861. };
  16862. var serializeFresnelParameter = function (fresnelParameter) {
  16863. var serializationObject = {};
  16864. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16865. serializationObject.leftColor = fresnelParameter.leftColor;
  16866. serializationObject.rightColor = fresnelParameter.rightColor;
  16867. serializationObject.bias = fresnelParameter.bias;
  16868. serializationObject.power = fresnelParameter.power;
  16869. return serializationObject;
  16870. };
  16871. var serializeCamera = function (camera) {
  16872. var serializationObject = {};
  16873. serializationObject.name = camera.name;
  16874. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16875. serializationObject.id = camera.id;
  16876. serializationObject.position = camera.position.asArray();
  16877. // Parent
  16878. if (camera.parent) {
  16879. serializationObject.parentId = camera.parent.id;
  16880. }
  16881. // Target
  16882. serializationObject.rotation = camera.rotation.asArray();
  16883. // Locked target
  16884. if (camera.lockedTarget && camera.lockedTarget.id) {
  16885. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16886. }
  16887. serializationObject.fov = camera.fov;
  16888. serializationObject.minZ = camera.minZ;
  16889. serializationObject.maxZ = camera.maxZ;
  16890. serializationObject.speed = camera.speed;
  16891. serializationObject.inertia = camera.inertia;
  16892. serializationObject.checkCollisions = camera.checkCollisions;
  16893. serializationObject.applyGravity = camera.applyGravity;
  16894. if (camera.ellipsoid) {
  16895. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16896. }
  16897. // Animations
  16898. appendAnimations(camera, serializationObject);
  16899. // Layer mask
  16900. serializationObject.layerMask = camera.layerMask;
  16901. return serializationObject;
  16902. };
  16903. var appendAnimations = function (source, destination) {
  16904. if (source.animations) {
  16905. destination.animations = [];
  16906. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16907. var animation = source.animations[animationIndex];
  16908. destination.animations.push(serializeAnimation(animation));
  16909. }
  16910. }
  16911. };
  16912. var serializeAnimation = function (animation) {
  16913. var serializationObject = {};
  16914. serializationObject.name = animation.name;
  16915. serializationObject.property = animation.targetProperty;
  16916. serializationObject.framePerSecond = animation.framePerSecond;
  16917. serializationObject.dataType = animation.dataType;
  16918. serializationObject.loopBehavior = animation.loopMode;
  16919. var dataType = animation.dataType;
  16920. serializationObject.keys = [];
  16921. var keys = animation.getKeys();
  16922. for (var index = 0; index < keys.length; index++) {
  16923. var animationKey = keys[index];
  16924. var key = {};
  16925. key.frame = animationKey.frame;
  16926. switch (dataType) {
  16927. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16928. key.values = [animationKey.value];
  16929. break;
  16930. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16931. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16932. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16933. key.values = animationKey.value.asArray();
  16934. break;
  16935. }
  16936. serializationObject.keys.push(key);
  16937. }
  16938. return serializationObject;
  16939. };
  16940. var serializeMultiMaterial = function (material) {
  16941. var serializationObject = {};
  16942. serializationObject.name = material.name;
  16943. serializationObject.id = material.id;
  16944. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16945. serializationObject.materials = [];
  16946. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16947. var subMat = material.subMaterials[matIndex];
  16948. if (subMat) {
  16949. serializationObject.materials.push(subMat.id);
  16950. } else {
  16951. serializationObject.materials.push(null);
  16952. }
  16953. }
  16954. return serializationObject;
  16955. };
  16956. var serializeMaterial = function (material) {
  16957. var serializationObject = {};
  16958. serializationObject.name = material.name;
  16959. serializationObject.ambient = material.ambientColor.asArray();
  16960. serializationObject.diffuse = material.diffuseColor.asArray();
  16961. serializationObject.specular = material.specularColor.asArray();
  16962. serializationObject.specularPower = material.specularPower;
  16963. serializationObject.emissive = material.emissiveColor.asArray();
  16964. serializationObject.alpha = material.alpha;
  16965. serializationObject.id = material.id;
  16966. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16967. serializationObject.backFaceCulling = material.backFaceCulling;
  16968. if (material.diffuseTexture) {
  16969. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16970. }
  16971. if (material.diffuseFresnelParameters) {
  16972. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16973. }
  16974. if (material.ambientTexture) {
  16975. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16976. }
  16977. if (material.opacityTexture) {
  16978. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16979. }
  16980. if (material.opacityFresnelParameters) {
  16981. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16982. }
  16983. if (material.reflectionTexture) {
  16984. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16985. }
  16986. if (material.reflectionFresnelParameters) {
  16987. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16988. }
  16989. if (material.emissiveTexture) {
  16990. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16991. }
  16992. if (material.emissiveFresnelParameters) {
  16993. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16994. }
  16995. if (material.specularTexture) {
  16996. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16997. }
  16998. if (material.bumpTexture) {
  16999. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17000. }
  17001. return serializationObject;
  17002. };
  17003. var serializeTexture = function (texture) {
  17004. var serializationObject = {};
  17005. if (!texture.name) {
  17006. return null;
  17007. }
  17008. if (texture instanceof BABYLON.CubeTexture) {
  17009. serializationObject.name = texture.name;
  17010. serializationObject.hasAlpha = texture.hasAlpha;
  17011. serializationObject.level = texture.level;
  17012. serializationObject.coordinatesMode = texture.coordinatesMode;
  17013. return serializationObject;
  17014. }
  17015. if (texture instanceof BABYLON.MirrorTexture) {
  17016. var mirrorTexture = texture;
  17017. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17018. serializationObject.renderList = [];
  17019. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17020. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17021. }
  17022. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17023. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  17024. var renderTargetTexture = texture;
  17025. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17026. serializationObject.renderList = [];
  17027. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17028. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17029. }
  17030. }
  17031. var regularTexture = texture;
  17032. serializationObject.name = texture.name;
  17033. serializationObject.hasAlpha = texture.hasAlpha;
  17034. serializationObject.level = texture.level;
  17035. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17036. serializationObject.coordinatesMode = texture.coordinatesMode;
  17037. serializationObject.uOffset = regularTexture.uOffset;
  17038. serializationObject.vOffset = regularTexture.vOffset;
  17039. serializationObject.uScale = regularTexture.uScale;
  17040. serializationObject.vScale = regularTexture.vScale;
  17041. serializationObject.uAng = regularTexture.uAng;
  17042. serializationObject.vAng = regularTexture.vAng;
  17043. serializationObject.wAng = regularTexture.wAng;
  17044. serializationObject.wrapU = texture.wrapU;
  17045. serializationObject.wrapV = texture.wrapV;
  17046. // Animations
  17047. appendAnimations(texture, serializationObject);
  17048. return serializationObject;
  17049. };
  17050. var serializeSkeleton = function (skeleton) {
  17051. var serializationObject = {};
  17052. serializationObject.name = skeleton.name;
  17053. serializationObject.id = skeleton.id;
  17054. serializationObject.bones = [];
  17055. for (var index = 0; index < skeleton.bones.length; index++) {
  17056. var bone = skeleton.bones[index];
  17057. var serializedBone = {
  17058. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17059. name: bone.name,
  17060. matrix: bone.getLocalMatrix().toArray()
  17061. };
  17062. serializationObject.bones.push(serializedBone);
  17063. if (bone.animations && bone.animations.length > 0) {
  17064. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17065. }
  17066. }
  17067. return serializationObject;
  17068. };
  17069. var serializeParticleSystem = function (particleSystem) {
  17070. var serializationObject = {};
  17071. serializationObject.emitterId = particleSystem.emitter.id;
  17072. serializationObject.capacity = particleSystem.getCapacity();
  17073. if (particleSystem.particleTexture) {
  17074. serializationObject.textureName = particleSystem.particleTexture.name;
  17075. }
  17076. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17077. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17078. serializationObject.minSize = particleSystem.minSize;
  17079. serializationObject.maxSize = particleSystem.maxSize;
  17080. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17081. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17082. serializationObject.emitRate = particleSystem.emitRate;
  17083. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17084. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17085. serializationObject.gravity = particleSystem.gravity.asArray();
  17086. serializationObject.direction1 = particleSystem.direction1.asArray();
  17087. serializationObject.direction2 = particleSystem.direction2.asArray();
  17088. serializationObject.color1 = particleSystem.color1.asArray();
  17089. serializationObject.color2 = particleSystem.color2.asArray();
  17090. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17091. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17092. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17093. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17094. serializationObject.blendMode = particleSystem.blendMode;
  17095. return serializationObject;
  17096. };
  17097. var serializeLensFlareSystem = function (lensFlareSystem) {
  17098. var serializationObject = {};
  17099. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17100. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17101. serializationObject.flares = [];
  17102. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17103. var flare = lensFlareSystem.lensFlares[index];
  17104. serializationObject.flares.push({
  17105. size: flare.size,
  17106. position: flare.position,
  17107. color: flare.color.asArray(),
  17108. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17109. });
  17110. }
  17111. return serializationObject;
  17112. };
  17113. var serializeShadowGenerator = function (light) {
  17114. var serializationObject = {};
  17115. var shadowGenerator = light.getShadowGenerator();
  17116. serializationObject.lightId = light.id;
  17117. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17118. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17119. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17120. serializationObject.renderList = [];
  17121. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17122. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17123. serializationObject.renderList.push(mesh.id);
  17124. }
  17125. return serializationObject;
  17126. };
  17127. var serializedGeometries = [];
  17128. var serializeGeometry = function (geometry, serializationGeometries) {
  17129. if (serializedGeometries[geometry.id]) {
  17130. return;
  17131. }
  17132. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17133. serializationGeometries.boxes.push(serializeBox(geometry));
  17134. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17135. serializationGeometries.spheres.push(serializeSphere(geometry));
  17136. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17137. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17138. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17139. serializationGeometries.toruses.push(serializeTorus(geometry));
  17140. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17141. serializationGeometries.grounds.push(serializeGround(geometry));
  17142. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17143. serializationGeometries.planes.push(serializePlane(geometry));
  17144. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17145. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17146. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17147. throw new Error("Unknow primitive type");
  17148. } else {
  17149. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17150. }
  17151. serializedGeometries[geometry.id] = true;
  17152. };
  17153. var serializeGeometryBase = function (geometry) {
  17154. var serializationObject = {};
  17155. serializationObject.id = geometry.id;
  17156. if (BABYLON.Tags.HasTags(geometry)) {
  17157. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17158. }
  17159. return serializationObject;
  17160. };
  17161. var serializeVertexData = function (vertexData) {
  17162. var serializationObject = serializeGeometryBase(vertexData);
  17163. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17164. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17165. }
  17166. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17167. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17168. }
  17169. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17170. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17171. }
  17172. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17173. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17174. }
  17175. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17176. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17177. }
  17178. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17179. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17180. serializationObject.matricesIndices._isExpanded = true;
  17181. }
  17182. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17183. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17184. }
  17185. serializationObject.indices = vertexData.getIndices();
  17186. return serializationObject;
  17187. };
  17188. var serializePrimitive = function (primitive) {
  17189. var serializationObject = serializeGeometryBase(primitive);
  17190. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17191. return serializationObject;
  17192. };
  17193. var serializeBox = function (box) {
  17194. var serializationObject = serializePrimitive(box);
  17195. serializationObject.size = box.size;
  17196. return serializationObject;
  17197. };
  17198. var serializeSphere = function (sphere) {
  17199. var serializationObject = serializePrimitive(sphere);
  17200. serializationObject.segments = sphere.segments;
  17201. serializationObject.diameter = sphere.diameter;
  17202. return serializationObject;
  17203. };
  17204. var serializeCylinder = function (cylinder) {
  17205. var serializationObject = serializePrimitive(cylinder);
  17206. serializationObject.height = cylinder.height;
  17207. serializationObject.diameterTop = cylinder.diameterTop;
  17208. serializationObject.diameterBottom = cylinder.diameterBottom;
  17209. serializationObject.tessellation = cylinder.tessellation;
  17210. return serializationObject;
  17211. };
  17212. var serializeTorus = function (torus) {
  17213. var serializationObject = serializePrimitive(torus);
  17214. serializationObject.diameter = torus.diameter;
  17215. serializationObject.thickness = torus.thickness;
  17216. serializationObject.tessellation = torus.tessellation;
  17217. return serializationObject;
  17218. };
  17219. var serializeGround = function (ground) {
  17220. var serializationObject = serializePrimitive(ground);
  17221. serializationObject.width = ground.width;
  17222. serializationObject.height = ground.height;
  17223. serializationObject.subdivisions = ground.subdivisions;
  17224. return serializationObject;
  17225. };
  17226. var serializePlane = function (plane) {
  17227. var serializationObject = serializePrimitive(plane);
  17228. serializationObject.size = plane.size;
  17229. return serializationObject;
  17230. };
  17231. var serializeTorusKnot = function (torusKnot) {
  17232. var serializationObject = serializePrimitive(torusKnot);
  17233. serializationObject.radius = torusKnot.radius;
  17234. serializationObject.tube = torusKnot.tube;
  17235. serializationObject.radialSegments = torusKnot.radialSegments;
  17236. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17237. serializationObject.p = torusKnot.p;
  17238. serializationObject.q = torusKnot.q;
  17239. return serializationObject;
  17240. };
  17241. var serializeMesh = function (mesh, serializationScene) {
  17242. var serializationObject = {};
  17243. serializationObject.name = mesh.name;
  17244. serializationObject.id = mesh.id;
  17245. if (BABYLON.Tags.HasTags(mesh)) {
  17246. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17247. }
  17248. serializationObject.position = mesh.position.asArray();
  17249. if (mesh.rotationQuaternion) {
  17250. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17251. } else if (mesh.rotation) {
  17252. serializationObject.rotation = mesh.rotation.asArray();
  17253. }
  17254. serializationObject.scaling = mesh.scaling.asArray();
  17255. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17256. serializationObject.isEnabled = mesh.isEnabled();
  17257. serializationObject.isVisible = mesh.isVisible;
  17258. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17259. serializationObject.pickable = mesh.isPickable;
  17260. serializationObject.receiveShadows = mesh.receiveShadows;
  17261. serializationObject.billboardMode = mesh.billboardMode;
  17262. serializationObject.visibility = mesh.visibility;
  17263. serializationObject.checkCollisions = mesh.checkCollisions;
  17264. // Parent
  17265. if (mesh.parent) {
  17266. serializationObject.parentId = mesh.parent.id;
  17267. }
  17268. // Geometry
  17269. var geometry = mesh._geometry;
  17270. if (geometry) {
  17271. var geometryId = geometry.id;
  17272. serializationObject.geometryId = geometryId;
  17273. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17274. // 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
  17275. serializeGeometry(geometry, serializationScene.geometries);
  17276. }
  17277. // SubMeshes
  17278. serializationObject.subMeshes = [];
  17279. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17280. var subMesh = mesh.subMeshes[subIndex];
  17281. serializationObject.subMeshes.push({
  17282. materialIndex: subMesh.materialIndex,
  17283. verticesStart: subMesh.verticesStart,
  17284. verticesCount: subMesh.verticesCount,
  17285. indexStart: subMesh.indexStart,
  17286. indexCount: subMesh.indexCount
  17287. });
  17288. }
  17289. }
  17290. // Material
  17291. if (mesh.material) {
  17292. serializationObject.materialId = mesh.material.id;
  17293. } else {
  17294. mesh.material = null;
  17295. }
  17296. // Skeleton
  17297. if (mesh.skeleton) {
  17298. serializationObject.skeletonId = mesh.skeleton.id;
  17299. }
  17300. // Physics
  17301. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17302. serializationObject.physicsMass = mesh.getPhysicsMass();
  17303. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17304. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17305. switch (mesh.getPhysicsImpostor()) {
  17306. case BABYLON.PhysicsEngine.BoxImpostor:
  17307. serializationObject.physicsImpostor = 1;
  17308. break;
  17309. case BABYLON.PhysicsEngine.SphereImpostor:
  17310. serializationObject.physicsImpostor = 2;
  17311. break;
  17312. }
  17313. }
  17314. // Instances
  17315. serializationObject.instances = [];
  17316. for (var index = 0; index < mesh.instances.length; index++) {
  17317. var instance = mesh.instances[index];
  17318. var serializationInstance = {
  17319. name: instance.name,
  17320. position: instance.position,
  17321. rotation: instance.rotation,
  17322. rotationQuaternion: instance.rotationQuaternion,
  17323. scaling: instance.scaling
  17324. };
  17325. serializationObject.instances.push(serializationInstance);
  17326. // Animations
  17327. appendAnimations(instance, serializationInstance);
  17328. }
  17329. // Animations
  17330. appendAnimations(mesh, serializationObject);
  17331. // Layer mask
  17332. serializationObject.layerMask = mesh.layerMask;
  17333. return serializationObject;
  17334. };
  17335. var SceneSerializer = (function () {
  17336. function SceneSerializer() {
  17337. }
  17338. SceneSerializer.Serialize = function (scene) {
  17339. var serializationObject = {};
  17340. // Scene
  17341. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17342. serializationObject.autoClear = scene.autoClear;
  17343. serializationObject.clearColor = scene.clearColor.asArray();
  17344. serializationObject.ambientColor = scene.ambientColor.asArray();
  17345. serializationObject.gravity = scene.gravity.asArray();
  17346. // Fog
  17347. if (scene.fogMode && scene.fogMode !== 0) {
  17348. serializationObject.fogMode = scene.fogMode;
  17349. serializationObject.fogColor = scene.fogColor.asArray();
  17350. serializationObject.fogStart = scene.fogStart;
  17351. serializationObject.fogEnd = scene.fogEnd;
  17352. serializationObject.fogDensity = scene.fogDensity;
  17353. }
  17354. // Lights
  17355. serializationObject.lights = [];
  17356. for (var index = 0; index < scene.lights.length; index++) {
  17357. var light = scene.lights[index];
  17358. serializationObject.lights.push(serializeLight(light));
  17359. }
  17360. // Cameras
  17361. serializationObject.cameras = [];
  17362. for (index = 0; index < scene.cameras.length; index++) {
  17363. var camera = scene.cameras[index];
  17364. if (camera instanceof BABYLON.FreeCamera) {
  17365. serializationObject.cameras.push(serializeCamera(camera));
  17366. }
  17367. }
  17368. if (scene.activeCamera) {
  17369. serializationObject.activeCameraID = scene.activeCamera.id;
  17370. }
  17371. // Materials
  17372. serializationObject.materials = [];
  17373. serializationObject.multiMaterials = [];
  17374. for (index = 0; index < scene.materials.length; index++) {
  17375. var material = scene.materials[index];
  17376. if (material instanceof BABYLON.StandardMaterial) {
  17377. serializationObject.materials.push(serializeMaterial(material));
  17378. } else if (material instanceof BABYLON.MultiMaterial) {
  17379. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17380. }
  17381. }
  17382. // Skeletons
  17383. serializationObject.skeletons = [];
  17384. for (index = 0; index < scene.skeletons.length; index++) {
  17385. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17386. }
  17387. // Geometries
  17388. serializationObject.geometries = {};
  17389. serializationObject.geometries.boxes = [];
  17390. serializationObject.geometries.spheres = [];
  17391. serializationObject.geometries.cylinders = [];
  17392. serializationObject.geometries.toruses = [];
  17393. serializationObject.geometries.grounds = [];
  17394. serializationObject.geometries.planes = [];
  17395. serializationObject.geometries.torusKnots = [];
  17396. serializationObject.geometries.vertexData = [];
  17397. serializedGeometries = [];
  17398. var geometries = scene.getGeometries();
  17399. for (var index = 0; index < geometries.length; index++) {
  17400. var geometry = geometries[index];
  17401. if (geometry.isReady()) {
  17402. serializeGeometry(geometry, serializationObject.geometries);
  17403. }
  17404. }
  17405. // Meshes
  17406. serializationObject.meshes = [];
  17407. for (index = 0; index < scene.meshes.length; index++) {
  17408. var abstractMesh = scene.meshes[index];
  17409. if (abstractMesh instanceof BABYLON.Mesh) {
  17410. var mesh = abstractMesh;
  17411. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17412. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17413. }
  17414. }
  17415. }
  17416. // Particles Systems
  17417. serializationObject.particleSystems = [];
  17418. for (index = 0; index < scene.particleSystems.length; index++) {
  17419. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17420. }
  17421. // Lens flares
  17422. serializationObject.lensFlareSystems = [];
  17423. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17424. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17425. }
  17426. // Shadows
  17427. serializationObject.shadowGenerators = [];
  17428. for (index = 0; index < scene.lights.length; index++) {
  17429. light = scene.lights[index];
  17430. if (light.getShadowGenerator()) {
  17431. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17432. }
  17433. }
  17434. return serializationObject;
  17435. };
  17436. return SceneSerializer;
  17437. })();
  17438. BABYLON.SceneSerializer = SceneSerializer;
  17439. })(BABYLON || (BABYLON = {}));
  17440. //# sourceMappingURL=babylon.sceneSerializer.js.map
  17441. var BABYLON;
  17442. (function (BABYLON) {
  17443. var SceneLoader = (function () {
  17444. function SceneLoader() {
  17445. }
  17446. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17447. get: function () {
  17448. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17449. },
  17450. set: function (value) {
  17451. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17452. },
  17453. enumerable: true,
  17454. configurable: true
  17455. });
  17456. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17457. get: function () {
  17458. return SceneLoader._ShowLoadingScreen;
  17459. },
  17460. set: function (value) {
  17461. SceneLoader._ShowLoadingScreen = value;
  17462. },
  17463. enumerable: true,
  17464. configurable: true
  17465. });
  17466. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17467. var dotPosition = sceneFilename.lastIndexOf(".");
  17468. var queryStringPosition = sceneFilename.indexOf("?");
  17469. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17470. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17471. var plugin = this._registeredPlugins[index];
  17472. if (plugin.extensions.indexOf(extension) !== -1) {
  17473. return plugin;
  17474. }
  17475. }
  17476. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17477. };
  17478. // Public functions
  17479. SceneLoader.RegisterPlugin = function (plugin) {
  17480. plugin.extensions = plugin.extensions.toLowerCase();
  17481. SceneLoader._registeredPlugins.push(plugin);
  17482. };
  17483. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17484. var manifestChecked = function (success) {
  17485. scene.database = database;
  17486. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17487. var importMeshFromData = function (data) {
  17488. var meshes = [];
  17489. var particleSystems = [];
  17490. var skeletons = [];
  17491. try {
  17492. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17493. if (onerror) {
  17494. onerror(scene, 'unable to load the scene');
  17495. }
  17496. return;
  17497. }
  17498. } catch (e) {
  17499. if (onerror) {
  17500. onerror(scene, e);
  17501. }
  17502. return;
  17503. }
  17504. if (onsuccess) {
  17505. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17506. onsuccess(meshes, particleSystems, skeletons);
  17507. }
  17508. };
  17509. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17510. // Direct load
  17511. importMeshFromData(sceneFilename.substr(5));
  17512. return;
  17513. }
  17514. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17515. importMeshFromData(data);
  17516. }, progressCallBack, database);
  17517. };
  17518. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17519. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17520. };
  17521. /**
  17522. * Load a scene
  17523. * @param rootUrl a string that defines the root url for scene and resources
  17524. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17525. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17526. */
  17527. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17528. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17529. };
  17530. /**
  17531. * Append a scene
  17532. * @param rootUrl a string that defines the root url for scene and resources
  17533. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17534. * @param scene is the instance of BABYLON.Scene to append to
  17535. */
  17536. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17537. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17538. var database;
  17539. if (SceneLoader.ShowLoadingScreen) {
  17540. scene.getEngine().displayLoadingUI();
  17541. }
  17542. var loadSceneFromData = function (data) {
  17543. scene.database = database;
  17544. if (!plugin.load(scene, data, rootUrl)) {
  17545. if (onerror) {
  17546. onerror(scene);
  17547. }
  17548. scene.getEngine().hideLoadingUI();
  17549. return;
  17550. }
  17551. if (onsuccess) {
  17552. onsuccess(scene);
  17553. }
  17554. if (SceneLoader.ShowLoadingScreen) {
  17555. scene.executeWhenReady(function () {
  17556. scene.getEngine().hideLoadingUI();
  17557. });
  17558. }
  17559. };
  17560. var manifestChecked = function (success) {
  17561. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17562. };
  17563. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17564. // Direct load
  17565. loadSceneFromData(sceneFilename.substr(5));
  17566. return;
  17567. }
  17568. if (rootUrl.indexOf("file:") === -1) {
  17569. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17570. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17571. } else {
  17572. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17573. }
  17574. };
  17575. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17576. SceneLoader._ShowLoadingScreen = true;
  17577. SceneLoader._registeredPlugins = new Array();
  17578. return SceneLoader;
  17579. })();
  17580. BABYLON.SceneLoader = SceneLoader;
  17581. ;
  17582. })(BABYLON || (BABYLON = {}));
  17583. //# sourceMappingURL=babylon.sceneLoader.js.map
  17584. var BABYLON;
  17585. (function (BABYLON) {
  17586. (function (Internals) {
  17587. var checkColors4 = function (colors, count) {
  17588. // Check if color3 was used
  17589. if (colors.length === count * 3) {
  17590. var colors4 = [];
  17591. for (var index = 0; index < colors.length; index += 3) {
  17592. var newIndex = (index / 3) * 4;
  17593. colors4[newIndex] = colors[index];
  17594. colors4[newIndex + 1] = colors[index + 1];
  17595. colors4[newIndex + 2] = colors[index + 2];
  17596. colors4[newIndex + 3] = 1.0;
  17597. }
  17598. return colors4;
  17599. }
  17600. return colors;
  17601. };
  17602. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17603. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17604. texture.name = parsedTexture.name;
  17605. texture.hasAlpha = parsedTexture.hasAlpha;
  17606. texture.level = parsedTexture.level;
  17607. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17608. return texture;
  17609. };
  17610. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17611. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17612. return null;
  17613. }
  17614. if (parsedTexture.isCube) {
  17615. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17616. }
  17617. var texture;
  17618. if (parsedTexture.mirrorPlane) {
  17619. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17620. texture._waitingRenderList = parsedTexture.renderList;
  17621. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17622. } else if (parsedTexture.isRenderTarget) {
  17623. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17624. texture._waitingRenderList = parsedTexture.renderList;
  17625. } else {
  17626. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17627. }
  17628. texture.name = parsedTexture.name;
  17629. texture.hasAlpha = parsedTexture.hasAlpha;
  17630. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17631. texture.level = parsedTexture.level;
  17632. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17633. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17634. texture.uOffset = parsedTexture.uOffset;
  17635. texture.vOffset = parsedTexture.vOffset;
  17636. texture.uScale = parsedTexture.uScale;
  17637. texture.vScale = parsedTexture.vScale;
  17638. texture.uAng = parsedTexture.uAng;
  17639. texture.vAng = parsedTexture.vAng;
  17640. texture.wAng = parsedTexture.wAng;
  17641. texture.wrapU = parsedTexture.wrapU;
  17642. texture.wrapV = parsedTexture.wrapV;
  17643. // Animations
  17644. if (parsedTexture.animations) {
  17645. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17646. var parsedAnimation = parsedTexture.animations[animationIndex];
  17647. texture.animations.push(parseAnimation(parsedAnimation));
  17648. }
  17649. }
  17650. return texture;
  17651. };
  17652. var parseSkeleton = function (parsedSkeleton, scene) {
  17653. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17654. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17655. var parsedBone = parsedSkeleton.bones[index];
  17656. var parentBone = null;
  17657. if (parsedBone.parentBoneIndex > -1) {
  17658. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17659. }
  17660. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17661. if (parsedBone.animation) {
  17662. bone.animations.push(parseAnimation(parsedBone.animation));
  17663. }
  17664. }
  17665. return skeleton;
  17666. };
  17667. var parseFresnelParameters = function (parsedFresnelParameters) {
  17668. var fresnelParameters = new BABYLON.FresnelParameters();
  17669. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17670. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17671. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17672. fresnelParameters.bias = parsedFresnelParameters.bias;
  17673. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17674. return fresnelParameters;
  17675. };
  17676. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17677. var material;
  17678. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17679. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17680. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17681. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17682. material.specularPower = parsedMaterial.specularPower;
  17683. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17684. material.alpha = parsedMaterial.alpha;
  17685. material.id = parsedMaterial.id;
  17686. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17687. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17688. material.wireframe = parsedMaterial.wireframe;
  17689. if (parsedMaterial.diffuseTexture) {
  17690. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17691. }
  17692. if (parsedMaterial.diffuseFresnelParameters) {
  17693. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17694. }
  17695. if (parsedMaterial.ambientTexture) {
  17696. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17697. }
  17698. if (parsedMaterial.opacityTexture) {
  17699. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17700. }
  17701. if (parsedMaterial.opacityFresnelParameters) {
  17702. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17703. }
  17704. if (parsedMaterial.reflectionTexture) {
  17705. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17706. }
  17707. if (parsedMaterial.reflectionFresnelParameters) {
  17708. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17709. }
  17710. if (parsedMaterial.emissiveTexture) {
  17711. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17712. }
  17713. if (parsedMaterial.emissiveFresnelParameters) {
  17714. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17715. }
  17716. if (parsedMaterial.specularTexture) {
  17717. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17718. }
  17719. if (parsedMaterial.bumpTexture) {
  17720. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17721. }
  17722. return material;
  17723. };
  17724. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17725. for (var index = 0; index < parsedData.materials.length; index++) {
  17726. var parsedMaterial = parsedData.materials[index];
  17727. if (parsedMaterial.id === id) {
  17728. return parseMaterial(parsedMaterial, scene, rootUrl);
  17729. }
  17730. }
  17731. return null;
  17732. };
  17733. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17734. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17735. multiMaterial.id = parsedMultiMaterial.id;
  17736. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17737. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17738. var subMatId = parsedMultiMaterial.materials[matIndex];
  17739. if (subMatId) {
  17740. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17741. } else {
  17742. multiMaterial.subMaterials.push(null);
  17743. }
  17744. }
  17745. return multiMaterial;
  17746. };
  17747. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17748. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17749. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17750. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17751. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17752. var parsedFlare = parsedLensFlareSystem.flares[index];
  17753. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17754. }
  17755. return lensFlareSystem;
  17756. };
  17757. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17758. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17759. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17760. if (parsedParticleSystem.textureName) {
  17761. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17762. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17763. }
  17764. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17765. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17766. particleSystem.minSize = parsedParticleSystem.minSize;
  17767. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17768. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17769. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17770. particleSystem.emitter = emitter;
  17771. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17772. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17773. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17774. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17775. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17776. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17777. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17778. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17779. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17780. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17781. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17782. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17783. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17784. particleSystem.start();
  17785. return particleSystem;
  17786. };
  17787. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17788. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17789. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17790. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17791. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17792. shadowGenerator.getShadowMap().renderList.push(mesh);
  17793. }
  17794. if (parsedShadowGenerator.usePoissonSampling) {
  17795. shadowGenerator.usePoissonSampling = true;
  17796. } else {
  17797. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17798. }
  17799. return shadowGenerator;
  17800. };
  17801. var parseAnimation = function (parsedAnimation) {
  17802. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17803. var dataType = parsedAnimation.dataType;
  17804. var keys = [];
  17805. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17806. var key = parsedAnimation.keys[index];
  17807. var data;
  17808. switch (dataType) {
  17809. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17810. data = key.values[0];
  17811. break;
  17812. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17813. data = BABYLON.Quaternion.FromArray(key.values);
  17814. break;
  17815. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17816. data = BABYLON.Matrix.FromArray(key.values);
  17817. break;
  17818. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17819. default:
  17820. data = BABYLON.Vector3.FromArray(key.values);
  17821. break;
  17822. }
  17823. keys.push({
  17824. frame: key.frame,
  17825. value: data
  17826. });
  17827. }
  17828. animation.setKeys(keys);
  17829. return animation;
  17830. };
  17831. var parseLight = function (parsedLight, scene) {
  17832. var light;
  17833. switch (parsedLight.type) {
  17834. case 0:
  17835. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17836. break;
  17837. case 1:
  17838. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17839. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17840. break;
  17841. case 2:
  17842. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17843. break;
  17844. case 3:
  17845. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17846. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17847. break;
  17848. }
  17849. light.id = parsedLight.id;
  17850. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17851. if (parsedLight.intensity !== undefined) {
  17852. light.intensity = parsedLight.intensity;
  17853. }
  17854. if (parsedLight.range) {
  17855. light.range = parsedLight.range;
  17856. }
  17857. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17858. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17859. if (parsedLight.excludedMeshesIds) {
  17860. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17861. }
  17862. // Parent
  17863. if (parsedLight.parentId) {
  17864. light._waitingParentId = parsedLight.parentId;
  17865. }
  17866. if (parsedLight.includedOnlyMeshesIds) {
  17867. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17868. }
  17869. // Animations
  17870. if (parsedLight.animations) {
  17871. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17872. var parsedAnimation = parsedLight.animations[animationIndex];
  17873. light.animations.push(parseAnimation(parsedAnimation));
  17874. }
  17875. }
  17876. if (parsedLight.autoAnimate) {
  17877. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17878. }
  17879. };
  17880. var parseCamera = function (parsedCamera, scene) {
  17881. var camera;
  17882. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17883. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17884. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17885. var alpha = parsedCamera.alpha;
  17886. var beta = parsedCamera.beta;
  17887. var radius = parsedCamera.radius;
  17888. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17889. var eye_space = parsedCamera.eye_space;
  17890. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17891. } else {
  17892. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17893. }
  17894. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17895. eye_space = parsedCamera.eye_space;
  17896. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17897. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17898. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17899. } else if (parsedCamera.type === "FollowCamera") {
  17900. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17901. camera.heightOffset = parsedCamera.heightOffset;
  17902. camera.radius = parsedCamera.radius;
  17903. camera.rotationOffset = parsedCamera.rotationOffset;
  17904. if (lockedTargetMesh)
  17905. camera.target = lockedTargetMesh;
  17906. } else if (parsedCamera.type === "GamepadCamera") {
  17907. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17908. } else if (parsedCamera.type === "OculusCamera") {
  17909. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17910. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17911. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17912. } else if (parsedCamera.type === "TouchCamera") {
  17913. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17914. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17915. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17916. } else if (parsedCamera.type === "WebVRCamera") {
  17917. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17918. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17919. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17920. } else {
  17921. // Free Camera is the default value
  17922. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17923. }
  17924. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17925. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17926. camera.lockedTarget = lockedTargetMesh;
  17927. }
  17928. camera.id = parsedCamera.id;
  17929. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17930. // Parent
  17931. if (parsedCamera.parentId) {
  17932. camera._waitingParentId = parsedCamera.parentId;
  17933. }
  17934. // Target
  17935. if (parsedCamera.target) {
  17936. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17937. } else {
  17938. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17939. }
  17940. camera.fov = parsedCamera.fov;
  17941. camera.minZ = parsedCamera.minZ;
  17942. camera.maxZ = parsedCamera.maxZ;
  17943. camera.speed = parsedCamera.speed;
  17944. camera.inertia = parsedCamera.inertia;
  17945. camera.checkCollisions = parsedCamera.checkCollisions;
  17946. camera.applyGravity = parsedCamera.applyGravity;
  17947. if (parsedCamera.ellipsoid) {
  17948. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17949. }
  17950. // Animations
  17951. if (parsedCamera.animations) {
  17952. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17953. var parsedAnimation = parsedCamera.animations[animationIndex];
  17954. camera.animations.push(parseAnimation(parsedAnimation));
  17955. }
  17956. }
  17957. if (parsedCamera.autoAnimate) {
  17958. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17959. }
  17960. // Layer Mask
  17961. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17962. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17963. } else {
  17964. camera.layerMask = 0xFFFFFFFF;
  17965. }
  17966. return camera;
  17967. };
  17968. var parseGeometry = function (parsedGeometry, scene) {
  17969. var id = parsedGeometry.id;
  17970. return scene.getGeometryByID(id);
  17971. };
  17972. var parseBox = function (parsedBox, scene) {
  17973. if (parseGeometry(parsedBox, scene)) {
  17974. return null;
  17975. }
  17976. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17977. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17978. scene.pushGeometry(box, true);
  17979. return box;
  17980. };
  17981. var parseSphere = function (parsedSphere, scene) {
  17982. if (parseGeometry(parsedSphere, scene)) {
  17983. return null;
  17984. }
  17985. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17986. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17987. scene.pushGeometry(sphere, true);
  17988. return sphere;
  17989. };
  17990. var parseCylinder = function (parsedCylinder, scene) {
  17991. if (parseGeometry(parsedCylinder, scene)) {
  17992. return null;
  17993. }
  17994. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17995. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17996. scene.pushGeometry(cylinder, true);
  17997. return cylinder;
  17998. };
  17999. var parseTorus = function (parsedTorus, scene) {
  18000. if (parseGeometry(parsedTorus, scene)) {
  18001. return null;
  18002. }
  18003. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18004. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18005. scene.pushGeometry(torus, true);
  18006. return torus;
  18007. };
  18008. var parseGround = function (parsedGround, scene) {
  18009. if (parseGeometry(parsedGround, scene)) {
  18010. return null;
  18011. }
  18012. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18013. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18014. scene.pushGeometry(ground, true);
  18015. return ground;
  18016. };
  18017. var parsePlane = function (parsedPlane, scene) {
  18018. if (parseGeometry(parsedPlane, scene)) {
  18019. return null;
  18020. }
  18021. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18022. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18023. scene.pushGeometry(plane, true);
  18024. return plane;
  18025. };
  18026. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18027. if (parseGeometry(parsedTorusKnot, scene)) {
  18028. return null;
  18029. }
  18030. 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);
  18031. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18032. scene.pushGeometry(torusKnot, true);
  18033. return torusKnot;
  18034. };
  18035. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18036. if (parseGeometry(parsedVertexData, scene)) {
  18037. return null;
  18038. }
  18039. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18040. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18041. if (parsedVertexData.delayLoadingFile) {
  18042. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18043. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18044. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18045. geometry._delayInfo = [];
  18046. if (parsedVertexData.hasUVs) {
  18047. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18048. }
  18049. if (parsedVertexData.hasUVs2) {
  18050. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18051. }
  18052. if (parsedVertexData.hasColors) {
  18053. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18054. }
  18055. if (parsedVertexData.hasMatricesIndices) {
  18056. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18057. }
  18058. if (parsedVertexData.hasMatricesWeights) {
  18059. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18060. }
  18061. geometry._delayLoadingFunction = importVertexData;
  18062. } else {
  18063. importVertexData(parsedVertexData, geometry);
  18064. }
  18065. scene.pushGeometry(geometry, true);
  18066. return geometry;
  18067. };
  18068. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18069. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18070. mesh.id = parsedMesh.id;
  18071. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18072. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18073. if (parsedMesh.rotationQuaternion) {
  18074. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18075. } else if (parsedMesh.rotation) {
  18076. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18077. }
  18078. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18079. if (parsedMesh.localMatrix) {
  18080. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18081. } else if (parsedMesh.pivotMatrix) {
  18082. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18083. }
  18084. mesh.setEnabled(parsedMesh.isEnabled);
  18085. mesh.isVisible = parsedMesh.isVisible;
  18086. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18087. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18088. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18089. if (parsedMesh.applyFog !== undefined) {
  18090. mesh.applyFog = parsedMesh.applyFog;
  18091. }
  18092. if (parsedMesh.pickable !== undefined) {
  18093. mesh.isPickable = parsedMesh.pickable;
  18094. }
  18095. if (parsedMesh.alphaIndex !== undefined) {
  18096. mesh.alphaIndex = parsedMesh.alphaIndex;
  18097. }
  18098. mesh.receiveShadows = parsedMesh.receiveShadows;
  18099. mesh.billboardMode = parsedMesh.billboardMode;
  18100. if (parsedMesh.visibility !== undefined) {
  18101. mesh.visibility = parsedMesh.visibility;
  18102. }
  18103. mesh.checkCollisions = parsedMesh.checkCollisions;
  18104. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18105. // Parent
  18106. if (parsedMesh.parentId) {
  18107. mesh._waitingParentId = parsedMesh.parentId;
  18108. }
  18109. // Actions
  18110. if (parsedMesh.actions !== undefined) {
  18111. mesh._waitingActions = parsedMesh.actions;
  18112. }
  18113. // Geometry
  18114. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18115. if (parsedMesh.delayLoadingFile) {
  18116. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18117. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18118. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18119. if (parsedMesh._binaryInfo) {
  18120. mesh._binaryInfo = parsedMesh._binaryInfo;
  18121. }
  18122. mesh._delayInfo = [];
  18123. if (parsedMesh.hasUVs) {
  18124. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18125. }
  18126. if (parsedMesh.hasUVs2) {
  18127. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18128. }
  18129. if (parsedMesh.hasColors) {
  18130. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18131. }
  18132. if (parsedMesh.hasMatricesIndices) {
  18133. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18134. }
  18135. if (parsedMesh.hasMatricesWeights) {
  18136. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18137. }
  18138. mesh._delayLoadingFunction = importGeometry;
  18139. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18140. mesh._checkDelayState();
  18141. }
  18142. } else {
  18143. importGeometry(parsedMesh, mesh);
  18144. }
  18145. // Material
  18146. if (parsedMesh.materialId) {
  18147. mesh.setMaterialByID(parsedMesh.materialId);
  18148. } else {
  18149. mesh.material = null;
  18150. }
  18151. // Skeleton
  18152. if (parsedMesh.skeletonId > -1) {
  18153. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18154. }
  18155. // Physics
  18156. if (parsedMesh.physicsImpostor) {
  18157. if (!scene.isPhysicsEnabled()) {
  18158. scene.enablePhysics();
  18159. }
  18160. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18161. }
  18162. // Animations
  18163. if (parsedMesh.animations) {
  18164. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18165. var parsedAnimation = parsedMesh.animations[animationIndex];
  18166. mesh.animations.push(parseAnimation(parsedAnimation));
  18167. }
  18168. }
  18169. if (parsedMesh.autoAnimate) {
  18170. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18171. }
  18172. // Layer Mask
  18173. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18174. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18175. } else {
  18176. mesh.layerMask = 0xFFFFFFFF;
  18177. }
  18178. // Instances
  18179. if (parsedMesh.instances) {
  18180. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18181. var parsedInstance = parsedMesh.instances[index];
  18182. var instance = mesh.createInstance(parsedInstance.name);
  18183. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18184. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18185. if (parsedInstance.rotationQuaternion) {
  18186. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18187. } else if (parsedInstance.rotation) {
  18188. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18189. }
  18190. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18191. instance.checkCollisions = mesh.checkCollisions;
  18192. if (parsedMesh.animations) {
  18193. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18194. parsedAnimation = parsedMesh.animations[animationIndex];
  18195. instance.animations.push(parseAnimation(parsedAnimation));
  18196. }
  18197. }
  18198. }
  18199. }
  18200. return mesh;
  18201. };
  18202. var parseActions = function (parsedActions, object, scene) {
  18203. var actionManager = new BABYLON.ActionManager(scene);
  18204. if (object === null)
  18205. scene.actionManager = actionManager;
  18206. else
  18207. object.actionManager = actionManager;
  18208. // instanciate a new object
  18209. var instanciate = function (name, params) {
  18210. var newInstance = Object.create(BABYLON[name].prototype);
  18211. newInstance.constructor.apply(newInstance, params);
  18212. return newInstance;
  18213. };
  18214. var parseParameter = function (name, value, target, propertyPath) {
  18215. if (propertyPath === null) {
  18216. // String, boolean or float
  18217. var floatValue = parseFloat(value);
  18218. if (value === "true" || value === "false")
  18219. return value === "true";
  18220. else
  18221. return isNaN(floatValue) ? value : floatValue;
  18222. }
  18223. var effectiveTarget = propertyPath.split(".");
  18224. var values = value.split(",");
  18225. for (var i = 0; i < effectiveTarget.length; i++) {
  18226. target = target[effectiveTarget[i]];
  18227. }
  18228. // Return appropriate value with its type
  18229. if (target instanceof Boolean)
  18230. return values[0] === "true";
  18231. if (target instanceof String)
  18232. return values[0];
  18233. // Parameters with multiple values such as Vector3 etc.
  18234. var split = new Array();
  18235. for (var i = 0; i < values.length; i++)
  18236. split.push(parseFloat(values[i]));
  18237. if (target instanceof BABYLON.Vector3)
  18238. return BABYLON.Vector3.FromArray(split);
  18239. if (target instanceof BABYLON.Vector4)
  18240. return BABYLON.Vector4.FromArray(split);
  18241. if (target instanceof BABYLON.Color3)
  18242. return BABYLON.Color3.FromArray(split);
  18243. if (target instanceof BABYLON.Color4)
  18244. return BABYLON.Color4.FromArray(split);
  18245. return parseFloat(values[0]);
  18246. };
  18247. // traverse graph per trigger
  18248. var traverse = function (parsedAction, trigger, condition, action) {
  18249. var parameters = new Array();
  18250. var target = null;
  18251. var propertyPath = null;
  18252. // Parameters
  18253. if (parsedAction.type === 2)
  18254. parameters.push(actionManager);
  18255. else
  18256. parameters.push(trigger);
  18257. for (var i = 0; i < parsedAction.properties.length; i++) {
  18258. var value = parsedAction.properties[i].value;
  18259. var name = parsedAction.properties[i].name;
  18260. if (name === "target")
  18261. value = target = scene.getNodeByName(value);
  18262. else if (name === "parent")
  18263. value = scene.getNodeByName(value);
  18264. else if (name !== "propertyPath") {
  18265. if (parsedAction.type === 2 && name === "operator")
  18266. value = BABYLON.ValueCondition[value];
  18267. else
  18268. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18269. } else {
  18270. propertyPath = value;
  18271. }
  18272. parameters.push(value);
  18273. }
  18274. parameters.push(condition);
  18275. // If interpolate value action
  18276. if (parsedAction.name === "InterpolateValueAction") {
  18277. var param = parameters[parameters.length - 2];
  18278. parameters[parameters.length - 1] = param;
  18279. parameters[parameters.length - 2] = condition;
  18280. }
  18281. // Action or condition(s)
  18282. var newAction = instanciate(parsedAction.name, parameters);
  18283. if (newAction instanceof BABYLON.Condition) {
  18284. condition = newAction;
  18285. newAction = action;
  18286. } else {
  18287. condition = null;
  18288. if (action)
  18289. action.then(newAction);
  18290. else
  18291. actionManager.registerAction(newAction);
  18292. }
  18293. for (var i = 0; i < parsedAction.children.length; i++)
  18294. traverse(parsedAction.children[i], trigger, condition, newAction);
  18295. };
  18296. for (var i = 0; i < parsedActions.children.length; i++) {
  18297. var triggerParams;
  18298. var trigger = parsedActions.children[i];
  18299. if (trigger.properties.length > 0) {
  18300. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18301. } else
  18302. triggerParams = BABYLON.ActionManager[trigger.name];
  18303. for (var j = 0; j < trigger.children.length; j++)
  18304. traverse(trigger.children[j], triggerParams, null, null);
  18305. }
  18306. };
  18307. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18308. names = (names instanceof Array) ? names : [names];
  18309. for (var i in names) {
  18310. if (mesh.name === names[i]) {
  18311. hierarchyIds.push(mesh.id);
  18312. return true;
  18313. }
  18314. }
  18315. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18316. hierarchyIds.push(mesh.id);
  18317. return true;
  18318. }
  18319. return false;
  18320. };
  18321. var importVertexData = function (parsedVertexData, geometry) {
  18322. var vertexData = new BABYLON.VertexData();
  18323. // positions
  18324. var positions = parsedVertexData.positions;
  18325. if (positions) {
  18326. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18327. }
  18328. // normals
  18329. var normals = parsedVertexData.normals;
  18330. if (normals) {
  18331. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18332. }
  18333. // uvs
  18334. var uvs = parsedVertexData.uvs;
  18335. if (uvs) {
  18336. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18337. }
  18338. // uv2s
  18339. var uv2s = parsedVertexData.uv2s;
  18340. if (uv2s) {
  18341. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18342. }
  18343. // colors
  18344. var colors = parsedVertexData.colors;
  18345. if (colors) {
  18346. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18347. }
  18348. // matricesIndices
  18349. var matricesIndices = parsedVertexData.matricesIndices;
  18350. if (matricesIndices) {
  18351. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18352. }
  18353. // matricesWeights
  18354. var matricesWeights = parsedVertexData.matricesWeights;
  18355. if (matricesWeights) {
  18356. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18357. }
  18358. // indices
  18359. var indices = parsedVertexData.indices;
  18360. if (indices) {
  18361. vertexData.indices = indices;
  18362. }
  18363. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18364. };
  18365. var importGeometry = function (parsedGeometry, mesh) {
  18366. var scene = mesh.getScene();
  18367. // Geometry
  18368. var geometryId = parsedGeometry.geometryId;
  18369. if (geometryId) {
  18370. var geometry = scene.getGeometryByID(geometryId);
  18371. if (geometry) {
  18372. geometry.applyToMesh(mesh);
  18373. }
  18374. } else if (parsedGeometry instanceof ArrayBuffer) {
  18375. var binaryInfo = mesh._binaryInfo;
  18376. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18377. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18378. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18379. }
  18380. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18381. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18382. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18383. }
  18384. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18385. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18386. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18387. }
  18388. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18389. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18390. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18391. }
  18392. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18393. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18394. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18395. }
  18396. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18397. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18398. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18399. }
  18400. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18401. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18402. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18403. }
  18404. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18405. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18406. mesh.setIndices(indicesData);
  18407. }
  18408. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18409. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18410. mesh.subMeshes = [];
  18411. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18412. var materialIndex = subMeshesData[(i * 5) + 0];
  18413. var verticesStart = subMeshesData[(i * 5) + 1];
  18414. var verticesCount = subMeshesData[(i * 5) + 2];
  18415. var indexStart = subMeshesData[(i * 5) + 3];
  18416. var indexCount = subMeshesData[(i * 5) + 4];
  18417. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18418. }
  18419. }
  18420. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18421. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18422. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18423. if (parsedGeometry.uvs) {
  18424. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18425. }
  18426. if (parsedGeometry.uvs2) {
  18427. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18428. }
  18429. if (parsedGeometry.colors) {
  18430. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18431. }
  18432. if (parsedGeometry.matricesIndices) {
  18433. if (!parsedGeometry.matricesIndices._isExpanded) {
  18434. var floatIndices = [];
  18435. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18436. var matricesIndex = parsedGeometry.matricesIndices[i];
  18437. floatIndices.push(matricesIndex & 0x000000FF);
  18438. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18439. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18440. floatIndices.push(matricesIndex >> 24);
  18441. }
  18442. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18443. } else {
  18444. delete parsedGeometry.matricesIndices._isExpanded;
  18445. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18446. }
  18447. }
  18448. if (parsedGeometry.matricesWeights) {
  18449. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18450. }
  18451. mesh.setIndices(parsedGeometry.indices);
  18452. // SubMeshes
  18453. if (parsedGeometry.subMeshes) {
  18454. mesh.subMeshes = [];
  18455. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18456. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18457. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18458. }
  18459. }
  18460. }
  18461. // Flat shading
  18462. if (mesh._shouldGenerateFlatShading) {
  18463. mesh.convertToFlatShadedMesh();
  18464. delete mesh._shouldGenerateFlatShading;
  18465. }
  18466. // Update
  18467. mesh.computeWorldMatrix(true);
  18468. // Octree
  18469. if (scene._selectionOctree) {
  18470. scene._selectionOctree.addMesh(mesh);
  18471. }
  18472. };
  18473. BABYLON.SceneLoader.RegisterPlugin({
  18474. extensions: ".babylon",
  18475. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18476. var parsedData = JSON.parse(data);
  18477. var loadedSkeletonsIds = [];
  18478. var loadedMaterialsIds = [];
  18479. var hierarchyIds = [];
  18480. for (var index = 0; index < parsedData.meshes.length; index++) {
  18481. var parsedMesh = parsedData.meshes[index];
  18482. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18483. if (meshesNames instanceof Array) {
  18484. // Remove found mesh name from list.
  18485. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18486. }
  18487. // Material ?
  18488. if (parsedMesh.materialId) {
  18489. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18490. if (!materialFound) {
  18491. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18492. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18493. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18494. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18495. var subMatId = parsedMultiMaterial.materials[matIndex];
  18496. loadedMaterialsIds.push(subMatId);
  18497. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18498. }
  18499. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18500. parseMultiMaterial(parsedMultiMaterial, scene);
  18501. materialFound = true;
  18502. break;
  18503. }
  18504. }
  18505. }
  18506. if (!materialFound) {
  18507. loadedMaterialsIds.push(parsedMesh.materialId);
  18508. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18509. }
  18510. }
  18511. // Skeleton ?
  18512. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18513. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18514. if (!skeletonAlreadyLoaded) {
  18515. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18516. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18517. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18518. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18519. loadedSkeletonsIds.push(parsedSkeleton.id);
  18520. }
  18521. }
  18522. }
  18523. }
  18524. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18525. meshes.push(mesh);
  18526. }
  18527. }
  18528. for (index = 0; index < scene.meshes.length; index++) {
  18529. var currentMesh = scene.meshes[index];
  18530. if (currentMesh._waitingParentId) {
  18531. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18532. currentMesh._waitingParentId = undefined;
  18533. }
  18534. }
  18535. // Particles
  18536. if (parsedData.particleSystems) {
  18537. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18538. var parsedParticleSystem = parsedData.particleSystems[index];
  18539. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18540. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18541. }
  18542. }
  18543. }
  18544. return true;
  18545. },
  18546. load: function (scene, data, rootUrl) {
  18547. var parsedData = JSON.parse(data);
  18548. // Scene
  18549. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18550. scene.autoClear = parsedData.autoClear;
  18551. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18552. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18553. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18554. // Fog
  18555. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18556. scene.fogMode = parsedData.fogMode;
  18557. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18558. scene.fogStart = parsedData.fogStart;
  18559. scene.fogEnd = parsedData.fogEnd;
  18560. scene.fogDensity = parsedData.fogDensity;
  18561. }
  18562. for (var index = 0; index < parsedData.lights.length; index++) {
  18563. var parsedLight = parsedData.lights[index];
  18564. parseLight(parsedLight, scene);
  18565. }
  18566. // Materials
  18567. if (parsedData.materials) {
  18568. for (index = 0; index < parsedData.materials.length; index++) {
  18569. var parsedMaterial = parsedData.materials[index];
  18570. parseMaterial(parsedMaterial, scene, rootUrl);
  18571. }
  18572. }
  18573. if (parsedData.multiMaterials) {
  18574. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18575. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18576. parseMultiMaterial(parsedMultiMaterial, scene);
  18577. }
  18578. }
  18579. // Skeletons
  18580. if (parsedData.skeletons) {
  18581. for (index = 0; index < parsedData.skeletons.length; index++) {
  18582. var parsedSkeleton = parsedData.skeletons[index];
  18583. parseSkeleton(parsedSkeleton, scene);
  18584. }
  18585. }
  18586. // Geometries
  18587. var geometries = parsedData.geometries;
  18588. if (geometries) {
  18589. // Boxes
  18590. var boxes = geometries.boxes;
  18591. if (boxes) {
  18592. for (index = 0; index < boxes.length; index++) {
  18593. var parsedBox = boxes[index];
  18594. parseBox(parsedBox, scene);
  18595. }
  18596. }
  18597. // Spheres
  18598. var spheres = geometries.spheres;
  18599. if (spheres) {
  18600. for (index = 0; index < spheres.length; index++) {
  18601. var parsedSphere = spheres[index];
  18602. parseSphere(parsedSphere, scene);
  18603. }
  18604. }
  18605. // Cylinders
  18606. var cylinders = geometries.cylinders;
  18607. if (cylinders) {
  18608. for (index = 0; index < cylinders.length; index++) {
  18609. var parsedCylinder = cylinders[index];
  18610. parseCylinder(parsedCylinder, scene);
  18611. }
  18612. }
  18613. // Toruses
  18614. var toruses = geometries.toruses;
  18615. if (toruses) {
  18616. for (index = 0; index < toruses.length; index++) {
  18617. var parsedTorus = toruses[index];
  18618. parseTorus(parsedTorus, scene);
  18619. }
  18620. }
  18621. // Grounds
  18622. var grounds = geometries.grounds;
  18623. if (grounds) {
  18624. for (index = 0; index < grounds.length; index++) {
  18625. var parsedGround = grounds[index];
  18626. parseGround(parsedGround, scene);
  18627. }
  18628. }
  18629. // Planes
  18630. var planes = geometries.planes;
  18631. if (planes) {
  18632. for (index = 0; index < planes.length; index++) {
  18633. var parsedPlane = planes[index];
  18634. parsePlane(parsedPlane, scene);
  18635. }
  18636. }
  18637. // TorusKnots
  18638. var torusKnots = geometries.torusKnots;
  18639. if (torusKnots) {
  18640. for (index = 0; index < torusKnots.length; index++) {
  18641. var parsedTorusKnot = torusKnots[index];
  18642. parseTorusKnot(parsedTorusKnot, scene);
  18643. }
  18644. }
  18645. // VertexData
  18646. var vertexData = geometries.vertexData;
  18647. if (vertexData) {
  18648. for (index = 0; index < vertexData.length; index++) {
  18649. var parsedVertexData = vertexData[index];
  18650. parseVertexData(parsedVertexData, scene, rootUrl);
  18651. }
  18652. }
  18653. }
  18654. for (index = 0; index < parsedData.meshes.length; index++) {
  18655. var parsedMesh = parsedData.meshes[index];
  18656. parseMesh(parsedMesh, scene, rootUrl);
  18657. }
  18658. for (index = 0; index < parsedData.cameras.length; index++) {
  18659. var parsedCamera = parsedData.cameras[index];
  18660. parseCamera(parsedCamera, scene);
  18661. }
  18662. if (parsedData.activeCameraID) {
  18663. scene.setActiveCameraByID(parsedData.activeCameraID);
  18664. }
  18665. for (index = 0; index < scene.cameras.length; index++) {
  18666. var camera = scene.cameras[index];
  18667. if (camera._waitingParentId) {
  18668. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18669. camera._waitingParentId = undefined;
  18670. }
  18671. }
  18672. for (index = 0; index < scene.lights.length; index++) {
  18673. var light = scene.lights[index];
  18674. if (light._waitingParentId) {
  18675. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18676. light._waitingParentId = undefined;
  18677. }
  18678. }
  18679. for (index = 0; index < scene.meshes.length; index++) {
  18680. var mesh = scene.meshes[index];
  18681. if (mesh._waitingParentId) {
  18682. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18683. mesh._waitingParentId = undefined;
  18684. }
  18685. if (mesh._waitingActions) {
  18686. parseActions(mesh._waitingActions, mesh, scene);
  18687. mesh._waitingActions = undefined;
  18688. }
  18689. }
  18690. // Particles Systems
  18691. if (parsedData.particleSystems) {
  18692. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18693. var parsedParticleSystem = parsedData.particleSystems[index];
  18694. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18695. }
  18696. }
  18697. // Lens flares
  18698. if (parsedData.lensFlareSystems) {
  18699. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18700. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18701. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18702. }
  18703. }
  18704. // Shadows
  18705. if (parsedData.shadowGenerators) {
  18706. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18707. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18708. parseShadowGenerator(parsedShadowGenerator, scene);
  18709. }
  18710. }
  18711. // Actions (scene)
  18712. if (parsedData.actions) {
  18713. parseActions(parsedData.actions, null, scene);
  18714. }
  18715. // Finish
  18716. return true;
  18717. }
  18718. });
  18719. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18720. var Internals = BABYLON.Internals;
  18721. })(BABYLON || (BABYLON = {}));
  18722. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18723. var BABYLON;
  18724. (function (BABYLON) {
  18725. // Unique ID when we import meshes from Babylon to CSG
  18726. var currentCSGMeshId = 0;
  18727. // # class Vertex
  18728. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18729. // one to provide additional features like texture coordinates and vertex
  18730. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18731. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18732. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18733. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18734. // is not used anywhere else.
  18735. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18736. var Vertex = (function () {
  18737. function Vertex(pos, normal, uv) {
  18738. this.pos = pos;
  18739. this.normal = normal;
  18740. this.uv = uv;
  18741. }
  18742. Vertex.prototype.clone = function () {
  18743. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18744. };
  18745. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18746. // orientation of a polygon is flipped.
  18747. Vertex.prototype.flip = function () {
  18748. this.normal = this.normal.scale(-1);
  18749. };
  18750. // Create a new vertex between this vertex and `other` by linearly
  18751. // interpolating all properties using a parameter of `t`. Subclasses should
  18752. // override this to interpolate additional properties.
  18753. Vertex.prototype.interpolate = function (other, t) {
  18754. 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));
  18755. };
  18756. return Vertex;
  18757. })();
  18758. // # class Plane
  18759. // Represents a plane in 3D space.
  18760. var Plane = (function () {
  18761. function Plane(normal, w) {
  18762. this.normal = normal;
  18763. this.w = w;
  18764. }
  18765. Plane.FromPoints = function (a, b, c) {
  18766. var v0 = c.subtract(a);
  18767. var v1 = b.subtract(a);
  18768. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18769. return null;
  18770. }
  18771. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18772. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18773. };
  18774. Plane.prototype.clone = function () {
  18775. return new Plane(this.normal.clone(), this.w);
  18776. };
  18777. Plane.prototype.flip = function () {
  18778. this.normal.scaleInPlace(-1);
  18779. this.w = -this.w;
  18780. };
  18781. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18782. // fragments in the appropriate lists. Coplanar polygons go into either
  18783. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18784. // respect to this plane. Polygons in front or in back of this plane go into
  18785. // either `front` or `back`.
  18786. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18787. var COPLANAR = 0;
  18788. var FRONT = 1;
  18789. var BACK = 2;
  18790. var SPANNING = 3;
  18791. // Classify each point as well as the entire polygon into one of the above
  18792. // four classes.
  18793. var polygonType = 0;
  18794. var types = [];
  18795. for (var i = 0; i < polygon.vertices.length; i++) {
  18796. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18797. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18798. polygonType |= type;
  18799. types.push(type);
  18800. }
  18801. switch (polygonType) {
  18802. case COPLANAR:
  18803. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18804. break;
  18805. case FRONT:
  18806. front.push(polygon);
  18807. break;
  18808. case BACK:
  18809. back.push(polygon);
  18810. break;
  18811. case SPANNING:
  18812. var f = [], b = [];
  18813. for (i = 0; i < polygon.vertices.length; i++) {
  18814. var j = (i + 1) % polygon.vertices.length;
  18815. var ti = types[i], tj = types[j];
  18816. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18817. if (ti != BACK)
  18818. f.push(vi);
  18819. if (ti != FRONT)
  18820. b.push(ti != BACK ? vi.clone() : vi);
  18821. if ((ti | tj) == SPANNING) {
  18822. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18823. var v = vi.interpolate(vj, t);
  18824. f.push(v);
  18825. b.push(v.clone());
  18826. }
  18827. }
  18828. if (f.length >= 3) {
  18829. var poly = new Polygon(f, polygon.shared);
  18830. if (poly.plane)
  18831. front.push(poly);
  18832. }
  18833. if (b.length >= 3) {
  18834. poly = new Polygon(b, polygon.shared);
  18835. if (poly.plane)
  18836. back.push(poly);
  18837. }
  18838. break;
  18839. }
  18840. };
  18841. Plane.EPSILON = 1e-5;
  18842. return Plane;
  18843. })();
  18844. // # class Polygon
  18845. // Represents a convex polygon. The vertices used to initialize a polygon must
  18846. // be coplanar and form a convex loop.
  18847. //
  18848. // Each convex polygon has a `shared` property, which is shared between all
  18849. // polygons that are clones of each other or were split from the same polygon.
  18850. // This can be used to define per-polygon properties (such as surface color).
  18851. var Polygon = (function () {
  18852. function Polygon(vertices, shared) {
  18853. this.vertices = vertices;
  18854. this.shared = shared;
  18855. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18856. }
  18857. Polygon.prototype.clone = function () {
  18858. var vertices = this.vertices.map(function (v) {
  18859. return v.clone();
  18860. });
  18861. return new Polygon(vertices, this.shared);
  18862. };
  18863. Polygon.prototype.flip = function () {
  18864. this.vertices.reverse().map(function (v) {
  18865. v.flip();
  18866. });
  18867. this.plane.flip();
  18868. };
  18869. return Polygon;
  18870. })();
  18871. // # class Node
  18872. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18873. // by picking a polygon to split along. That polygon (and all other coplanar
  18874. // polygons) are added directly to that node and the other polygons are added to
  18875. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18876. // no distinction between internal and leaf nodes.
  18877. var Node = (function () {
  18878. function Node(polygons) {
  18879. this.plane = null;
  18880. this.front = null;
  18881. this.back = null;
  18882. this.polygons = [];
  18883. if (polygons) {
  18884. this.build(polygons);
  18885. }
  18886. }
  18887. Node.prototype.clone = function () {
  18888. var node = new Node();
  18889. node.plane = this.plane && this.plane.clone();
  18890. node.front = this.front && this.front.clone();
  18891. node.back = this.back && this.back.clone();
  18892. node.polygons = this.polygons.map(function (p) {
  18893. return p.clone();
  18894. });
  18895. return node;
  18896. };
  18897. // Convert solid space to empty space and empty space to solid space.
  18898. Node.prototype.invert = function () {
  18899. for (var i = 0; i < this.polygons.length; i++) {
  18900. this.polygons[i].flip();
  18901. }
  18902. if (this.plane) {
  18903. this.plane.flip();
  18904. }
  18905. if (this.front) {
  18906. this.front.invert();
  18907. }
  18908. if (this.back) {
  18909. this.back.invert();
  18910. }
  18911. var temp = this.front;
  18912. this.front = this.back;
  18913. this.back = temp;
  18914. };
  18915. // Recursively remove all polygons in `polygons` that are inside this BSP
  18916. // tree.
  18917. Node.prototype.clipPolygons = function (polygons) {
  18918. if (!this.plane)
  18919. return polygons.slice();
  18920. var front = [], back = [];
  18921. for (var i = 0; i < polygons.length; i++) {
  18922. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18923. }
  18924. if (this.front) {
  18925. front = this.front.clipPolygons(front);
  18926. }
  18927. if (this.back) {
  18928. back = this.back.clipPolygons(back);
  18929. } else {
  18930. back = [];
  18931. }
  18932. return front.concat(back);
  18933. };
  18934. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18935. // `bsp`.
  18936. Node.prototype.clipTo = function (bsp) {
  18937. this.polygons = bsp.clipPolygons(this.polygons);
  18938. if (this.front)
  18939. this.front.clipTo(bsp);
  18940. if (this.back)
  18941. this.back.clipTo(bsp);
  18942. };
  18943. // Return a list of all polygons in this BSP tree.
  18944. Node.prototype.allPolygons = function () {
  18945. var polygons = this.polygons.slice();
  18946. if (this.front)
  18947. polygons = polygons.concat(this.front.allPolygons());
  18948. if (this.back)
  18949. polygons = polygons.concat(this.back.allPolygons());
  18950. return polygons;
  18951. };
  18952. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18953. // new polygons are filtered down to the bottom of the tree and become new
  18954. // nodes there. Each set of polygons is partitioned using the first polygon
  18955. // (no heuristic is used to pick a good split).
  18956. Node.prototype.build = function (polygons) {
  18957. if (!polygons.length)
  18958. return;
  18959. if (!this.plane)
  18960. this.plane = polygons[0].plane.clone();
  18961. var front = [], back = [];
  18962. for (var i = 0; i < polygons.length; i++) {
  18963. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18964. }
  18965. if (front.length) {
  18966. if (!this.front)
  18967. this.front = new Node();
  18968. this.front.build(front);
  18969. }
  18970. if (back.length) {
  18971. if (!this.back)
  18972. this.back = new Node();
  18973. this.back.build(back);
  18974. }
  18975. };
  18976. return Node;
  18977. })();
  18978. var CSG = (function () {
  18979. function CSG() {
  18980. this.polygons = new Array();
  18981. }
  18982. // Convert BABYLON.Mesh to BABYLON.CSG
  18983. CSG.FromMesh = function (mesh) {
  18984. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18985. if (mesh instanceof BABYLON.Mesh) {
  18986. mesh.computeWorldMatrix(true);
  18987. var matrix = mesh.getWorldMatrix();
  18988. var meshPosition = mesh.position.clone();
  18989. var meshRotation = mesh.rotation.clone();
  18990. var meshScaling = mesh.scaling.clone();
  18991. } else {
  18992. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18993. }
  18994. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18995. var subMeshes = mesh.subMeshes;
  18996. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18997. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18998. vertices = [];
  18999. for (var j = 0; j < 3; j++) {
  19000. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19001. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19002. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19003. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19004. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19005. vertex = new Vertex(position, normal, uv);
  19006. vertices.push(vertex);
  19007. }
  19008. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19009. // To handle the case of degenerated triangle
  19010. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19011. if (polygon.plane)
  19012. polygons.push(polygon);
  19013. }
  19014. }
  19015. var csg = CSG.FromPolygons(polygons);
  19016. csg.matrix = matrix;
  19017. csg.position = meshPosition;
  19018. csg.rotation = meshRotation;
  19019. csg.scaling = meshScaling;
  19020. currentCSGMeshId++;
  19021. return csg;
  19022. };
  19023. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19024. CSG.FromPolygons = function (polygons) {
  19025. var csg = new BABYLON.CSG();
  19026. csg.polygons = polygons;
  19027. return csg;
  19028. };
  19029. CSG.prototype.clone = function () {
  19030. var csg = new BABYLON.CSG();
  19031. csg.polygons = this.polygons.map(function (p) {
  19032. return p.clone();
  19033. });
  19034. csg.copyTransformAttributes(this);
  19035. return csg;
  19036. };
  19037. CSG.prototype.toPolygons = function () {
  19038. return this.polygons;
  19039. };
  19040. CSG.prototype.union = function (csg) {
  19041. var a = new Node(this.clone().polygons);
  19042. var b = new Node(csg.clone().polygons);
  19043. a.clipTo(b);
  19044. b.clipTo(a);
  19045. b.invert();
  19046. b.clipTo(a);
  19047. b.invert();
  19048. a.build(b.allPolygons());
  19049. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19050. };
  19051. CSG.prototype.unionInPlace = function (csg) {
  19052. var a = new Node(this.polygons);
  19053. var b = new Node(csg.polygons);
  19054. a.clipTo(b);
  19055. b.clipTo(a);
  19056. b.invert();
  19057. b.clipTo(a);
  19058. b.invert();
  19059. a.build(b.allPolygons());
  19060. this.polygons = a.allPolygons();
  19061. };
  19062. CSG.prototype.subtract = function (csg) {
  19063. var a = new Node(this.clone().polygons);
  19064. var b = new Node(csg.clone().polygons);
  19065. a.invert();
  19066. a.clipTo(b);
  19067. b.clipTo(a);
  19068. b.invert();
  19069. b.clipTo(a);
  19070. b.invert();
  19071. a.build(b.allPolygons());
  19072. a.invert();
  19073. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19074. };
  19075. CSG.prototype.subtractInPlace = function (csg) {
  19076. var a = new Node(this.polygons);
  19077. var b = new Node(csg.polygons);
  19078. a.invert();
  19079. a.clipTo(b);
  19080. b.clipTo(a);
  19081. b.invert();
  19082. b.clipTo(a);
  19083. b.invert();
  19084. a.build(b.allPolygons());
  19085. a.invert();
  19086. this.polygons = a.allPolygons();
  19087. };
  19088. CSG.prototype.intersect = function (csg) {
  19089. var a = new Node(this.clone().polygons);
  19090. var b = new Node(csg.clone().polygons);
  19091. a.invert();
  19092. b.clipTo(a);
  19093. b.invert();
  19094. a.clipTo(b);
  19095. b.clipTo(a);
  19096. a.build(b.allPolygons());
  19097. a.invert();
  19098. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19099. };
  19100. CSG.prototype.intersectInPlace = function (csg) {
  19101. var a = new Node(this.polygons);
  19102. var b = new Node(csg.polygons);
  19103. a.invert();
  19104. b.clipTo(a);
  19105. b.invert();
  19106. a.clipTo(b);
  19107. b.clipTo(a);
  19108. a.build(b.allPolygons());
  19109. a.invert();
  19110. this.polygons = a.allPolygons();
  19111. };
  19112. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19113. // not modified.
  19114. CSG.prototype.inverse = function () {
  19115. var csg = this.clone();
  19116. csg.inverseInPlace();
  19117. return csg;
  19118. };
  19119. CSG.prototype.inverseInPlace = function () {
  19120. this.polygons.map(function (p) {
  19121. p.flip();
  19122. });
  19123. };
  19124. // This is used to keep meshes transformations so they can be restored
  19125. // when we build back a Babylon Mesh
  19126. // NB : All CSG operations are performed in world coordinates
  19127. CSG.prototype.copyTransformAttributes = function (csg) {
  19128. this.matrix = csg.matrix;
  19129. this.position = csg.position;
  19130. this.rotation = csg.rotation;
  19131. this.scaling = csg.scaling;
  19132. return this;
  19133. };
  19134. // Build Raw mesh from CSG
  19135. // Coordinates here are in world space
  19136. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19137. var matrix = this.matrix.clone();
  19138. matrix.invert();
  19139. 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;
  19140. if (keepSubMeshes) {
  19141. // Sort Polygons, since subMeshes are indices range
  19142. polygons.sort(function (a, b) {
  19143. if (a.shared.meshId === b.shared.meshId) {
  19144. return a.shared.subMeshId - b.shared.subMeshId;
  19145. } else {
  19146. return a.shared.meshId - b.shared.meshId;
  19147. }
  19148. });
  19149. }
  19150. for (var i = 0, il = polygons.length; i < il; i++) {
  19151. polygon = polygons[i];
  19152. // Building SubMeshes
  19153. if (!subMesh_dict[polygon.shared.meshId]) {
  19154. subMesh_dict[polygon.shared.meshId] = {};
  19155. }
  19156. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19157. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19158. indexStart: +Infinity,
  19159. indexEnd: -Infinity,
  19160. materialIndex: polygon.shared.materialIndex
  19161. };
  19162. }
  19163. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19164. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19165. polygonIndices[0] = 0;
  19166. polygonIndices[1] = j - 1;
  19167. polygonIndices[2] = j;
  19168. for (var k = 0; k < 3; k++) {
  19169. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19170. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19171. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19172. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19173. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19174. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19175. // Check if 2 points can be merged
  19176. 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)) {
  19177. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19178. uvs.push(uv.x, uv.y);
  19179. normals.push(normal.x, normal.y, normal.z);
  19180. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19181. }
  19182. indices.push(vertex_idx);
  19183. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19184. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19185. currentIndex++;
  19186. }
  19187. }
  19188. }
  19189. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19190. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19191. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19192. mesh.setIndices(indices);
  19193. if (keepSubMeshes) {
  19194. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19195. var materialIndexOffset = 0, materialMaxIndex;
  19196. mesh.subMeshes.length = 0;
  19197. for (var m in subMesh_dict) {
  19198. materialMaxIndex = -1;
  19199. for (var sm in subMesh_dict[m]) {
  19200. subMesh_obj = subMesh_dict[m][sm];
  19201. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19202. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19203. }
  19204. materialIndexOffset += ++materialMaxIndex;
  19205. }
  19206. }
  19207. return mesh;
  19208. };
  19209. // Build Mesh from CSG taking material and transforms into account
  19210. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19211. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19212. mesh.material = material;
  19213. mesh.position.copyFrom(this.position);
  19214. mesh.rotation.copyFrom(this.rotation);
  19215. mesh.scaling.copyFrom(this.scaling);
  19216. mesh.computeWorldMatrix(true);
  19217. return mesh;
  19218. };
  19219. return CSG;
  19220. })();
  19221. BABYLON.CSG = CSG;
  19222. })(BABYLON || (BABYLON = {}));
  19223. //# sourceMappingURL=babylon.csg.js.map
  19224. var BABYLON;
  19225. (function (BABYLON) {
  19226. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19227. __extends(OculusDistortionCorrectionPostProcess, _super);
  19228. //ANY
  19229. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19230. var _this = this;
  19231. _super.call(this, name, "oculusDistortionCorrection", [
  19232. 'LensCenter',
  19233. 'Scale',
  19234. 'ScaleIn',
  19235. 'HmdWarpParam'
  19236. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19237. this._isRightEye = isRightEye;
  19238. this._distortionFactors = cameraSettings.DistortionK;
  19239. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19240. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19241. this.onSizeChanged = function () {
  19242. _this.aspectRatio = _this.width * .5 / _this.height;
  19243. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19244. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19245. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19246. };
  19247. this.onApply = function (effect) {
  19248. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19249. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19250. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19251. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19252. };
  19253. }
  19254. return OculusDistortionCorrectionPostProcess;
  19255. })(BABYLON.PostProcess);
  19256. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19257. })(BABYLON || (BABYLON = {}));
  19258. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  19259. // Mainly based on these 2 articles :
  19260. // 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
  19261. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19262. var BABYLON;
  19263. (function (BABYLON) {
  19264. (function (JoystickAxis) {
  19265. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19266. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19267. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19268. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19269. var JoystickAxis = BABYLON.JoystickAxis;
  19270. var VirtualJoystick = (function () {
  19271. function VirtualJoystick(leftJoystick) {
  19272. var _this = this;
  19273. if (leftJoystick) {
  19274. this._leftJoystick = true;
  19275. } else {
  19276. this._leftJoystick = false;
  19277. }
  19278. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19279. VirtualJoystick._globalJoystickIndex++;
  19280. // By default left & right arrow keys are moving the X
  19281. // and up & down keys are moving the Y
  19282. this._axisTargetedByLeftAndRight = 0 /* X */;
  19283. this._axisTargetedByUpAndDown = 1 /* Y */;
  19284. this.reverseLeftRight = false;
  19285. this.reverseUpDown = false;
  19286. // collections of pointers
  19287. this._touches = new BABYLON.VirtualJoystick.Collection();
  19288. this.deltaPosition = BABYLON.Vector3.Zero();
  19289. this._joystickSensibility = 25;
  19290. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19291. this._rotationSpeed = 25;
  19292. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19293. this._rotateOnAxisRelativeToMesh = false;
  19294. // injecting a canvas element on top of the canvas 3D game
  19295. if (!VirtualJoystick.vjCanvas) {
  19296. window.addEventListener("resize", function () {
  19297. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19298. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19299. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19300. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19301. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19302. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19303. }, false);
  19304. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19305. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19306. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19307. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19308. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19309. VirtualJoystick.vjCanvas.style.width = "100%";
  19310. VirtualJoystick.vjCanvas.style.height = "100%";
  19311. VirtualJoystick.vjCanvas.style.position = "absolute";
  19312. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19313. VirtualJoystick.vjCanvas.style.top = "0px";
  19314. VirtualJoystick.vjCanvas.style.left = "0px";
  19315. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19316. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19317. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19318. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19319. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19320. document.body.appendChild(VirtualJoystick.vjCanvas);
  19321. }
  19322. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19323. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19324. this.pressed = false;
  19325. // default joystick color
  19326. this._joystickColor = "cyan";
  19327. this._joystickPointerID = -1;
  19328. // current joystick position
  19329. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19330. // origin joystick position
  19331. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19332. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19333. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19334. _this._onPointerDown(evt);
  19335. }, false);
  19336. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19337. _this._onPointerMove(evt);
  19338. }, false);
  19339. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19340. _this._onPointerUp(evt);
  19341. }, false);
  19342. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19343. _this._onPointerUp(evt);
  19344. }, false);
  19345. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19346. evt.preventDefault(); // Disables system menu
  19347. }, false);
  19348. requestAnimationFrame(function () {
  19349. _this._drawVirtualJoystick();
  19350. });
  19351. }
  19352. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19353. this._joystickSensibility = newJoystickSensibility;
  19354. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19355. };
  19356. VirtualJoystick.prototype._onPointerDown = function (e) {
  19357. var positionOnScreenCondition;
  19358. e.preventDefault();
  19359. if (this._leftJoystick === true) {
  19360. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19361. } else {
  19362. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19363. }
  19364. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19365. // First contact will be dedicated to the virtual joystick
  19366. this._joystickPointerID = e.pointerId;
  19367. this._joystickPointerStartPos.x = e.clientX;
  19368. this._joystickPointerStartPos.y = e.clientY;
  19369. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19370. this._deltaJoystickVector.x = 0;
  19371. this._deltaJoystickVector.y = 0;
  19372. this.pressed = true;
  19373. this._touches.add(e.pointerId.toString(), e);
  19374. } else {
  19375. // You can only trigger the action buttons with a joystick declared
  19376. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19377. this._action();
  19378. this._touches.add(e.pointerId.toString(), e);
  19379. }
  19380. }
  19381. };
  19382. VirtualJoystick.prototype._onPointerMove = function (e) {
  19383. // If the current pointer is the one associated to the joystick (first touch contact)
  19384. if (this._joystickPointerID == e.pointerId) {
  19385. this._joystickPointerPos.x = e.clientX;
  19386. this._joystickPointerPos.y = e.clientY;
  19387. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19388. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19389. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19390. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19391. switch (this._axisTargetedByLeftAndRight) {
  19392. case 0 /* X */:
  19393. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19394. break;
  19395. case 1 /* Y */:
  19396. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19397. break;
  19398. case 2 /* Z */:
  19399. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19400. break;
  19401. }
  19402. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19403. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19404. switch (this._axisTargetedByUpAndDown) {
  19405. case 0 /* X */:
  19406. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19407. break;
  19408. case 1 /* Y */:
  19409. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19410. break;
  19411. case 2 /* Z */:
  19412. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19413. break;
  19414. }
  19415. } else {
  19416. if (this._touches.item(e.pointerId.toString())) {
  19417. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19418. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19419. }
  19420. }
  19421. };
  19422. VirtualJoystick.prototype._onPointerUp = function (e) {
  19423. this._clearCanvas();
  19424. if (this._joystickPointerID == e.pointerId) {
  19425. this._joystickPointerID = -1;
  19426. this.pressed = false;
  19427. }
  19428. this._deltaJoystickVector.x = 0;
  19429. this._deltaJoystickVector.y = 0;
  19430. this._touches.remove(e.pointerId.toString());
  19431. };
  19432. /**
  19433. * Change the color of the virtual joystick
  19434. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19435. */
  19436. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19437. this._joystickColor = newColor;
  19438. };
  19439. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19440. this._action = action;
  19441. };
  19442. // Define which axis you'd like to control for left & right
  19443. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19444. switch (axis) {
  19445. case 0 /* X */:
  19446. case 1 /* Y */:
  19447. case 2 /* Z */:
  19448. this._axisTargetedByLeftAndRight = axis;
  19449. break;
  19450. default:
  19451. this._axisTargetedByLeftAndRight = 0 /* X */;
  19452. break;
  19453. }
  19454. };
  19455. // Define which axis you'd like to control for up & down
  19456. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19457. switch (axis) {
  19458. case 0 /* X */:
  19459. case 1 /* Y */:
  19460. case 2 /* Z */:
  19461. this._axisTargetedByUpAndDown = axis;
  19462. break;
  19463. default:
  19464. this._axisTargetedByUpAndDown = 1 /* Y */;
  19465. break;
  19466. }
  19467. };
  19468. VirtualJoystick.prototype._clearCanvas = function () {
  19469. if (this._leftJoystick) {
  19470. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19471. } else {
  19472. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19473. }
  19474. };
  19475. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19476. var _this = this;
  19477. if (this.pressed) {
  19478. this._clearCanvas();
  19479. this._touches.forEach(function (touch) {
  19480. if (touch.pointerId === _this._joystickPointerID) {
  19481. VirtualJoystick.vjCanvasContext.beginPath();
  19482. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19483. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19484. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19485. VirtualJoystick.vjCanvasContext.stroke();
  19486. VirtualJoystick.vjCanvasContext.beginPath();
  19487. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19488. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19489. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19490. VirtualJoystick.vjCanvasContext.stroke();
  19491. VirtualJoystick.vjCanvasContext.beginPath();
  19492. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19493. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19494. VirtualJoystick.vjCanvasContext.stroke();
  19495. } else {
  19496. VirtualJoystick.vjCanvasContext.beginPath();
  19497. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19498. VirtualJoystick.vjCanvasContext.beginPath();
  19499. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19500. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19501. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19502. VirtualJoystick.vjCanvasContext.stroke();
  19503. }
  19504. ;
  19505. });
  19506. }
  19507. requestAnimationFrame(function () {
  19508. _this._drawVirtualJoystick();
  19509. });
  19510. };
  19511. VirtualJoystick.prototype.releaseCanvas = function () {
  19512. if (VirtualJoystick.vjCanvas) {
  19513. document.body.removeChild(VirtualJoystick.vjCanvas);
  19514. VirtualJoystick.vjCanvas = null;
  19515. }
  19516. };
  19517. VirtualJoystick._globalJoystickIndex = 0;
  19518. return VirtualJoystick;
  19519. })();
  19520. BABYLON.VirtualJoystick = VirtualJoystick;
  19521. })(BABYLON || (BABYLON = {}));
  19522. var BABYLON;
  19523. (function (BABYLON) {
  19524. (function (VirtualJoystick) {
  19525. var Collection = (function () {
  19526. function Collection() {
  19527. this._count = 0;
  19528. this._collection = new Array();
  19529. }
  19530. Collection.prototype.Count = function () {
  19531. return this._count;
  19532. };
  19533. Collection.prototype.add = function (key, item) {
  19534. if (this._collection[key] != undefined) {
  19535. return undefined;
  19536. }
  19537. this._collection[key] = item;
  19538. return ++this._count;
  19539. };
  19540. Collection.prototype.remove = function (key) {
  19541. if (this._collection[key] == undefined) {
  19542. return undefined;
  19543. }
  19544. delete this._collection[key];
  19545. return --this._count;
  19546. };
  19547. Collection.prototype.item = function (key) {
  19548. return this._collection[key];
  19549. };
  19550. Collection.prototype.forEach = function (block) {
  19551. var key;
  19552. for (key in this._collection) {
  19553. if (this._collection.hasOwnProperty(key)) {
  19554. block(this._collection[key]);
  19555. }
  19556. }
  19557. };
  19558. return Collection;
  19559. })();
  19560. VirtualJoystick.Collection = Collection;
  19561. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  19562. var VirtualJoystick = BABYLON.VirtualJoystick;
  19563. })(BABYLON || (BABYLON = {}));
  19564. //# sourceMappingURL=babylon.virtualJoystick.js.map
  19565. var BABYLON;
  19566. (function (BABYLON) {
  19567. var OculusRiftDevKit2013_Metric = {
  19568. HResolution: 1280,
  19569. VResolution: 800,
  19570. HScreenSize: 0.149759993,
  19571. VScreenSize: 0.0935999975,
  19572. VScreenCenter: 0.0467999987,
  19573. EyeToScreenDistance: 0.0410000011,
  19574. LensSeparationDistance: 0.0635000020,
  19575. InterpupillaryDistance: 0.0640000030,
  19576. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19577. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19578. PostProcessScaleFactor: 1.714605507808412,
  19579. LensCenterOffset: 0.151976421
  19580. };
  19581. var _OculusInnerCamera = (function (_super) {
  19582. __extends(_OculusInnerCamera, _super);
  19583. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  19584. _super.call(this, name, position, scene);
  19585. this._workMatrix = new BABYLON.Matrix();
  19586. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19587. // Constants
  19588. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19589. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19590. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19591. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19592. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19593. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19594. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19595. // Postprocess
  19596. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19597. }
  19598. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  19599. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19600. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19601. return this._projectionMatrix;
  19602. };
  19603. _OculusInnerCamera.prototype._getViewMatrix = function () {
  19604. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19605. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19606. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19607. // Computing target and final matrix
  19608. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19609. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19610. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19611. return this._viewMatrix;
  19612. };
  19613. return _OculusInnerCamera;
  19614. })(BABYLON.FreeCamera);
  19615. var OculusCamera = (function (_super) {
  19616. __extends(OculusCamera, _super);
  19617. function OculusCamera(name, position, scene) {
  19618. _super.call(this, name, position, scene);
  19619. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  19620. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  19621. this.subCameras.push(this._leftCamera);
  19622. this.subCameras.push(this._rightCamera);
  19623. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19624. }
  19625. OculusCamera.prototype._update = function () {
  19626. this._leftCamera.position.copyFrom(this.position);
  19627. this._rightCamera.position.copyFrom(this.position);
  19628. this._updateCamera(this._leftCamera);
  19629. this._updateCamera(this._rightCamera);
  19630. _super.prototype._update.call(this);
  19631. };
  19632. OculusCamera.prototype._updateCamera = function (camera) {
  19633. camera.minZ = this.minZ;
  19634. camera.maxZ = this.maxZ;
  19635. camera.rotation.x = this.rotation.x;
  19636. camera.rotation.y = this.rotation.y;
  19637. camera.rotation.z = this.rotation.z;
  19638. };
  19639. // Oculus events
  19640. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19641. var yaw = evt.alpha / 180 * Math.PI;
  19642. var pitch = evt.beta / 180 * Math.PI;
  19643. var roll = evt.gamma / 180 * Math.PI;
  19644. if (!this._offsetOrientation) {
  19645. this._offsetOrientation = {
  19646. yaw: yaw,
  19647. pitch: pitch,
  19648. roll: roll
  19649. };
  19650. return;
  19651. } else {
  19652. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19653. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19654. this.rotation.z += this._offsetOrientation.roll - roll;
  19655. this._offsetOrientation.yaw = yaw;
  19656. this._offsetOrientation.pitch = pitch;
  19657. this._offsetOrientation.roll = roll;
  19658. }
  19659. };
  19660. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19661. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19662. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19663. };
  19664. OculusCamera.prototype.detachControl = function (element) {
  19665. _super.prototype.detachControl.call(this, element);
  19666. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19667. };
  19668. return OculusCamera;
  19669. })(BABYLON.FreeCamera);
  19670. BABYLON.OculusCamera = OculusCamera;
  19671. })(BABYLON || (BABYLON = {}));
  19672. //# sourceMappingURL=babylon.oculusCamera.js.map
  19673. var BABYLON;
  19674. (function (BABYLON) {
  19675. var OculusRiftDevKit2013_Metric = {
  19676. HResolution: 1280,
  19677. VResolution: 800,
  19678. HScreenSize: 0.149759993,
  19679. VScreenSize: 0.0935999975,
  19680. VScreenCenter: 0.0467999987,
  19681. EyeToScreenDistance: 0.0410000011,
  19682. LensSeparationDistance: 0.0635000020,
  19683. InterpupillaryDistance: 0.0640000030,
  19684. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19685. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19686. PostProcessScaleFactor: 1.714605507808412,
  19687. LensCenterOffset: 0.151976421
  19688. };
  19689. var _OculusInnerGamepadCamera = (function (_super) {
  19690. __extends(_OculusInnerGamepadCamera, _super);
  19691. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19692. _super.call(this, name, position, scene);
  19693. this._workMatrix = new BABYLON.Matrix();
  19694. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19695. // Constants
  19696. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19697. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19698. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19699. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19700. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19701. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19702. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19703. // Postprocess
  19704. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19705. }
  19706. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19707. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19708. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19709. return this._projectionMatrix;
  19710. };
  19711. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19712. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19713. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19714. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19715. // Computing target and final matrix
  19716. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19717. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19718. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19719. return this._viewMatrix;
  19720. };
  19721. return _OculusInnerGamepadCamera;
  19722. })(BABYLON.FreeCamera);
  19723. var OculusGamepadCamera = (function (_super) {
  19724. __extends(OculusGamepadCamera, _super);
  19725. function OculusGamepadCamera(name, position, scene) {
  19726. var _this = this;
  19727. _super.call(this, name, position, scene);
  19728. this.angularSensibility = 200;
  19729. this.moveSensibility = 75;
  19730. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19731. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19732. this.subCameras.push(this._leftCamera);
  19733. this.subCameras.push(this._rightCamera);
  19734. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19735. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19736. _this._onNewGameConnected(gamepad);
  19737. });
  19738. }
  19739. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19740. // Only the first gamepad can control the camera
  19741. if (gamepad.index === 0) {
  19742. this._gamepad = gamepad;
  19743. }
  19744. };
  19745. OculusGamepadCamera.prototype._update = function () {
  19746. this._leftCamera.position.copyFrom(this.position);
  19747. this._rightCamera.position.copyFrom(this.position);
  19748. this._updateCamera(this._leftCamera);
  19749. this._updateCamera(this._rightCamera);
  19750. _super.prototype._update.call(this);
  19751. };
  19752. OculusGamepadCamera.prototype._checkInputs = function () {
  19753. if (!this._gamepad) {
  19754. return;
  19755. }
  19756. var LSValues = this._gamepad.leftStick;
  19757. var normalizedLX = LSValues.x / this.moveSensibility;
  19758. var normalizedLY = LSValues.y / this.moveSensibility;
  19759. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19760. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19761. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19762. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19763. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19764. };
  19765. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19766. camera.minZ = this.minZ;
  19767. camera.maxZ = this.maxZ;
  19768. camera.rotation.x = this.rotation.x;
  19769. camera.rotation.y = this.rotation.y;
  19770. camera.rotation.z = this.rotation.z;
  19771. };
  19772. // Oculus events
  19773. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19774. var yaw = evt.alpha / 180 * Math.PI;
  19775. var pitch = evt.beta / 180 * Math.PI;
  19776. var roll = evt.gamma / 180 * Math.PI;
  19777. if (!this._offsetOrientation) {
  19778. this._offsetOrientation = {
  19779. yaw: yaw,
  19780. pitch: pitch,
  19781. roll: roll
  19782. };
  19783. return;
  19784. } else {
  19785. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19786. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19787. this.rotation.z += this._offsetOrientation.roll - roll;
  19788. this._offsetOrientation.yaw = yaw;
  19789. this._offsetOrientation.pitch = pitch;
  19790. this._offsetOrientation.roll = roll;
  19791. }
  19792. };
  19793. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19794. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19795. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19796. };
  19797. OculusGamepadCamera.prototype.detachControl = function (element) {
  19798. _super.prototype.detachControl.call(this, element);
  19799. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19800. };
  19801. OculusGamepadCamera.prototype.dispose = function () {
  19802. this._gamepads.dispose();
  19803. _super.prototype.dispose.call(this);
  19804. };
  19805. return OculusGamepadCamera;
  19806. })(BABYLON.FreeCamera);
  19807. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19808. })(BABYLON || (BABYLON = {}));
  19809. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19810. var BABYLON;
  19811. (function (BABYLON) {
  19812. // We're mainly based on the logic defined into the FreeCamera code
  19813. var VirtualJoysticksCamera = (function (_super) {
  19814. __extends(VirtualJoysticksCamera, _super);
  19815. function VirtualJoysticksCamera(name, position, scene) {
  19816. _super.call(this, name, position, scene);
  19817. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19818. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19819. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19820. this._leftjoystick.setJoystickSensibility(0.15);
  19821. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19822. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19823. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19824. this._rightjoystick.reverseUpDown = true;
  19825. this._rightjoystick.setJoystickSensibility(0.05);
  19826. this._rightjoystick.setJoystickColor("yellow");
  19827. }
  19828. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19829. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19830. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19831. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19832. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19833. if (!this._leftjoystick.pressed) {
  19834. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19835. }
  19836. if (!this._rightjoystick.pressed) {
  19837. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19838. }
  19839. };
  19840. VirtualJoysticksCamera.prototype.dispose = function () {
  19841. this._leftjoystick.releaseCanvas();
  19842. _super.prototype.dispose.call(this);
  19843. };
  19844. return VirtualJoysticksCamera;
  19845. })(BABYLON.FreeCamera);
  19846. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19847. })(BABYLON || (BABYLON = {}));
  19848. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19849. var BABYLON;
  19850. (function (BABYLON) {
  19851. var ShaderMaterial = (function (_super) {
  19852. __extends(ShaderMaterial, _super);
  19853. function ShaderMaterial(name, scene, shaderPath, options) {
  19854. _super.call(this, name, scene);
  19855. this._textures = new Array();
  19856. this._floats = new Array();
  19857. this._floatsArrays = {};
  19858. this._colors3 = new Array();
  19859. this._colors4 = new Array();
  19860. this._vectors2 = new Array();
  19861. this._vectors3 = new Array();
  19862. this._matrices = new Array();
  19863. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19864. this._shaderPath = shaderPath;
  19865. options.needAlphaBlending = options.needAlphaBlending || false;
  19866. options.needAlphaTesting = options.needAlphaTesting || false;
  19867. options.attributes = options.attributes || ["position", "normal", "uv"];
  19868. options.uniforms = options.uniforms || ["worldViewProjection"];
  19869. options.samplers = options.samplers || [];
  19870. this._options = options;
  19871. }
  19872. ShaderMaterial.prototype.needAlphaBlending = function () {
  19873. return this._options.needAlphaBlending;
  19874. };
  19875. ShaderMaterial.prototype.needAlphaTesting = function () {
  19876. return this._options.needAlphaTesting;
  19877. };
  19878. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19879. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19880. this._options.uniforms.push(uniformName);
  19881. }
  19882. };
  19883. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19884. if (this._options.samplers.indexOf(name) === -1) {
  19885. this._options.samplers.push(name);
  19886. }
  19887. this._textures[name] = texture;
  19888. return this;
  19889. };
  19890. ShaderMaterial.prototype.setFloat = function (name, value) {
  19891. this._checkUniform(name);
  19892. this._floats[name] = value;
  19893. return this;
  19894. };
  19895. ShaderMaterial.prototype.setFloats = function (name, value) {
  19896. this._checkUniform(name);
  19897. this._floatsArrays[name] = value;
  19898. return this;
  19899. };
  19900. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19901. this._checkUniform(name);
  19902. this._colors3[name] = value;
  19903. return this;
  19904. };
  19905. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19906. this._checkUniform(name);
  19907. this._colors4[name] = value;
  19908. return this;
  19909. };
  19910. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19911. this._checkUniform(name);
  19912. this._vectors2[name] = value;
  19913. return this;
  19914. };
  19915. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19916. this._checkUniform(name);
  19917. this._vectors3[name] = value;
  19918. return this;
  19919. };
  19920. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19921. this._checkUniform(name);
  19922. this._matrices[name] = value;
  19923. return this;
  19924. };
  19925. ShaderMaterial.prototype.isReady = function () {
  19926. var scene = this.getScene();
  19927. var engine = scene.getEngine();
  19928. if (!this.checkReadyOnEveryCall) {
  19929. if (this._renderId === scene.getRenderId()) {
  19930. return true;
  19931. }
  19932. }
  19933. var previousEffect = this._effect;
  19934. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19935. if (!this._effect.isReady()) {
  19936. return false;
  19937. }
  19938. if (previousEffect !== this._effect) {
  19939. scene.resetCachedMaterial();
  19940. }
  19941. this._renderId = scene.getRenderId();
  19942. return true;
  19943. };
  19944. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19945. var scene = this.getScene();
  19946. if (this._options.uniforms.indexOf("world") !== -1) {
  19947. this._effect.setMatrix("world", world);
  19948. }
  19949. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19950. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19951. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19952. }
  19953. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19954. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19955. }
  19956. };
  19957. ShaderMaterial.prototype.bind = function (world) {
  19958. // Std values
  19959. this.bindOnlyWorldMatrix(world);
  19960. if (this.getScene().getCachedMaterial() !== this) {
  19961. if (this._options.uniforms.indexOf("view") !== -1) {
  19962. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19963. }
  19964. if (this._options.uniforms.indexOf("projection") !== -1) {
  19965. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19966. }
  19967. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19968. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19969. }
  19970. for (var name in this._textures) {
  19971. this._effect.setTexture(name, this._textures[name]);
  19972. }
  19973. for (name in this._floats) {
  19974. this._effect.setFloat(name, this._floats[name]);
  19975. }
  19976. for (name in this._floatsArrays) {
  19977. this._effect.setArray(name, this._floatsArrays[name]);
  19978. }
  19979. for (name in this._colors3) {
  19980. this._effect.setColor3(name, this._colors3[name]);
  19981. }
  19982. for (name in this._colors4) {
  19983. var color = this._colors4[name];
  19984. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19985. }
  19986. for (name in this._vectors2) {
  19987. this._effect.setVector2(name, this._vectors2[name]);
  19988. }
  19989. for (name in this._vectors3) {
  19990. this._effect.setVector3(name, this._vectors3[name]);
  19991. }
  19992. for (name in this._matrices) {
  19993. this._effect.setMatrix(name, this._matrices[name]);
  19994. }
  19995. }
  19996. _super.prototype.bind.call(this, world, null);
  19997. };
  19998. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19999. for (var name in this._textures) {
  20000. this._textures[name].dispose();
  20001. }
  20002. this._textures = [];
  20003. _super.prototype.dispose.call(this, forceDisposeEffect);
  20004. };
  20005. return ShaderMaterial;
  20006. })(BABYLON.Material);
  20007. BABYLON.ShaderMaterial = ShaderMaterial;
  20008. })(BABYLON || (BABYLON = {}));
  20009. //# sourceMappingURL=babylon.shaderMaterial.js.map
  20010. var BABYLON;
  20011. (function (BABYLON) {
  20012. var VertexData = (function () {
  20013. function VertexData() {
  20014. }
  20015. VertexData.prototype.set = function (data, kind) {
  20016. switch (kind) {
  20017. case BABYLON.VertexBuffer.PositionKind:
  20018. this.positions = data;
  20019. break;
  20020. case BABYLON.VertexBuffer.NormalKind:
  20021. this.normals = data;
  20022. break;
  20023. case BABYLON.VertexBuffer.UVKind:
  20024. this.uvs = data;
  20025. break;
  20026. case BABYLON.VertexBuffer.UV2Kind:
  20027. this.uv2s = data;
  20028. break;
  20029. case BABYLON.VertexBuffer.ColorKind:
  20030. this.colors = data;
  20031. break;
  20032. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20033. this.matricesIndices = data;
  20034. break;
  20035. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20036. this.matricesWeights = data;
  20037. break;
  20038. }
  20039. };
  20040. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20041. this._applyTo(mesh, updatable);
  20042. };
  20043. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20044. this._applyTo(geometry, updatable);
  20045. };
  20046. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20047. this._update(mesh);
  20048. };
  20049. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20050. this._update(geometry);
  20051. };
  20052. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20053. if (this.positions) {
  20054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20055. }
  20056. if (this.normals) {
  20057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20058. }
  20059. if (this.uvs) {
  20060. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20061. }
  20062. if (this.uv2s) {
  20063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20064. }
  20065. if (this.colors) {
  20066. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20067. }
  20068. if (this.matricesIndices) {
  20069. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20070. }
  20071. if (this.matricesWeights) {
  20072. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20073. }
  20074. if (this.indices) {
  20075. meshOrGeometry.setIndices(this.indices);
  20076. }
  20077. };
  20078. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20079. if (this.positions) {
  20080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20081. }
  20082. if (this.normals) {
  20083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20084. }
  20085. if (this.uvs) {
  20086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20087. }
  20088. if (this.uv2s) {
  20089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20090. }
  20091. if (this.colors) {
  20092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20093. }
  20094. if (this.matricesIndices) {
  20095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20096. }
  20097. if (this.matricesWeights) {
  20098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20099. }
  20100. if (this.indices) {
  20101. meshOrGeometry.setIndices(this.indices);
  20102. }
  20103. };
  20104. VertexData.prototype.transform = function (matrix) {
  20105. var transformed = BABYLON.Vector3.Zero();
  20106. if (this.positions) {
  20107. var position = BABYLON.Vector3.Zero();
  20108. for (var index = 0; index < this.positions.length; index += 3) {
  20109. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20110. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20111. this.positions[index] = transformed.x;
  20112. this.positions[index + 1] = transformed.y;
  20113. this.positions[index + 2] = transformed.z;
  20114. }
  20115. }
  20116. if (this.normals) {
  20117. var normal = BABYLON.Vector3.Zero();
  20118. for (index = 0; index < this.normals.length; index += 3) {
  20119. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20120. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20121. this.normals[index] = transformed.x;
  20122. this.normals[index + 1] = transformed.y;
  20123. this.normals[index + 2] = transformed.z;
  20124. }
  20125. }
  20126. };
  20127. VertexData.prototype.merge = function (other) {
  20128. if (other.indices) {
  20129. if (!this.indices) {
  20130. this.indices = [];
  20131. }
  20132. var offset = this.positions ? this.positions.length / 3 : 0;
  20133. for (var index = 0; index < other.indices.length; index++) {
  20134. this.indices.push(other.indices[index] + offset);
  20135. }
  20136. }
  20137. if (other.positions) {
  20138. if (!this.positions) {
  20139. this.positions = [];
  20140. }
  20141. for (index = 0; index < other.positions.length; index++) {
  20142. this.positions.push(other.positions[index]);
  20143. }
  20144. }
  20145. if (other.normals) {
  20146. if (!this.normals) {
  20147. this.normals = [];
  20148. }
  20149. for (index = 0; index < other.normals.length; index++) {
  20150. this.normals.push(other.normals[index]);
  20151. }
  20152. }
  20153. if (other.uvs) {
  20154. if (!this.uvs) {
  20155. this.uvs = [];
  20156. }
  20157. for (index = 0; index < other.uvs.length; index++) {
  20158. this.uvs.push(other.uvs[index]);
  20159. }
  20160. }
  20161. if (other.uv2s) {
  20162. if (!this.uv2s) {
  20163. this.uv2s = [];
  20164. }
  20165. for (index = 0; index < other.uv2s.length; index++) {
  20166. this.uv2s.push(other.uv2s[index]);
  20167. }
  20168. }
  20169. if (other.matricesIndices) {
  20170. if (!this.matricesIndices) {
  20171. this.matricesIndices = [];
  20172. }
  20173. for (index = 0; index < other.matricesIndices.length; index++) {
  20174. this.matricesIndices.push(other.matricesIndices[index]);
  20175. }
  20176. }
  20177. if (other.matricesWeights) {
  20178. if (!this.matricesWeights) {
  20179. this.matricesWeights = [];
  20180. }
  20181. for (index = 0; index < other.matricesWeights.length; index++) {
  20182. this.matricesWeights.push(other.matricesWeights[index]);
  20183. }
  20184. }
  20185. if (other.colors) {
  20186. if (!this.colors) {
  20187. this.colors = [];
  20188. }
  20189. for (index = 0; index < other.colors.length; index++) {
  20190. this.colors.push(other.colors[index]);
  20191. }
  20192. }
  20193. };
  20194. // Statics
  20195. VertexData.ExtractFromMesh = function (mesh) {
  20196. return VertexData._ExtractFrom(mesh);
  20197. };
  20198. VertexData.ExtractFromGeometry = function (geometry) {
  20199. return VertexData._ExtractFrom(geometry);
  20200. };
  20201. VertexData._ExtractFrom = function (meshOrGeometry) {
  20202. var result = new BABYLON.VertexData();
  20203. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20204. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20205. }
  20206. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20207. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20208. }
  20209. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20210. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20211. }
  20212. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20213. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20214. }
  20215. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20216. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20217. }
  20218. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20219. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20220. }
  20221. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20222. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20223. }
  20224. result.indices = meshOrGeometry.getIndices();
  20225. return result;
  20226. };
  20227. VertexData.CreateBox = function (size) {
  20228. var normalsSource = [
  20229. new BABYLON.Vector3(0, 0, 1),
  20230. new BABYLON.Vector3(0, 0, -1),
  20231. new BABYLON.Vector3(1, 0, 0),
  20232. new BABYLON.Vector3(-1, 0, 0),
  20233. new BABYLON.Vector3(0, 1, 0),
  20234. new BABYLON.Vector3(0, -1, 0)
  20235. ];
  20236. var indices = [];
  20237. var positions = [];
  20238. var normals = [];
  20239. var uvs = [];
  20240. size = size || 1;
  20241. for (var index = 0; index < normalsSource.length; index++) {
  20242. var normal = normalsSource[index];
  20243. // Get two vectors perpendicular to the face normal and to each other.
  20244. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20245. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20246. // Six indices (two triangles) per face.
  20247. var verticesLength = positions.length / 3;
  20248. indices.push(verticesLength);
  20249. indices.push(verticesLength + 1);
  20250. indices.push(verticesLength + 2);
  20251. indices.push(verticesLength);
  20252. indices.push(verticesLength + 2);
  20253. indices.push(verticesLength + 3);
  20254. // Four vertices per face.
  20255. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20256. positions.push(vertex.x, vertex.y, vertex.z);
  20257. normals.push(normal.x, normal.y, normal.z);
  20258. uvs.push(1.0, 1.0);
  20259. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20260. positions.push(vertex.x, vertex.y, vertex.z);
  20261. normals.push(normal.x, normal.y, normal.z);
  20262. uvs.push(0.0, 1.0);
  20263. vertex = normal.add(side1).add(side2).scale(size / 2);
  20264. positions.push(vertex.x, vertex.y, vertex.z);
  20265. normals.push(normal.x, normal.y, normal.z);
  20266. uvs.push(0.0, 0.0);
  20267. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20268. positions.push(vertex.x, vertex.y, vertex.z);
  20269. normals.push(normal.x, normal.y, normal.z);
  20270. uvs.push(1.0, 0.0);
  20271. }
  20272. // Result
  20273. var vertexData = new BABYLON.VertexData();
  20274. vertexData.indices = indices;
  20275. vertexData.positions = positions;
  20276. vertexData.normals = normals;
  20277. vertexData.uvs = uvs;
  20278. return vertexData;
  20279. };
  20280. VertexData.CreateSphere = function (segments, diameter) {
  20281. segments = segments || 32;
  20282. diameter = diameter || 1;
  20283. var radius = diameter / 2;
  20284. var totalZRotationSteps = 2 + segments;
  20285. var totalYRotationSteps = 2 * totalZRotationSteps;
  20286. var indices = [];
  20287. var positions = [];
  20288. var normals = [];
  20289. var uvs = [];
  20290. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20291. var normalizedZ = zRotationStep / totalZRotationSteps;
  20292. var angleZ = (normalizedZ * Math.PI);
  20293. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20294. var normalizedY = yRotationStep / totalYRotationSteps;
  20295. var angleY = normalizedY * Math.PI * 2;
  20296. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20297. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20298. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20299. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20300. var vertex = complete.scale(radius);
  20301. var normal = BABYLON.Vector3.Normalize(vertex);
  20302. positions.push(vertex.x, vertex.y, vertex.z);
  20303. normals.push(normal.x, normal.y, normal.z);
  20304. uvs.push(normalizedZ, normalizedY);
  20305. }
  20306. if (zRotationStep > 0) {
  20307. var verticesCount = positions.length / 3;
  20308. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20309. indices.push((firstIndex));
  20310. indices.push((firstIndex + 1));
  20311. indices.push(firstIndex + totalYRotationSteps + 1);
  20312. indices.push((firstIndex + totalYRotationSteps + 1));
  20313. indices.push((firstIndex + 1));
  20314. indices.push((firstIndex + totalYRotationSteps + 2));
  20315. }
  20316. }
  20317. }
  20318. // Result
  20319. var vertexData = new BABYLON.VertexData();
  20320. vertexData.indices = indices;
  20321. vertexData.positions = positions;
  20322. vertexData.normals = normals;
  20323. vertexData.uvs = uvs;
  20324. return vertexData;
  20325. };
  20326. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20327. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20328. var radiusTop = diameterTop / 2;
  20329. var radiusBottom = diameterBottom / 2;
  20330. var indices = [];
  20331. var positions = [];
  20332. var normals = [];
  20333. var uvs = [];
  20334. height = height || 1;
  20335. diameterTop = diameterTop || 0.5;
  20336. diameterBottom = diameterBottom || 1;
  20337. tessellation = tessellation || 16;
  20338. subdivisions = subdivisions || 1;
  20339. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20340. var getCircleVector = function (i) {
  20341. var angle = (i * 2.0 * Math.PI / tessellation);
  20342. var dx = Math.cos(angle);
  20343. var dz = Math.sin(angle);
  20344. return new BABYLON.Vector3(dx, 0, dz);
  20345. };
  20346. var createCylinderCap = function (isTop) {
  20347. var radius = isTop ? radiusTop : radiusBottom;
  20348. if (radius == 0) {
  20349. return;
  20350. }
  20351. var vbase = positions.length / 3;
  20352. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20353. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20354. if (!isTop) {
  20355. offset.scaleInPlace(-1);
  20356. textureScale.x = -textureScale.x;
  20357. }
  20358. for (i = 0; i < tessellation; i++) {
  20359. var circleVector = getCircleVector(i);
  20360. var position = circleVector.scale(radius).add(offset);
  20361. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20362. positions.push(position.x, position.y, position.z);
  20363. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20364. }
  20365. for (var i = 0; i < tessellation - 2; i++) {
  20366. if (!isTop) {
  20367. indices.push(vbase);
  20368. indices.push(vbase + (i + 2) % tessellation);
  20369. indices.push(vbase + (i + 1) % tessellation);
  20370. } else {
  20371. indices.push(vbase);
  20372. indices.push(vbase + (i + 1) % tessellation);
  20373. indices.push(vbase + (i + 2) % tessellation);
  20374. }
  20375. }
  20376. };
  20377. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20378. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20379. var stride = tessellation + 1;
  20380. for (var i = 0; i <= tessellation; i++) {
  20381. var circleVector = getCircleVector(i);
  20382. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20383. var position, radius = radiusBottom;
  20384. for (var s = 0; s <= subdivisions; s++) {
  20385. // Update variables
  20386. position = circleVector.scale(radius);
  20387. position.addInPlace(base.add(offset.scale(s)));
  20388. textureCoordinate.y += 1 / subdivisions;
  20389. radius += (radiusTop - radiusBottom) / subdivisions;
  20390. // Push in arrays
  20391. positions.push(position.x, position.y, position.z);
  20392. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20393. }
  20394. }
  20395. subdivisions += 1;
  20396. for (var s = 0; s < subdivisions - 1; s++) {
  20397. for (var i = 0; i <= tessellation; i++) {
  20398. indices.push(i * subdivisions + s);
  20399. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20400. indices.push(i * subdivisions + (s + 1));
  20401. indices.push(i * subdivisions + (s + 1));
  20402. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20403. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20404. }
  20405. }
  20406. // Create flat triangle fan caps to seal the top and bottom.
  20407. createCylinderCap(true);
  20408. createCylinderCap(false);
  20409. // Normals
  20410. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20411. // Result
  20412. var vertexData = new BABYLON.VertexData();
  20413. vertexData.indices = indices;
  20414. vertexData.positions = positions;
  20415. vertexData.normals = normals;
  20416. vertexData.uvs = uvs;
  20417. return vertexData;
  20418. };
  20419. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20420. var indices = [];
  20421. var positions = [];
  20422. var normals = [];
  20423. var uvs = [];
  20424. diameter = diameter || 1;
  20425. thickness = thickness || 0.5;
  20426. tessellation = tessellation || 16;
  20427. var stride = tessellation + 1;
  20428. for (var i = 0; i <= tessellation; i++) {
  20429. var u = i / tessellation;
  20430. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20431. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20432. for (var j = 0; j <= tessellation; j++) {
  20433. var v = 1 - j / tessellation;
  20434. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20435. var dx = Math.cos(innerAngle);
  20436. var dy = Math.sin(innerAngle);
  20437. // Create a vertex.
  20438. var normal = new BABYLON.Vector3(dx, dy, 0);
  20439. var position = normal.scale(thickness / 2);
  20440. var textureCoordinate = new BABYLON.Vector2(u, v);
  20441. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20442. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20443. positions.push(position.x, position.y, position.z);
  20444. normals.push(normal.x, normal.y, normal.z);
  20445. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20446. // And create indices for two triangles.
  20447. var nextI = (i + 1) % stride;
  20448. var nextJ = (j + 1) % stride;
  20449. indices.push(i * stride + j);
  20450. indices.push(i * stride + nextJ);
  20451. indices.push(nextI * stride + j);
  20452. indices.push(i * stride + nextJ);
  20453. indices.push(nextI * stride + nextJ);
  20454. indices.push(nextI * stride + j);
  20455. }
  20456. }
  20457. // Result
  20458. var vertexData = new BABYLON.VertexData();
  20459. vertexData.indices = indices;
  20460. vertexData.positions = positions;
  20461. vertexData.normals = normals;
  20462. vertexData.uvs = uvs;
  20463. return vertexData;
  20464. };
  20465. VertexData.CreateLines = function (points) {
  20466. var indices = [];
  20467. var positions = [];
  20468. for (var index = 0; index < points.length; index++) {
  20469. positions.push(points[index].x, points[index].y, points[index].z);
  20470. if (index > 0) {
  20471. indices.push(index - 1);
  20472. indices.push(index);
  20473. }
  20474. }
  20475. // Result
  20476. var vertexData = new BABYLON.VertexData();
  20477. vertexData.indices = indices;
  20478. vertexData.positions = positions;
  20479. return vertexData;
  20480. };
  20481. VertexData.CreateGround = function (width, height, subdivisions) {
  20482. var indices = [];
  20483. var positions = [];
  20484. var normals = [];
  20485. var uvs = [];
  20486. var row, col;
  20487. width = width || 1;
  20488. height = height || 1;
  20489. subdivisions = subdivisions || 1;
  20490. for (row = 0; row <= subdivisions; row++) {
  20491. for (col = 0; col <= subdivisions; col++) {
  20492. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20493. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20494. positions.push(position.x, position.y, position.z);
  20495. normals.push(normal.x, normal.y, normal.z);
  20496. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20497. }
  20498. }
  20499. for (row = 0; row < subdivisions; row++) {
  20500. for (col = 0; col < subdivisions; col++) {
  20501. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20502. indices.push(col + 1 + row * (subdivisions + 1));
  20503. indices.push(col + row * (subdivisions + 1));
  20504. indices.push(col + (row + 1) * (subdivisions + 1));
  20505. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20506. indices.push(col + row * (subdivisions + 1));
  20507. }
  20508. }
  20509. // Result
  20510. var vertexData = new BABYLON.VertexData();
  20511. vertexData.indices = indices;
  20512. vertexData.positions = positions;
  20513. vertexData.normals = normals;
  20514. vertexData.uvs = uvs;
  20515. return vertexData;
  20516. };
  20517. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  20518. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  20519. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  20520. var indices = [];
  20521. var positions = [];
  20522. var normals = [];
  20523. var uvs = [];
  20524. var row, col, tileRow, tileCol;
  20525. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  20526. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  20527. precision.w = (precision.w < 1) ? 1 : precision.w;
  20528. precision.h = (precision.h < 1) ? 1 : precision.h;
  20529. var tileSize = {
  20530. 'w': (xmax - xmin) / subdivisions.w,
  20531. 'h': (zmax - zmin) / subdivisions.h
  20532. };
  20533. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  20534. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  20535. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  20536. }
  20537. }
  20538. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  20539. // Indices
  20540. var base = positions.length / 3;
  20541. var rowLength = precision.w + 1;
  20542. for (row = 0; row < precision.h; row++) {
  20543. for (col = 0; col < precision.w; col++) {
  20544. var square = [
  20545. base + col + row * rowLength,
  20546. base + (col + 1) + row * rowLength,
  20547. base + (col + 1) + (row + 1) * rowLength,
  20548. base + col + (row + 1) * rowLength
  20549. ];
  20550. indices.push(square[1]);
  20551. indices.push(square[2]);
  20552. indices.push(square[3]);
  20553. indices.push(square[0]);
  20554. indices.push(square[1]);
  20555. indices.push(square[3]);
  20556. }
  20557. }
  20558. // Position, normals and uvs
  20559. var position = BABYLON.Vector3.Zero();
  20560. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20561. for (row = 0; row <= precision.h; row++) {
  20562. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  20563. for (col = 0; col <= precision.w; col++) {
  20564. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  20565. position.y = 0;
  20566. positions.push(position.x, position.y, position.z);
  20567. normals.push(normal.x, normal.y, normal.z);
  20568. uvs.push(col / precision.w, row / precision.h);
  20569. }
  20570. }
  20571. }
  20572. // Result
  20573. var vertexData = new BABYLON.VertexData();
  20574. vertexData.indices = indices;
  20575. vertexData.positions = positions;
  20576. vertexData.normals = normals;
  20577. vertexData.uvs = uvs;
  20578. return vertexData;
  20579. };
  20580. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  20581. var indices = [];
  20582. var positions = [];
  20583. var normals = [];
  20584. var uvs = [];
  20585. var row, col;
  20586. for (row = 0; row <= subdivisions; row++) {
  20587. for (col = 0; col <= subdivisions; col++) {
  20588. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20589. // Compute height
  20590. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  20591. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  20592. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  20593. var r = buffer[pos] / 255.0;
  20594. var g = buffer[pos + 1] / 255.0;
  20595. var b = buffer[pos + 2] / 255.0;
  20596. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20597. position.y = minHeight + (maxHeight - minHeight) * gradient;
  20598. // Add vertex
  20599. positions.push(position.x, position.y, position.z);
  20600. normals.push(0, 0, 0);
  20601. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20602. }
  20603. }
  20604. for (row = 0; row < subdivisions; row++) {
  20605. for (col = 0; col < subdivisions; col++) {
  20606. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20607. indices.push(col + 1 + row * (subdivisions + 1));
  20608. indices.push(col + row * (subdivisions + 1));
  20609. indices.push(col + (row + 1) * (subdivisions + 1));
  20610. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20611. indices.push(col + row * (subdivisions + 1));
  20612. }
  20613. }
  20614. // Normals
  20615. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20616. // Result
  20617. var vertexData = new BABYLON.VertexData();
  20618. vertexData.indices = indices;
  20619. vertexData.positions = positions;
  20620. vertexData.normals = normals;
  20621. vertexData.uvs = uvs;
  20622. return vertexData;
  20623. };
  20624. VertexData.CreatePlane = function (size) {
  20625. var indices = [];
  20626. var positions = [];
  20627. var normals = [];
  20628. var uvs = [];
  20629. size = size || 1;
  20630. // Vertices
  20631. var halfSize = size / 2.0;
  20632. positions.push(-halfSize, -halfSize, 0);
  20633. normals.push(0, 0, -1.0);
  20634. uvs.push(0.0, 0.0);
  20635. positions.push(halfSize, -halfSize, 0);
  20636. normals.push(0, 0, -1.0);
  20637. uvs.push(1.0, 0.0);
  20638. positions.push(halfSize, halfSize, 0);
  20639. normals.push(0, 0, -1.0);
  20640. uvs.push(1.0, 1.0);
  20641. positions.push(-halfSize, halfSize, 0);
  20642. normals.push(0, 0, -1.0);
  20643. uvs.push(0.0, 1.0);
  20644. // Indices
  20645. indices.push(0);
  20646. indices.push(1);
  20647. indices.push(2);
  20648. indices.push(0);
  20649. indices.push(2);
  20650. indices.push(3);
  20651. // Result
  20652. var vertexData = new BABYLON.VertexData();
  20653. vertexData.indices = indices;
  20654. vertexData.positions = positions;
  20655. vertexData.normals = normals;
  20656. vertexData.uvs = uvs;
  20657. return vertexData;
  20658. };
  20659. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20660. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20661. var indices = [];
  20662. var positions = [];
  20663. var normals = [];
  20664. var uvs = [];
  20665. radius = radius || 2;
  20666. tube = tube || 0.5;
  20667. radialSegments = radialSegments || 32;
  20668. tubularSegments = tubularSegments || 32;
  20669. p = p || 2;
  20670. q = q || 3;
  20671. // Helper
  20672. var getPos = function (angle) {
  20673. var cu = Math.cos(angle);
  20674. var su = Math.sin(angle);
  20675. var quOverP = q / p * angle;
  20676. var cs = Math.cos(quOverP);
  20677. var tx = radius * (2 + cs) * 0.5 * cu;
  20678. var ty = radius * (2 + cs) * su * 0.5;
  20679. var tz = radius * Math.sin(quOverP) * 0.5;
  20680. return new BABYLON.Vector3(tx, ty, tz);
  20681. };
  20682. for (var i = 0; i <= radialSegments; i++) {
  20683. var modI = i % radialSegments;
  20684. var u = modI / radialSegments * 2 * p * Math.PI;
  20685. var p1 = getPos(u);
  20686. var p2 = getPos(u + 0.01);
  20687. var tang = p2.subtract(p1);
  20688. var n = p2.add(p1);
  20689. var bitan = BABYLON.Vector3.Cross(tang, n);
  20690. n = BABYLON.Vector3.Cross(bitan, tang);
  20691. bitan.normalize();
  20692. n.normalize();
  20693. for (var j = 0; j < tubularSegments; j++) {
  20694. var modJ = j % tubularSegments;
  20695. var v = modJ / tubularSegments * 2 * Math.PI;
  20696. var cx = -tube * Math.cos(v);
  20697. var cy = tube * Math.sin(v);
  20698. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20699. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20700. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20701. uvs.push(i / radialSegments);
  20702. uvs.push(j / tubularSegments);
  20703. }
  20704. }
  20705. for (i = 0; i < radialSegments; i++) {
  20706. for (j = 0; j < tubularSegments; j++) {
  20707. var jNext = (j + 1) % tubularSegments;
  20708. var a = i * tubularSegments + j;
  20709. var b = (i + 1) * tubularSegments + j;
  20710. var c = (i + 1) * tubularSegments + jNext;
  20711. var d = i * tubularSegments + jNext;
  20712. indices.push(d);
  20713. indices.push(b);
  20714. indices.push(a);
  20715. indices.push(d);
  20716. indices.push(c);
  20717. indices.push(b);
  20718. }
  20719. }
  20720. // Normals
  20721. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20722. // Result
  20723. var vertexData = new BABYLON.VertexData();
  20724. vertexData.indices = indices;
  20725. vertexData.positions = positions;
  20726. vertexData.normals = normals;
  20727. vertexData.uvs = uvs;
  20728. return vertexData;
  20729. };
  20730. // Tools
  20731. VertexData.ComputeNormals = function (positions, indices, normals) {
  20732. var positionVectors = [];
  20733. var facesOfVertices = [];
  20734. var index;
  20735. for (index = 0; index < positions.length; index += 3) {
  20736. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20737. positionVectors.push(vector3);
  20738. facesOfVertices.push([]);
  20739. }
  20740. // Compute normals
  20741. var facesNormals = [];
  20742. for (index = 0; index < indices.length / 3; index++) {
  20743. var i1 = indices[index * 3];
  20744. var i2 = indices[index * 3 + 1];
  20745. var i3 = indices[index * 3 + 2];
  20746. var p1 = positionVectors[i1];
  20747. var p2 = positionVectors[i2];
  20748. var p3 = positionVectors[i3];
  20749. var p1p2 = p1.subtract(p2);
  20750. var p3p2 = p3.subtract(p2);
  20751. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20752. facesOfVertices[i1].push(index);
  20753. facesOfVertices[i2].push(index);
  20754. facesOfVertices[i3].push(index);
  20755. }
  20756. for (index = 0; index < positionVectors.length; index++) {
  20757. var faces = facesOfVertices[index];
  20758. var normal = BABYLON.Vector3.Zero();
  20759. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20760. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20761. }
  20762. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20763. normals[index * 3] = normal.x;
  20764. normals[index * 3 + 1] = normal.y;
  20765. normals[index * 3 + 2] = normal.z;
  20766. }
  20767. };
  20768. return VertexData;
  20769. })();
  20770. BABYLON.VertexData = VertexData;
  20771. })(BABYLON || (BABYLON = {}));
  20772. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20773. var BABYLON;
  20774. (function (BABYLON) {
  20775. var buildCamera = function (that, name) {
  20776. that._leftCamera.isIntermediate = true;
  20777. that.subCameras.push(that._leftCamera);
  20778. that.subCameras.push(that._rightCamera);
  20779. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20780. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20781. that._anaglyphPostProcess.onApply = function (effect) {
  20782. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20783. };
  20784. that._update();
  20785. };
  20786. var AnaglyphArcRotateCamera = (function (_super) {
  20787. __extends(AnaglyphArcRotateCamera, _super);
  20788. // ANY
  20789. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20790. _super.call(this, name, alpha, beta, radius, target, scene);
  20791. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20792. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20793. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20794. buildCamera(this, name);
  20795. }
  20796. AnaglyphArcRotateCamera.prototype._update = function () {
  20797. this._updateCamera(this._leftCamera);
  20798. this._updateCamera(this._rightCamera);
  20799. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20800. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20801. _super.prototype._update.call(this);
  20802. };
  20803. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20804. camera.beta = this.beta;
  20805. camera.radius = this.radius;
  20806. camera.minZ = this.minZ;
  20807. camera.maxZ = this.maxZ;
  20808. camera.fov = this.fov;
  20809. camera.target = this.target;
  20810. };
  20811. return AnaglyphArcRotateCamera;
  20812. })(BABYLON.ArcRotateCamera);
  20813. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20814. var AnaglyphFreeCamera = (function (_super) {
  20815. __extends(AnaglyphFreeCamera, _super);
  20816. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20817. _super.call(this, name, position, scene);
  20818. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20819. this._transformMatrix = new BABYLON.Matrix();
  20820. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20821. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20822. buildCamera(this, name);
  20823. }
  20824. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20825. var target = this.getTarget();
  20826. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20827. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20828. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20829. };
  20830. AnaglyphFreeCamera.prototype._update = function () {
  20831. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20832. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20833. this._updateCamera(this._leftCamera);
  20834. this._updateCamera(this._rightCamera);
  20835. _super.prototype._update.call(this);
  20836. };
  20837. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20838. camera.minZ = this.minZ;
  20839. camera.maxZ = this.maxZ;
  20840. camera.fov = this.fov;
  20841. camera.viewport = this.viewport;
  20842. camera.setTarget(this.getTarget());
  20843. };
  20844. return AnaglyphFreeCamera;
  20845. })(BABYLON.FreeCamera);
  20846. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20847. })(BABYLON || (BABYLON = {}));
  20848. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20849. var BABYLON;
  20850. (function (BABYLON) {
  20851. var AnaglyphPostProcess = (function (_super) {
  20852. __extends(AnaglyphPostProcess, _super);
  20853. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20854. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20855. }
  20856. return AnaglyphPostProcess;
  20857. })(BABYLON.PostProcess);
  20858. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20859. })(BABYLON || (BABYLON = {}));
  20860. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20861. var BABYLON;
  20862. (function (BABYLON) {
  20863. var Tags = (function () {
  20864. function Tags() {
  20865. }
  20866. Tags.EnableFor = function (obj) {
  20867. obj._tags = obj._tags || {};
  20868. obj.hasTags = function () {
  20869. return Tags.HasTags(obj);
  20870. };
  20871. obj.addTags = function (tagsString) {
  20872. return Tags.AddTagsTo(obj, tagsString);
  20873. };
  20874. obj.removeTags = function (tagsString) {
  20875. return Tags.RemoveTagsFrom(obj, tagsString);
  20876. };
  20877. obj.matchesTagsQuery = function (tagsQuery) {
  20878. return Tags.MatchesQuery(obj, tagsQuery);
  20879. };
  20880. };
  20881. Tags.DisableFor = function (obj) {
  20882. delete obj._tags;
  20883. delete obj.hasTags;
  20884. delete obj.addTags;
  20885. delete obj.removeTags;
  20886. delete obj.matchesTagsQuery;
  20887. };
  20888. Tags.HasTags = function (obj) {
  20889. if (!obj._tags) {
  20890. return false;
  20891. }
  20892. return !BABYLON.Tools.IsEmpty(obj._tags);
  20893. };
  20894. Tags.GetTags = function (obj) {
  20895. if (!obj._tags) {
  20896. return null;
  20897. }
  20898. return obj._tags;
  20899. };
  20900. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20901. // a tag cannot start with '||', '&&', and '!'
  20902. // it cannot contain whitespaces
  20903. Tags.AddTagsTo = function (obj, tagsString) {
  20904. if (!tagsString) {
  20905. return;
  20906. }
  20907. var tags = tagsString.split(" ");
  20908. for (var t in tags) {
  20909. Tags._AddTagTo(obj, tags[t]);
  20910. }
  20911. };
  20912. Tags._AddTagTo = function (obj, tag) {
  20913. tag = tag.trim();
  20914. if (tag === "" || tag === "true" || tag === "false") {
  20915. return;
  20916. }
  20917. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20918. return;
  20919. }
  20920. Tags.EnableFor(obj);
  20921. obj._tags[tag] = true;
  20922. };
  20923. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20924. if (!Tags.HasTags(obj)) {
  20925. return;
  20926. }
  20927. var tags = tagsString.split(" ");
  20928. for (var t in tags) {
  20929. Tags._RemoveTagFrom(obj, tags[t]);
  20930. }
  20931. };
  20932. Tags._RemoveTagFrom = function (obj, tag) {
  20933. delete obj._tags[tag];
  20934. };
  20935. Tags.MatchesQuery = function (obj, tagsQuery) {
  20936. if (tagsQuery === undefined) {
  20937. return true;
  20938. }
  20939. if (tagsQuery === "") {
  20940. return Tags.HasTags(obj);
  20941. }
  20942. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20943. return Tags.HasTags(obj) && obj._tags[r];
  20944. });
  20945. };
  20946. return Tags;
  20947. })();
  20948. BABYLON.Tags = Tags;
  20949. })(BABYLON || (BABYLON = {}));
  20950. //# sourceMappingURL=babylon.tags.js.map
  20951. var BABYLON;
  20952. (function (BABYLON) {
  20953. (function (Internals) {
  20954. var AndOrNotEvaluator = (function () {
  20955. function AndOrNotEvaluator() {
  20956. }
  20957. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20958. if (!query.match(/\([^\(\)]*\)/g)) {
  20959. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20960. } else {
  20961. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20962. // remove parenthesis
  20963. r = r.slice(1, r.length - 1);
  20964. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20965. });
  20966. }
  20967. if (query === "true") {
  20968. return true;
  20969. }
  20970. if (query === "false") {
  20971. return false;
  20972. }
  20973. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20974. };
  20975. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20976. evaluateCallback = evaluateCallback || (function (r) {
  20977. return r === "true" ? true : false;
  20978. });
  20979. var result;
  20980. var or = parenthesisContent.split("||");
  20981. for (var i in or) {
  20982. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20983. var and = ori.split("&&");
  20984. if (and.length > 1) {
  20985. for (var j = 0; j < and.length; ++j) {
  20986. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20987. if (andj !== "true" && andj !== "false") {
  20988. if (andj[0] === "!") {
  20989. result = !evaluateCallback(andj.substring(1));
  20990. } else {
  20991. result = evaluateCallback(andj);
  20992. }
  20993. } else {
  20994. result = andj === "true" ? true : false;
  20995. }
  20996. if (!result) {
  20997. ori = "false";
  20998. break;
  20999. }
  21000. }
  21001. }
  21002. if (result || ori === "true") {
  21003. result = true;
  21004. break;
  21005. }
  21006. // result equals false (or undefined)
  21007. if (ori !== "true" && ori !== "false") {
  21008. if (ori[0] === "!") {
  21009. result = !evaluateCallback(ori.substring(1));
  21010. } else {
  21011. result = evaluateCallback(ori);
  21012. }
  21013. } else {
  21014. result = ori === "true" ? true : false;
  21015. }
  21016. }
  21017. // the whole parenthesis scope is replaced by 'true' or 'false'
  21018. return result ? "true" : "false";
  21019. };
  21020. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21021. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21022. // remove whitespaces
  21023. r = r.replace(/[\s]/g, function () {
  21024. return "";
  21025. });
  21026. return r.length % 2 ? "!" : "";
  21027. });
  21028. booleanString = booleanString.trim();
  21029. if (booleanString === "!true") {
  21030. booleanString = "false";
  21031. } else if (booleanString === "!false") {
  21032. booleanString = "true";
  21033. }
  21034. return booleanString;
  21035. };
  21036. return AndOrNotEvaluator;
  21037. })();
  21038. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21039. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21040. var Internals = BABYLON.Internals;
  21041. })(BABYLON || (BABYLON = {}));
  21042. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  21043. var BABYLON;
  21044. (function (BABYLON) {
  21045. var PostProcessRenderPass = (function () {
  21046. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21047. this._enabled = true;
  21048. this._refCount = 0;
  21049. this._name = name;
  21050. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21051. this.setRenderList(renderList);
  21052. this._renderTexture.onBeforeRender = beforeRender;
  21053. this._renderTexture.onAfterRender = afterRender;
  21054. this._scene = scene;
  21055. this._renderList = renderList;
  21056. }
  21057. // private
  21058. PostProcessRenderPass.prototype._incRefCount = function () {
  21059. if (this._refCount === 0) {
  21060. this._scene.customRenderTargets.push(this._renderTexture);
  21061. }
  21062. return ++this._refCount;
  21063. };
  21064. PostProcessRenderPass.prototype._decRefCount = function () {
  21065. this._refCount--;
  21066. if (this._refCount <= 0) {
  21067. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21068. }
  21069. return this._refCount;
  21070. };
  21071. PostProcessRenderPass.prototype._update = function () {
  21072. this.setRenderList(this._renderList);
  21073. };
  21074. // public
  21075. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21076. this._renderTexture.renderList = renderList;
  21077. };
  21078. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21079. return this._renderTexture;
  21080. };
  21081. return PostProcessRenderPass;
  21082. })();
  21083. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21084. })(BABYLON || (BABYLON = {}));
  21085. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  21086. var BABYLON;
  21087. (function (BABYLON) {
  21088. var PostProcessRenderEffect = (function () {
  21089. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21090. this._engine = engine;
  21091. this._name = name;
  21092. this._singleInstance = singleInstance || true;
  21093. this._getPostProcess = getPostProcess;
  21094. this._cameras = [];
  21095. this._indicesForCamera = [];
  21096. this._postProcesses = {};
  21097. this._renderPasses = {};
  21098. this._renderEffectAsPasses = {};
  21099. }
  21100. PostProcessRenderEffect.prototype._update = function () {
  21101. for (var renderPassName in this._renderPasses) {
  21102. this._renderPasses[renderPassName]._update();
  21103. }
  21104. };
  21105. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21106. this._renderPasses[renderPass._name] = renderPass;
  21107. this._linkParameters();
  21108. };
  21109. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21110. delete this._renderPasses[renderPass._name];
  21111. this._linkParameters();
  21112. };
  21113. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21114. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21115. this._linkParameters();
  21116. };
  21117. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21118. for (var renderPassName in this._renderPasses) {
  21119. if (renderPassName === passName) {
  21120. return this._renderPasses[passName];
  21121. }
  21122. }
  21123. };
  21124. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21125. this._renderPasses = {};
  21126. this._linkParameters();
  21127. };
  21128. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21129. var cameraKey;
  21130. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21131. for (var i = 0; i < _cam.length; i++) {
  21132. var camera = _cam[i];
  21133. var cameraName = camera.name;
  21134. if (this._singleInstance) {
  21135. cameraKey = 0;
  21136. } else {
  21137. cameraKey = cameraName;
  21138. }
  21139. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21140. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21141. if (!this._indicesForCamera[cameraName]) {
  21142. this._indicesForCamera[cameraName] = [];
  21143. }
  21144. this._indicesForCamera[cameraName].push(index);
  21145. if (this._cameras.indexOf(camera) === -1) {
  21146. this._cameras[cameraName] = camera;
  21147. }
  21148. for (var passName in this._renderPasses) {
  21149. this._renderPasses[passName]._incRefCount();
  21150. }
  21151. }
  21152. this._linkParameters();
  21153. };
  21154. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21155. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21156. for (var i = 0; i < _cam.length; i++) {
  21157. var camera = _cam[i];
  21158. var cameraName = camera.name;
  21159. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21160. var index = this._cameras.indexOf(cameraName);
  21161. this._indicesForCamera.splice(index, 1);
  21162. this._cameras.splice(index, 1);
  21163. for (var passName in this._renderPasses) {
  21164. this._renderPasses[passName]._decRefCount();
  21165. }
  21166. }
  21167. };
  21168. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21169. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21170. for (var i = 0; i < _cam.length; i++) {
  21171. var camera = _cam[i];
  21172. var cameraName = camera.name;
  21173. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21174. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21175. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21176. }
  21177. }
  21178. for (var passName in this._renderPasses) {
  21179. this._renderPasses[passName]._incRefCount();
  21180. }
  21181. }
  21182. };
  21183. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21184. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21185. for (var i = 0; i < _cam.length; i++) {
  21186. var camera = _cam[i];
  21187. var cameraName = camera.Name;
  21188. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21189. for (var passName in this._renderPasses) {
  21190. this._renderPasses[passName]._decRefCount();
  21191. }
  21192. }
  21193. };
  21194. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21195. if (this._singleInstance) {
  21196. return this._postProcesses[0];
  21197. } else {
  21198. return this._postProcesses[camera.name];
  21199. }
  21200. };
  21201. PostProcessRenderEffect.prototype._linkParameters = function () {
  21202. var _this = this;
  21203. for (var index in this._postProcesses) {
  21204. if (this.applyParameters) {
  21205. this.applyParameters(this._postProcesses[index]);
  21206. }
  21207. this._postProcesses[index].onBeforeRender = function (effect) {
  21208. _this._linkTextures(effect);
  21209. };
  21210. }
  21211. };
  21212. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21213. for (var renderPassName in this._renderPasses) {
  21214. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21215. }
  21216. for (var renderEffectName in this._renderEffectAsPasses) {
  21217. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21218. }
  21219. };
  21220. return PostProcessRenderEffect;
  21221. })();
  21222. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21223. })(BABYLON || (BABYLON = {}));
  21224. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  21225. var BABYLON;
  21226. (function (BABYLON) {
  21227. var PostProcessRenderPipeline = (function () {
  21228. function PostProcessRenderPipeline(engine, name) {
  21229. this._engine = engine;
  21230. this._name = name;
  21231. this._renderEffects = {};
  21232. this._renderEffectsForIsolatedPass = {};
  21233. this._cameras = [];
  21234. }
  21235. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21236. this._renderEffects[renderEffect._name] = renderEffect;
  21237. };
  21238. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21239. var renderEffects = this._renderEffects[renderEffectName];
  21240. if (!renderEffects) {
  21241. return;
  21242. }
  21243. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21244. };
  21245. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21246. var renderEffects = this._renderEffects[renderEffectName];
  21247. if (!renderEffects) {
  21248. return;
  21249. }
  21250. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21251. };
  21252. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21253. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21254. var indicesToDelete = [];
  21255. for (var i = 0; i < _cam.length; i++) {
  21256. var camera = _cam[i];
  21257. var cameraName = camera.name;
  21258. if (this._cameras.indexOf(camera) === -1) {
  21259. this._cameras[cameraName] = camera;
  21260. } else if (unique) {
  21261. indicesToDelete.push(i);
  21262. }
  21263. }
  21264. for (var i = 0; i < indicesToDelete.length; i++) {
  21265. cameras.splice(indicesToDelete[i], 1);
  21266. }
  21267. for (var renderEffectName in this._renderEffects) {
  21268. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21269. }
  21270. };
  21271. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21272. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21273. for (var renderEffectName in this._renderEffects) {
  21274. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21275. }
  21276. for (var i = 0; i < _cam.length; i++) {
  21277. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21278. }
  21279. };
  21280. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21281. var _this = this;
  21282. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21283. var pass = null;
  21284. for (var renderEffectName in this._renderEffects) {
  21285. pass = this._renderEffects[renderEffectName].getPass(passName);
  21286. if (pass != null) {
  21287. break;
  21288. }
  21289. }
  21290. if (pass === null) {
  21291. return;
  21292. }
  21293. for (var renderEffectName in this._renderEffects) {
  21294. this._renderEffects[renderEffectName]._disable(_cam);
  21295. }
  21296. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21297. for (var i = 0; i < _cam.length; i++) {
  21298. var camera = _cam[i];
  21299. var cameraName = camera.name;
  21300. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21301. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21302. });
  21303. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21304. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21305. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21306. }
  21307. };
  21308. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21309. var _this = this;
  21310. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21311. for (var i = 0; i < _cam.length; i++) {
  21312. var camera = _cam[i];
  21313. var cameraName = camera.name;
  21314. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21315. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21316. });
  21317. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21318. }
  21319. for (var renderEffectName in this._renderEffects) {
  21320. this._renderEffects[renderEffectName]._enable(_cam);
  21321. }
  21322. };
  21323. PostProcessRenderPipeline.prototype._update = function () {
  21324. for (var renderEffectName in this._renderEffects) {
  21325. this._renderEffects[renderEffectName]._update();
  21326. }
  21327. for (var i = 0; i < this._cameras.length; i++) {
  21328. var cameraName = this._cameras[i].name;
  21329. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21330. this._renderEffectsForIsolatedPass[cameraName]._update();
  21331. }
  21332. }
  21333. };
  21334. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21335. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21336. return PostProcessRenderPipeline;
  21337. })();
  21338. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21339. })(BABYLON || (BABYLON = {}));
  21340. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  21341. var BABYLON;
  21342. (function (BABYLON) {
  21343. var PostProcessRenderPipelineManager = (function () {
  21344. function PostProcessRenderPipelineManager() {
  21345. this._renderPipelines = {};
  21346. }
  21347. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21348. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21349. };
  21350. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21351. var renderPipeline = this._renderPipelines[renderPipelineName];
  21352. if (!renderPipeline) {
  21353. return;
  21354. }
  21355. renderPipeline._attachCameras(cameras, unique);
  21356. };
  21357. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21358. var renderPipeline = this._renderPipelines[renderPipelineName];
  21359. if (!renderPipeline) {
  21360. return;
  21361. }
  21362. renderPipeline._detachCameras(cameras);
  21363. };
  21364. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21365. var renderPipeline = this._renderPipelines[renderPipelineName];
  21366. if (!renderPipeline) {
  21367. return;
  21368. }
  21369. renderPipeline._enableEffect(renderEffectName, cameras);
  21370. };
  21371. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21372. var renderPipeline = this._renderPipelines[renderPipelineName];
  21373. if (!renderPipeline) {
  21374. return;
  21375. }
  21376. renderPipeline._disableEffect(renderEffectName, cameras);
  21377. };
  21378. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21379. var renderPipeline = this._renderPipelines[renderPipelineName];
  21380. if (!renderPipeline) {
  21381. return;
  21382. }
  21383. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21384. };
  21385. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21386. var renderPipeline = this._renderPipelines[renderPipelineName];
  21387. if (!renderPipeline) {
  21388. return;
  21389. }
  21390. renderPipeline._disableDisplayOnlyPass(cameras);
  21391. };
  21392. PostProcessRenderPipelineManager.prototype.update = function () {
  21393. for (var renderPipelineName in this._renderPipelines) {
  21394. this._renderPipelines[renderPipelineName]._update();
  21395. }
  21396. };
  21397. return PostProcessRenderPipelineManager;
  21398. })();
  21399. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21400. })(BABYLON || (BABYLON = {}));
  21401. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21402. var BABYLON;
  21403. (function (BABYLON) {
  21404. var DisplayPassPostProcess = (function (_super) {
  21405. __extends(DisplayPassPostProcess, _super);
  21406. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21407. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21408. }
  21409. return DisplayPassPostProcess;
  21410. })(BABYLON.PostProcess);
  21411. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21412. })(BABYLON || (BABYLON = {}));
  21413. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  21414. var BABYLON;
  21415. (function (BABYLON) {
  21416. var BoundingBoxRenderer = (function () {
  21417. function BoundingBoxRenderer(scene) {
  21418. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21419. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21420. this.showBackLines = true;
  21421. this.renderList = new BABYLON.SmartArray(32);
  21422. this._scene = scene;
  21423. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21424. attributes: ["position"],
  21425. uniforms: ["worldViewProjection", "color"]
  21426. });
  21427. var engine = this._scene.getEngine();
  21428. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21429. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21430. 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]);
  21431. }
  21432. BoundingBoxRenderer.prototype.reset = function () {
  21433. this.renderList.reset();
  21434. };
  21435. BoundingBoxRenderer.prototype.render = function () {
  21436. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21437. return;
  21438. }
  21439. var engine = this._scene.getEngine();
  21440. engine.setDepthWrite(false);
  21441. this._colorShader._preBind();
  21442. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21443. var boundingBox = this.renderList.data[boundingBoxIndex];
  21444. var min = boundingBox.minimum;
  21445. var max = boundingBox.maximum;
  21446. var diff = max.subtract(min);
  21447. var median = min.add(diff.scale(0.5));
  21448. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21449. // VBOs
  21450. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21451. if (this.showBackLines) {
  21452. // Back
  21453. engine.setDepthFunctionToGreaterOrEqual();
  21454. this._scene.resetCachedMaterial();
  21455. this._colorShader.setColor4("color", this.backColor.toColor4());
  21456. this._colorShader.bind(worldMatrix);
  21457. // Draw order
  21458. engine.draw(false, 0, 24);
  21459. }
  21460. // Front
  21461. engine.setDepthFunctionToLess();
  21462. this._scene.resetCachedMaterial();
  21463. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21464. this._colorShader.bind(worldMatrix);
  21465. // Draw order
  21466. engine.draw(false, 0, 24);
  21467. }
  21468. this._colorShader.unbind();
  21469. engine.setDepthFunctionToLessOrEqual();
  21470. engine.setDepthWrite(true);
  21471. };
  21472. BoundingBoxRenderer.prototype.dispose = function () {
  21473. this._colorShader.dispose();
  21474. this._vb.dispose();
  21475. this._scene.getEngine()._releaseBuffer(this._ib);
  21476. };
  21477. return BoundingBoxRenderer;
  21478. })();
  21479. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21480. })(BABYLON || (BABYLON = {}));
  21481. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  21482. var BABYLON;
  21483. (function (BABYLON) {
  21484. (function (Internals) {
  21485. /*
  21486. * Based on jsTGALoader - Javascript loader for TGA file
  21487. * By Vincent Thibault
  21488. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21489. */
  21490. var TGATools = (function () {
  21491. function TGATools() {
  21492. }
  21493. TGATools.GetTGAHeader = function (data) {
  21494. var offset = 0;
  21495. var header = {
  21496. id_length: data[offset++],
  21497. colormap_type: data[offset++],
  21498. image_type: data[offset++],
  21499. colormap_index: data[offset++] | data[offset++] << 8,
  21500. colormap_length: data[offset++] | data[offset++] << 8,
  21501. colormap_size: data[offset++],
  21502. origin: [
  21503. data[offset++] | data[offset++] << 8,
  21504. data[offset++] | data[offset++] << 8
  21505. ],
  21506. width: data[offset++] | data[offset++] << 8,
  21507. height: data[offset++] | data[offset++] << 8,
  21508. pixel_size: data[offset++],
  21509. flags: data[offset++]
  21510. };
  21511. return header;
  21512. };
  21513. TGATools.UploadContent = function (gl, data) {
  21514. // Not enough data to contain header ?
  21515. if (data.length < 19) {
  21516. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  21517. return;
  21518. }
  21519. // Read Header
  21520. var offset = 18;
  21521. var header = TGATools.GetTGAHeader(data);
  21522. // Assume it's a valid Targa file.
  21523. if (header.id_length + offset > data.length) {
  21524. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  21525. return;
  21526. }
  21527. // Skip not needed data
  21528. offset += header.id_length;
  21529. var use_rle = false;
  21530. var use_pal = false;
  21531. var use_rgb = false;
  21532. var use_grey = false;
  21533. switch (header.image_type) {
  21534. case TGATools._TYPE_RLE_INDEXED:
  21535. use_rle = true;
  21536. case TGATools._TYPE_INDEXED:
  21537. use_pal = true;
  21538. break;
  21539. case TGATools._TYPE_RLE_RGB:
  21540. use_rle = true;
  21541. case TGATools._TYPE_RGB:
  21542. use_rgb = true;
  21543. break;
  21544. case TGATools._TYPE_RLE_GREY:
  21545. use_rle = true;
  21546. case TGATools._TYPE_GREY:
  21547. use_grey = true;
  21548. break;
  21549. }
  21550. var pixel_data;
  21551. var numAlphaBits = header.flags & 0xf;
  21552. var pixel_size = header.pixel_size >> 3;
  21553. var pixel_total = header.width * header.height * pixel_size;
  21554. // Read palettes
  21555. var palettes;
  21556. if (use_pal) {
  21557. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  21558. }
  21559. // Read LRE
  21560. if (use_rle) {
  21561. pixel_data = new Uint8Array(pixel_total);
  21562. var c, count, i;
  21563. var localOffset = 0;
  21564. var pixels = new Uint8Array(pixel_size);
  21565. while (offset < pixel_total && localOffset < pixel_total) {
  21566. c = data[offset++];
  21567. count = (c & 0x7f) + 1;
  21568. // RLE pixels
  21569. if (c & 0x80) {
  21570. for (i = 0; i < pixel_size; ++i) {
  21571. pixels[i] = data[offset++];
  21572. }
  21573. for (i = 0; i < count; ++i) {
  21574. pixel_data.set(pixels, localOffset + i * pixel_size);
  21575. }
  21576. localOffset += pixel_size * count;
  21577. } else {
  21578. count *= pixel_size;
  21579. for (i = 0; i < count; ++i) {
  21580. pixel_data[localOffset + i] = data[offset++];
  21581. }
  21582. localOffset += count;
  21583. }
  21584. }
  21585. } else {
  21586. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  21587. }
  21588. // Load to texture
  21589. var x_start, y_start, x_step, y_step, y_end, x_end;
  21590. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  21591. default:
  21592. case TGATools._ORIGIN_UL:
  21593. x_start = 0;
  21594. x_step = 1;
  21595. x_end = header.width;
  21596. y_start = 0;
  21597. y_step = 1;
  21598. y_end = header.height;
  21599. break;
  21600. case TGATools._ORIGIN_BL:
  21601. x_start = 0;
  21602. x_step = 1;
  21603. x_end = header.width;
  21604. y_start = header.height - 1;
  21605. y_step = -1;
  21606. y_end = -1;
  21607. break;
  21608. case TGATools._ORIGIN_UR:
  21609. x_start = header.width - 1;
  21610. x_step = -1;
  21611. x_end = -1;
  21612. y_start = 0;
  21613. y_step = 1;
  21614. y_end = header.height;
  21615. break;
  21616. case TGATools._ORIGIN_BR:
  21617. x_start = header.width - 1;
  21618. x_step = -1;
  21619. x_end = -1;
  21620. y_start = header.height - 1;
  21621. y_step = -1;
  21622. y_end = -1;
  21623. break;
  21624. }
  21625. // Load the specify method
  21626. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21627. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21628. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21629. };
  21630. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21631. var image = pixel_data, colormap = palettes;
  21632. var width = header.width, height = header.height;
  21633. var color, i = 0, x, y;
  21634. var imageData = new Uint8Array(width * height * 4);
  21635. for (y = y_start; y !== y_end; y += y_step) {
  21636. for (x = x_start; x !== x_end; x += x_step, i++) {
  21637. color = image[i];
  21638. imageData[(x + width * y) * 4 + 3] = 255;
  21639. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21640. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21641. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21642. }
  21643. }
  21644. return imageData;
  21645. };
  21646. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21647. var image = pixel_data;
  21648. var width = header.width, height = header.height;
  21649. var color, i = 0, x, y;
  21650. var imageData = new Uint8Array(width * height * 4);
  21651. for (y = y_start; y !== y_end; y += y_step) {
  21652. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21653. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21654. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21655. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21656. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21657. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21658. }
  21659. }
  21660. return imageData;
  21661. };
  21662. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21663. var image = pixel_data;
  21664. var width = header.width, height = header.height;
  21665. var i = 0, x, y;
  21666. var imageData = new Uint8Array(width * height * 4);
  21667. for (y = y_start; y !== y_end; y += y_step) {
  21668. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21669. imageData[(x + width * y) * 4 + 3] = 255;
  21670. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21671. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21672. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21673. }
  21674. }
  21675. return imageData;
  21676. };
  21677. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21678. var image = pixel_data;
  21679. var width = header.width, height = header.height;
  21680. var i = 0, x, y;
  21681. var imageData = new Uint8Array(width * height * 4);
  21682. for (y = y_start; y !== y_end; y += y_step) {
  21683. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21684. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21685. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21686. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21687. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21688. }
  21689. }
  21690. return imageData;
  21691. };
  21692. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21693. var image = pixel_data;
  21694. var width = header.width, height = header.height;
  21695. var color, i = 0, x, y;
  21696. var imageData = new Uint8Array(width * height * 4);
  21697. for (y = y_start; y !== y_end; y += y_step) {
  21698. for (x = x_start; x !== x_end; x += x_step, i++) {
  21699. color = image[i];
  21700. imageData[(x + width * y) * 4 + 0] = color;
  21701. imageData[(x + width * y) * 4 + 1] = color;
  21702. imageData[(x + width * y) * 4 + 2] = color;
  21703. imageData[(x + width * y) * 4 + 3] = 255;
  21704. }
  21705. }
  21706. return imageData;
  21707. };
  21708. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21709. var image = pixel_data;
  21710. var width = header.width, height = header.height;
  21711. var i = 0, x, y;
  21712. var imageData = new Uint8Array(width * height * 4);
  21713. for (y = y_start; y !== y_end; y += y_step) {
  21714. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21715. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21716. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21717. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21718. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21719. }
  21720. }
  21721. return imageData;
  21722. };
  21723. TGATools._TYPE_NO_DATA = 0;
  21724. TGATools._TYPE_INDEXED = 1;
  21725. TGATools._TYPE_RGB = 2;
  21726. TGATools._TYPE_GREY = 3;
  21727. TGATools._TYPE_RLE_INDEXED = 9;
  21728. TGATools._TYPE_RLE_RGB = 10;
  21729. TGATools._TYPE_RLE_GREY = 11;
  21730. TGATools._ORIGIN_MASK = 0x30;
  21731. TGATools._ORIGIN_SHIFT = 0x04;
  21732. TGATools._ORIGIN_BL = 0x00;
  21733. TGATools._ORIGIN_BR = 0x01;
  21734. TGATools._ORIGIN_UL = 0x02;
  21735. TGATools._ORIGIN_UR = 0x03;
  21736. return TGATools;
  21737. })();
  21738. Internals.TGATools = TGATools;
  21739. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21740. var Internals = BABYLON.Internals;
  21741. })(BABYLON || (BABYLON = {}));
  21742. //# sourceMappingURL=babylon.tools.tga.js.map
  21743. var BABYLON;
  21744. (function (BABYLON) {
  21745. (function (Internals) {
  21746. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21747. // All values and structures referenced from:
  21748. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21749. var DDS_MAGIC = 0x20534444;
  21750. 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;
  21751. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21752. 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;
  21753. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21754. function FourCCToInt32(value) {
  21755. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21756. }
  21757. function Int32ToFourCC(value) {
  21758. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21759. }
  21760. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21761. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21762. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21763. var headerLengthInt = 31;
  21764. // Offsets into the header array
  21765. var off_magic = 0;
  21766. var off_size = 1;
  21767. var off_flags = 2;
  21768. var off_height = 3;
  21769. var off_width = 4;
  21770. var off_mipmapCount = 7;
  21771. var off_pfFlags = 20;
  21772. var off_pfFourCC = 21;
  21773. var off_RGBbpp = 22;
  21774. var off_RMask = 23;
  21775. var off_GMask = 24;
  21776. var off_BMask = 25;
  21777. var off_AMask = 26;
  21778. var off_caps1 = 27;
  21779. var off_caps2 = 28;
  21780. ;
  21781. var DDSTools = (function () {
  21782. function DDSTools() {
  21783. }
  21784. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21785. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21786. var mipmapCount = 1;
  21787. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21788. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21789. }
  21790. return {
  21791. width: header[off_width],
  21792. height: header[off_height],
  21793. mipmapCount: mipmapCount,
  21794. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21795. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21796. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21797. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21798. };
  21799. };
  21800. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21801. var byteArray = new Uint8Array(dataLength);
  21802. var srcData = new Uint8Array(arrayBuffer);
  21803. var index = 0;
  21804. for (var y = height - 1; y >= 0; y--) {
  21805. for (var x = 0; x < width; x++) {
  21806. var srcPos = dataOffset + (x + y * width) * 4;
  21807. byteArray[index + 2] = srcData[srcPos];
  21808. byteArray[index + 1] = srcData[srcPos + 1];
  21809. byteArray[index] = srcData[srcPos + 2];
  21810. byteArray[index + 3] = srcData[srcPos + 3];
  21811. index += 4;
  21812. }
  21813. }
  21814. return byteArray;
  21815. };
  21816. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21817. var byteArray = new Uint8Array(dataLength);
  21818. var srcData = new Uint8Array(arrayBuffer);
  21819. var index = 0;
  21820. for (var y = height - 1; y >= 0; y--) {
  21821. for (var x = 0; x < width; x++) {
  21822. var srcPos = dataOffset + (x + y * width) * 3;
  21823. byteArray[index + 2] = srcData[srcPos];
  21824. byteArray[index + 1] = srcData[srcPos + 1];
  21825. byteArray[index] = srcData[srcPos + 2];
  21826. index += 3;
  21827. }
  21828. }
  21829. return byteArray;
  21830. };
  21831. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21832. var byteArray = new Uint8Array(dataLength);
  21833. var srcData = new Uint8Array(arrayBuffer);
  21834. var index = 0;
  21835. for (var y = height - 1; y >= 0; y--) {
  21836. for (var x = 0; x < width; x++) {
  21837. var srcPos = dataOffset + (x + y * width);
  21838. byteArray[index] = srcData[srcPos];
  21839. index++;
  21840. }
  21841. }
  21842. return byteArray;
  21843. };
  21844. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21845. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21846. if (header[off_magic] != DDS_MAGIC) {
  21847. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21848. return;
  21849. }
  21850. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21851. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21852. return;
  21853. }
  21854. if (info.isFourCC) {
  21855. fourCC = header[off_pfFourCC];
  21856. switch (fourCC) {
  21857. case FOURCC_DXT1:
  21858. blockBytes = 8;
  21859. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21860. break;
  21861. case FOURCC_DXT3:
  21862. blockBytes = 16;
  21863. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21864. break;
  21865. case FOURCC_DXT5:
  21866. blockBytes = 16;
  21867. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21868. break;
  21869. default:
  21870. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21871. return;
  21872. }
  21873. }
  21874. mipmapCount = 1;
  21875. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21876. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21877. }
  21878. var bpp = header[off_RGBbpp];
  21879. for (var face = 0; face < faces; face++) {
  21880. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21881. width = header[off_width];
  21882. height = header[off_height];
  21883. dataOffset = header[off_size] + 4;
  21884. for (i = 0; i < mipmapCount; ++i) {
  21885. if (info.isRGB) {
  21886. if (bpp == 24) {
  21887. dataLength = width * height * 3;
  21888. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21889. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21890. } else {
  21891. dataLength = width * height * 4;
  21892. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21893. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21894. }
  21895. } else if (info.isLuminance) {
  21896. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21897. var unpaddedRowSize = width;
  21898. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21899. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21900. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21901. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21902. } else {
  21903. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21904. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21905. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21906. }
  21907. dataOffset += dataLength;
  21908. width *= 0.5;
  21909. height *= 0.5;
  21910. width = Math.max(1.0, width);
  21911. height = Math.max(1.0, height);
  21912. }
  21913. }
  21914. };
  21915. return DDSTools;
  21916. })();
  21917. Internals.DDSTools = DDSTools;
  21918. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21919. var Internals = BABYLON.Internals;
  21920. })(BABYLON || (BABYLON = {}));
  21921. //# sourceMappingURL=babylon.tools.dds.js.map
  21922. var BABYLON;
  21923. (function (BABYLON) {
  21924. var SmartArray = (function () {
  21925. function SmartArray(capacity) {
  21926. this.length = 0;
  21927. this._duplicateId = 0;
  21928. this.data = new Array(capacity);
  21929. this._id = SmartArray._GlobalId++;
  21930. }
  21931. SmartArray.prototype.push = function (value) {
  21932. this.data[this.length++] = value;
  21933. if (this.length > this.data.length) {
  21934. this.data.length *= 2;
  21935. }
  21936. if (!value.__smartArrayFlags) {
  21937. value.__smartArrayFlags = {};
  21938. }
  21939. value.__smartArrayFlags[this._id] = this._duplicateId;
  21940. };
  21941. SmartArray.prototype.pushNoDuplicate = function (value) {
  21942. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21943. return;
  21944. }
  21945. this.push(value);
  21946. };
  21947. SmartArray.prototype.sort = function (compareFn) {
  21948. this.data.sort(compareFn);
  21949. };
  21950. SmartArray.prototype.reset = function () {
  21951. this.length = 0;
  21952. this._duplicateId++;
  21953. };
  21954. SmartArray.prototype.concat = function (array) {
  21955. if (array.length === 0) {
  21956. return;
  21957. }
  21958. if (this.length + array.length > this.data.length) {
  21959. this.data.length = (this.length + array.length) * 2;
  21960. }
  21961. for (var index = 0; index < array.length; index++) {
  21962. this.data[this.length++] = (array.data || array)[index];
  21963. }
  21964. };
  21965. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21966. if (array.length === 0) {
  21967. return;
  21968. }
  21969. if (this.length + array.length > this.data.length) {
  21970. this.data.length = (this.length + array.length) * 2;
  21971. }
  21972. for (var index = 0; index < array.length; index++) {
  21973. var item = (array.data || array)[index];
  21974. this.pushNoDuplicate(item);
  21975. }
  21976. };
  21977. SmartArray.prototype.indexOf = function (value) {
  21978. var position = this.data.indexOf(value);
  21979. if (position >= this.length) {
  21980. return -1;
  21981. }
  21982. return position;
  21983. };
  21984. SmartArray._GlobalId = 0;
  21985. return SmartArray;
  21986. })();
  21987. BABYLON.SmartArray = SmartArray;
  21988. })(BABYLON || (BABYLON = {}));
  21989. //# sourceMappingURL=babylon.smartArray.js.map
  21990. var BABYLON;
  21991. (function (BABYLON) {
  21992. var CannonJSPlugin = (function () {
  21993. function CannonJSPlugin() {
  21994. this._registeredMeshes = [];
  21995. this._physicsMaterials = [];
  21996. this.updateBodyPosition = function (mesh) {
  21997. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21998. var registeredMesh = this._registeredMeshes[index];
  21999. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22000. var body = registeredMesh.body;
  22001. var center = mesh.getBoundingInfo().boundingBox.center;
  22002. body.position.set(center.x, center.z, center.y);
  22003. body.quaternion.x = mesh.rotationQuaternion.x;
  22004. body.quaternion.z = mesh.rotationQuaternion.y;
  22005. body.quaternion.y = mesh.rotationQuaternion.z;
  22006. body.quaternion.w = -mesh.rotationQuaternion.w;
  22007. return;
  22008. }
  22009. }
  22010. };
  22011. }
  22012. CannonJSPlugin.prototype.initialize = function (iterations) {
  22013. if (typeof iterations === "undefined") { iterations = 10; }
  22014. this._world = new CANNON.World();
  22015. this._world.broadphase = new CANNON.NaiveBroadphase();
  22016. this._world.solver.iterations = iterations;
  22017. };
  22018. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22019. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22020. };
  22021. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22022. this._world.step(delta);
  22023. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22024. var registeredMesh = this._registeredMeshes[index];
  22025. if (registeredMesh.isChild) {
  22026. continue;
  22027. }
  22028. // Body position
  22029. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22030. var deltaPos = registeredMesh.delta;
  22031. if (deltaPos) {
  22032. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22033. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22034. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22035. } else {
  22036. registeredMesh.mesh.position.x = bodyX;
  22037. registeredMesh.mesh.position.y = bodyZ;
  22038. registeredMesh.mesh.position.z = bodyY;
  22039. }
  22040. if (!registeredMesh.mesh.rotationQuaternion) {
  22041. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22042. }
  22043. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22044. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22045. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22046. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22047. }
  22048. };
  22049. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22050. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22051. };
  22052. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22053. this.unregisterMesh(mesh);
  22054. mesh.computeWorldMatrix(true);
  22055. switch (impostor) {
  22056. case BABYLON.PhysicsEngine.SphereImpostor:
  22057. var bbox = mesh.getBoundingInfo().boundingBox;
  22058. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22059. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22060. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22061. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22062. case BABYLON.PhysicsEngine.BoxImpostor:
  22063. bbox = mesh.getBoundingInfo().boundingBox;
  22064. var min = bbox.minimumWorld;
  22065. var max = bbox.maximumWorld;
  22066. var box = max.subtract(min).scale(0.5);
  22067. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22068. case BABYLON.PhysicsEngine.PlaneImpostor:
  22069. return this._createPlane(mesh, options);
  22070. case BABYLON.PhysicsEngine.MeshImpostor:
  22071. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22072. var rawFaces = mesh.getIndices();
  22073. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22074. }
  22075. return null;
  22076. };
  22077. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22078. var shape = new CANNON.Sphere(radius);
  22079. if (!options) {
  22080. return shape;
  22081. }
  22082. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22083. };
  22084. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22085. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22086. if (!options) {
  22087. return shape;
  22088. }
  22089. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22090. };
  22091. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22092. var shape = new CANNON.Plane();
  22093. if (!options) {
  22094. return shape;
  22095. }
  22096. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22097. };
  22098. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22099. var verts = [], faces = [];
  22100. mesh.computeWorldMatrix(true);
  22101. for (var i = 0; i < rawVerts.length; i += 3) {
  22102. var transformed = BABYLON.Vector3.Zero();
  22103. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22104. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22105. }
  22106. for (var j = 0; j < rawFaces.length; j += 3) {
  22107. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22108. }
  22109. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22110. if (!options) {
  22111. return shape;
  22112. }
  22113. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22114. };
  22115. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22116. var index;
  22117. var mat;
  22118. for (index = 0; index < this._physicsMaterials.length; index++) {
  22119. mat = this._physicsMaterials[index];
  22120. if (mat.friction === friction && mat.restitution === restitution) {
  22121. return mat;
  22122. }
  22123. }
  22124. var currentMat = new CANNON.Material();
  22125. currentMat.friction = friction;
  22126. currentMat.restitution = restitution;
  22127. this._physicsMaterials.push(currentMat);
  22128. for (index = 0; index < this._physicsMaterials.length; index++) {
  22129. mat = this._physicsMaterials[index];
  22130. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22131. contactMaterial.contactEquationStiffness = 1e10;
  22132. contactMaterial.contactEquationRegularizationTime = 10;
  22133. this._world.addContactMaterial(contactMaterial);
  22134. }
  22135. return currentMat;
  22136. };
  22137. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22138. var initialRotation = null;
  22139. if (mesh.rotationQuaternion) {
  22140. initialRotation = mesh.rotationQuaternion.clone();
  22141. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22142. }
  22143. // The delta between the mesh position and the mesh bounding box center
  22144. var bbox = mesh.getBoundingInfo().boundingBox;
  22145. var deltaPosition = mesh.position.subtract(bbox.center);
  22146. var material = this._addMaterial(friction, restitution);
  22147. var body = new CANNON.RigidBody(mass, shape, material);
  22148. if (initialRotation) {
  22149. body.quaternion.x = initialRotation.x;
  22150. body.quaternion.z = initialRotation.y;
  22151. body.quaternion.y = initialRotation.z;
  22152. body.quaternion.w = -initialRotation.w;
  22153. }
  22154. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22155. this._world.add(body);
  22156. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22157. return body;
  22158. };
  22159. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22160. var compoundShape = new CANNON.Compound();
  22161. for (var index = 0; index < parts.length; index++) {
  22162. var mesh = parts[index].mesh;
  22163. var shape = this.registerMesh(mesh, parts[index].impostor);
  22164. if (index == 0) {
  22165. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22166. } else {
  22167. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22168. }
  22169. }
  22170. var initialMesh = parts[0].mesh;
  22171. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22172. body.parts = parts;
  22173. return body;
  22174. };
  22175. CannonJSPlugin.prototype._unbindBody = function (body) {
  22176. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22177. var registeredMesh = this._registeredMeshes[index];
  22178. if (registeredMesh.body === body) {
  22179. registeredMesh.body = null;
  22180. registeredMesh.delta = 0;
  22181. }
  22182. }
  22183. };
  22184. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22185. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22186. var registeredMesh = this._registeredMeshes[index];
  22187. if (registeredMesh.mesh === mesh) {
  22188. // Remove body
  22189. if (registeredMesh.body) {
  22190. this._world.remove(registeredMesh.body);
  22191. this._unbindBody(registeredMesh.body);
  22192. }
  22193. this._registeredMeshes.splice(index, 1);
  22194. return;
  22195. }
  22196. }
  22197. };
  22198. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22199. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22200. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22201. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22202. var registeredMesh = this._registeredMeshes[index];
  22203. if (registeredMesh.mesh === mesh) {
  22204. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22205. return;
  22206. }
  22207. }
  22208. };
  22209. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22210. var body1 = null, body2 = null;
  22211. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22212. var registeredMesh = this._registeredMeshes[index];
  22213. if (registeredMesh.mesh === mesh1) {
  22214. body1 = registeredMesh.body;
  22215. } else if (registeredMesh.mesh === mesh2) {
  22216. body2 = registeredMesh.body;
  22217. }
  22218. }
  22219. if (!body1 || !body2) {
  22220. return false;
  22221. }
  22222. 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));
  22223. this._world.addConstraint(constraint);
  22224. return true;
  22225. };
  22226. CannonJSPlugin.prototype.dispose = function () {
  22227. while (this._registeredMeshes.length) {
  22228. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22229. }
  22230. };
  22231. CannonJSPlugin.prototype.isSupported = function () {
  22232. return window.CANNON !== undefined;
  22233. };
  22234. return CannonJSPlugin;
  22235. })();
  22236. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22237. })(BABYLON || (BABYLON = {}));
  22238. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22239. var BABYLON;
  22240. (function (BABYLON) {
  22241. var Condition = (function () {
  22242. function Condition(actionManager) {
  22243. this._actionManager = actionManager;
  22244. }
  22245. Condition.prototype.isValid = function () {
  22246. return true;
  22247. };
  22248. Condition.prototype._getProperty = function (propertyPath) {
  22249. return this._actionManager._getProperty(propertyPath);
  22250. };
  22251. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22252. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22253. };
  22254. return Condition;
  22255. })();
  22256. BABYLON.Condition = Condition;
  22257. var ValueCondition = (function (_super) {
  22258. __extends(ValueCondition, _super);
  22259. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22260. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  22261. _super.call(this, actionManager);
  22262. this.propertyPath = propertyPath;
  22263. this.value = value;
  22264. this.operator = operator;
  22265. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22266. this._property = this._getProperty(this.propertyPath);
  22267. }
  22268. Object.defineProperty(ValueCondition, "IsEqual", {
  22269. get: function () {
  22270. return ValueCondition._IsEqual;
  22271. },
  22272. enumerable: true,
  22273. configurable: true
  22274. });
  22275. Object.defineProperty(ValueCondition, "IsDifferent", {
  22276. get: function () {
  22277. return ValueCondition._IsDifferent;
  22278. },
  22279. enumerable: true,
  22280. configurable: true
  22281. });
  22282. Object.defineProperty(ValueCondition, "IsGreater", {
  22283. get: function () {
  22284. return ValueCondition._IsGreater;
  22285. },
  22286. enumerable: true,
  22287. configurable: true
  22288. });
  22289. Object.defineProperty(ValueCondition, "IsLesser", {
  22290. get: function () {
  22291. return ValueCondition._IsLesser;
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. // Methods
  22297. ValueCondition.prototype.isValid = function () {
  22298. switch (this.operator) {
  22299. case ValueCondition.IsGreater:
  22300. return this._target[this._property] > this.value;
  22301. case ValueCondition.IsLesser:
  22302. return this._target[this._property] < this.value;
  22303. case ValueCondition.IsEqual:
  22304. case ValueCondition.IsDifferent:
  22305. var check;
  22306. if (this.value.equals) {
  22307. check = this.value.equals(this._target[this._property]);
  22308. } else {
  22309. check = this.value === this._target[this._property];
  22310. }
  22311. return this.operator === ValueCondition.IsEqual ? check : !check;
  22312. }
  22313. return false;
  22314. };
  22315. ValueCondition._IsEqual = 0;
  22316. ValueCondition._IsDifferent = 1;
  22317. ValueCondition._IsGreater = 2;
  22318. ValueCondition._IsLesser = 3;
  22319. return ValueCondition;
  22320. })(Condition);
  22321. BABYLON.ValueCondition = ValueCondition;
  22322. var PredicateCondition = (function (_super) {
  22323. __extends(PredicateCondition, _super);
  22324. function PredicateCondition(actionManager, predicate) {
  22325. _super.call(this, actionManager);
  22326. this.predicate = predicate;
  22327. }
  22328. PredicateCondition.prototype.isValid = function () {
  22329. return this.predicate();
  22330. };
  22331. return PredicateCondition;
  22332. })(Condition);
  22333. BABYLON.PredicateCondition = PredicateCondition;
  22334. var StateCondition = (function (_super) {
  22335. __extends(StateCondition, _super);
  22336. function StateCondition(actionManager, target, value) {
  22337. _super.call(this, actionManager);
  22338. this.value = value;
  22339. this._target = target;
  22340. }
  22341. // Methods
  22342. StateCondition.prototype.isValid = function () {
  22343. return this._target.state === this.value;
  22344. };
  22345. return StateCondition;
  22346. })(Condition);
  22347. BABYLON.StateCondition = StateCondition;
  22348. })(BABYLON || (BABYLON = {}));
  22349. //# sourceMappingURL=babylon.condition.js.map
  22350. var BABYLON;
  22351. (function (BABYLON) {
  22352. var Action = (function () {
  22353. function Action(triggerOptions, condition) {
  22354. this.triggerOptions = triggerOptions;
  22355. if (triggerOptions.parameter) {
  22356. this.trigger = triggerOptions.trigger;
  22357. this._triggerParameter = triggerOptions.parameter;
  22358. } else {
  22359. this.trigger = triggerOptions;
  22360. }
  22361. this._nextActiveAction = this;
  22362. this._condition = condition;
  22363. }
  22364. // Methods
  22365. Action.prototype._prepare = function () {
  22366. };
  22367. Action.prototype.getTriggerParameter = function () {
  22368. return this._triggerParameter;
  22369. };
  22370. Action.prototype._executeCurrent = function (evt) {
  22371. if (this._condition) {
  22372. var currentRenderId = this._actionManager.getScene().getRenderId();
  22373. // We cache the current evaluation for the current frame
  22374. if (this._condition._evaluationId === currentRenderId) {
  22375. if (!this._condition._currentResult) {
  22376. return;
  22377. }
  22378. } else {
  22379. this._condition._evaluationId = currentRenderId;
  22380. if (!this._condition.isValid()) {
  22381. this._condition._currentResult = false;
  22382. return;
  22383. }
  22384. this._condition._currentResult = true;
  22385. }
  22386. }
  22387. this._nextActiveAction.execute(evt);
  22388. if (this._nextActiveAction._child) {
  22389. if (!this._nextActiveAction._child._actionManager) {
  22390. this._nextActiveAction._child._actionManager = this._actionManager;
  22391. }
  22392. this._nextActiveAction = this._nextActiveAction._child;
  22393. } else {
  22394. this._nextActiveAction = this;
  22395. }
  22396. };
  22397. Action.prototype.execute = function (evt) {
  22398. };
  22399. Action.prototype.then = function (action) {
  22400. this._child = action;
  22401. action._actionManager = this._actionManager;
  22402. action._prepare();
  22403. return action;
  22404. };
  22405. Action.prototype._getProperty = function (propertyPath) {
  22406. return this._actionManager._getProperty(propertyPath);
  22407. };
  22408. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22409. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22410. };
  22411. return Action;
  22412. })();
  22413. BABYLON.Action = Action;
  22414. })(BABYLON || (BABYLON = {}));
  22415. //# sourceMappingURL=babylon.action.js.map
  22416. var BABYLON;
  22417. (function (BABYLON) {
  22418. /**
  22419. * ActionEvent is the event beint sent when an action is triggered.
  22420. */
  22421. var ActionEvent = (function () {
  22422. /**
  22423. * @constructor
  22424. * @param source The mesh that triggered the action.
  22425. * @param pointerX the X mouse cursor position at the time of the event
  22426. * @param pointerY the Y mouse cursor position at the time of the event
  22427. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  22428. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  22429. */
  22430. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22431. this.source = source;
  22432. this.pointerX = pointerX;
  22433. this.pointerY = pointerY;
  22434. this.meshUnderPointer = meshUnderPointer;
  22435. this.sourceEvent = sourceEvent;
  22436. }
  22437. /**
  22438. * Helper function to auto-create an ActionEvent from a source mesh.
  22439. * @param source the source mesh that triggered the event
  22440. * @param evt {Event} The original (browser) event
  22441. */
  22442. ActionEvent.CreateNew = function (source, evt) {
  22443. var scene = source.getScene();
  22444. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22445. };
  22446. /**
  22447. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  22448. * @param scene the scene where the event occurred
  22449. * @param evt {Event} The original (browser) event
  22450. */
  22451. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22452. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22453. };
  22454. return ActionEvent;
  22455. })();
  22456. BABYLON.ActionEvent = ActionEvent;
  22457. /**
  22458. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  22459. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  22460. */
  22461. var ActionManager = (function () {
  22462. function ActionManager(scene) {
  22463. // Members
  22464. this.actions = new Array();
  22465. this._scene = scene;
  22466. scene._actionManagers.push(this);
  22467. }
  22468. Object.defineProperty(ActionManager, "NothingTrigger", {
  22469. get: function () {
  22470. return ActionManager._NothingTrigger;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22476. get: function () {
  22477. return ActionManager._OnPickTrigger;
  22478. },
  22479. enumerable: true,
  22480. configurable: true
  22481. });
  22482. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22483. get: function () {
  22484. return ActionManager._OnLeftPickTrigger;
  22485. },
  22486. enumerable: true,
  22487. configurable: true
  22488. });
  22489. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22490. get: function () {
  22491. return ActionManager._OnRightPickTrigger;
  22492. },
  22493. enumerable: true,
  22494. configurable: true
  22495. });
  22496. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  22497. get: function () {
  22498. return ActionManager._OnCenterPickTrigger;
  22499. },
  22500. enumerable: true,
  22501. configurable: true
  22502. });
  22503. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  22504. get: function () {
  22505. return ActionManager._OnPointerOverTrigger;
  22506. },
  22507. enumerable: true,
  22508. configurable: true
  22509. });
  22510. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  22511. get: function () {
  22512. return ActionManager._OnPointerOutTrigger;
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  22518. get: function () {
  22519. return ActionManager._OnEveryFrameTrigger;
  22520. },
  22521. enumerable: true,
  22522. configurable: true
  22523. });
  22524. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  22525. get: function () {
  22526. return ActionManager._OnIntersectionEnterTrigger;
  22527. },
  22528. enumerable: true,
  22529. configurable: true
  22530. });
  22531. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  22532. get: function () {
  22533. return ActionManager._OnIntersectionExitTrigger;
  22534. },
  22535. enumerable: true,
  22536. configurable: true
  22537. });
  22538. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  22539. get: function () {
  22540. return ActionManager._OnKeyDownTrigger;
  22541. },
  22542. enumerable: true,
  22543. configurable: true
  22544. });
  22545. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  22546. get: function () {
  22547. return ActionManager._OnKeyUpTrigger;
  22548. },
  22549. enumerable: true,
  22550. configurable: true
  22551. });
  22552. // Methods
  22553. ActionManager.prototype.dispose = function () {
  22554. var index = this._scene._actionManagers.indexOf(this);
  22555. if (index > -1) {
  22556. this._scene._actionManagers.splice(index, 1);
  22557. }
  22558. };
  22559. ActionManager.prototype.getScene = function () {
  22560. return this._scene;
  22561. };
  22562. /**
  22563. * Does this action manager handles actions of any of the given triggers
  22564. * @param {number[]} triggers - the triggers to be tested
  22565. * @return {boolean} whether one (or more) of the triggers is handeled
  22566. */
  22567. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  22568. for (var index = 0; index < this.actions.length; index++) {
  22569. var action = this.actions[index];
  22570. if (triggers.indexOf(action.trigger) > -1) {
  22571. return true;
  22572. }
  22573. }
  22574. return false;
  22575. };
  22576. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  22577. /**
  22578. * Does this action manager has pointer triggers
  22579. * @return {boolean} whether or not it has pointer triggers
  22580. */
  22581. get: function () {
  22582. for (var index = 0; index < this.actions.length; index++) {
  22583. var action = this.actions[index];
  22584. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  22585. return true;
  22586. }
  22587. }
  22588. return false;
  22589. },
  22590. enumerable: true,
  22591. configurable: true
  22592. });
  22593. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  22594. /**
  22595. * Does this action manager has pick triggers
  22596. * @return {boolean} whether or not it has pick triggers
  22597. */
  22598. get: function () {
  22599. for (var index = 0; index < this.actions.length; index++) {
  22600. var action = this.actions[index];
  22601. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  22602. return true;
  22603. }
  22604. }
  22605. return false;
  22606. },
  22607. enumerable: true,
  22608. configurable: true
  22609. });
  22610. /**
  22611. * Registers an action to this action manager
  22612. * @param {BABYLON.Action} action - the action to be registered
  22613. * @return {BABYLON.Action} the action amended (prepared) after registration
  22614. */
  22615. ActionManager.prototype.registerAction = function (action) {
  22616. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  22617. if (this.getScene().actionManager !== this) {
  22618. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  22619. return null;
  22620. }
  22621. }
  22622. this.actions.push(action);
  22623. action._actionManager = this;
  22624. action._prepare();
  22625. return action;
  22626. };
  22627. /**
  22628. * Process a specific trigger
  22629. * @param {number} trigger - the trigger to process
  22630. * @param evt {BABYLON.ActionEvent} the event details to be processed
  22631. */
  22632. ActionManager.prototype.processTrigger = function (trigger, evt) {
  22633. for (var index = 0; index < this.actions.length; index++) {
  22634. var action = this.actions[index];
  22635. if (action.trigger === trigger) {
  22636. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  22637. var parameter = action.getTriggerParameter();
  22638. if (parameter) {
  22639. if (evt.sourceEvent.key !== parameter) {
  22640. continue;
  22641. }
  22642. }
  22643. }
  22644. action._executeCurrent(evt);
  22645. }
  22646. }
  22647. };
  22648. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  22649. var properties = propertyPath.split(".");
  22650. for (var index = 0; index < properties.length - 1; index++) {
  22651. target = target[properties[index]];
  22652. }
  22653. return target;
  22654. };
  22655. ActionManager.prototype._getProperty = function (propertyPath) {
  22656. var properties = propertyPath.split(".");
  22657. return properties[properties.length - 1];
  22658. };
  22659. ActionManager._NothingTrigger = 0;
  22660. ActionManager._OnPickTrigger = 1;
  22661. ActionManager._OnLeftPickTrigger = 2;
  22662. ActionManager._OnRightPickTrigger = 3;
  22663. ActionManager._OnCenterPickTrigger = 4;
  22664. ActionManager._OnPointerOverTrigger = 5;
  22665. ActionManager._OnPointerOutTrigger = 6;
  22666. ActionManager._OnEveryFrameTrigger = 7;
  22667. ActionManager._OnIntersectionEnterTrigger = 8;
  22668. ActionManager._OnIntersectionExitTrigger = 9;
  22669. ActionManager._OnKeyDownTrigger = 10;
  22670. ActionManager._OnKeyUpTrigger = 11;
  22671. return ActionManager;
  22672. })();
  22673. BABYLON.ActionManager = ActionManager;
  22674. })(BABYLON || (BABYLON = {}));
  22675. //# sourceMappingURL=babylon.actionManager.js.map
  22676. var BABYLON;
  22677. (function (BABYLON) {
  22678. var InterpolateValueAction = (function (_super) {
  22679. __extends(InterpolateValueAction, _super);
  22680. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22681. if (typeof duration === "undefined") { duration = 1000; }
  22682. _super.call(this, triggerOptions, condition);
  22683. this.propertyPath = propertyPath;
  22684. this.value = value;
  22685. this.duration = duration;
  22686. this.stopOtherAnimations = stopOtherAnimations;
  22687. this._target = target;
  22688. }
  22689. InterpolateValueAction.prototype._prepare = function () {
  22690. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22691. this._property = this._getProperty(this.propertyPath);
  22692. };
  22693. InterpolateValueAction.prototype.execute = function () {
  22694. var scene = this._actionManager.getScene();
  22695. var keys = [
  22696. {
  22697. frame: 0,
  22698. value: this._target[this._property]
  22699. }, {
  22700. frame: 100,
  22701. value: this.value
  22702. }
  22703. ];
  22704. var dataType;
  22705. if (typeof this.value === "number") {
  22706. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22707. } else if (this.value instanceof BABYLON.Color3) {
  22708. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22709. } else if (this.value instanceof BABYLON.Vector3) {
  22710. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22711. } else if (this.value instanceof BABYLON.Matrix) {
  22712. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22713. } else if (this.value instanceof BABYLON.Quaternion) {
  22714. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22715. } else {
  22716. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22717. return;
  22718. }
  22719. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22720. animation.setKeys(keys);
  22721. if (this.stopOtherAnimations) {
  22722. scene.stopAnimation(this._target);
  22723. }
  22724. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22725. };
  22726. return InterpolateValueAction;
  22727. })(BABYLON.Action);
  22728. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22729. })(BABYLON || (BABYLON = {}));
  22730. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22731. var BABYLON;
  22732. (function (BABYLON) {
  22733. var SwitchBooleanAction = (function (_super) {
  22734. __extends(SwitchBooleanAction, _super);
  22735. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22736. _super.call(this, triggerOptions, condition);
  22737. this.propertyPath = propertyPath;
  22738. this._target = target;
  22739. }
  22740. SwitchBooleanAction.prototype._prepare = function () {
  22741. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22742. this._property = this._getProperty(this.propertyPath);
  22743. };
  22744. SwitchBooleanAction.prototype.execute = function () {
  22745. this._target[this._property] = !this._target[this._property];
  22746. };
  22747. return SwitchBooleanAction;
  22748. })(BABYLON.Action);
  22749. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22750. var SetStateAction = (function (_super) {
  22751. __extends(SetStateAction, _super);
  22752. function SetStateAction(triggerOptions, target, value, condition) {
  22753. _super.call(this, triggerOptions, condition);
  22754. this.value = value;
  22755. this._target = target;
  22756. }
  22757. SetStateAction.prototype.execute = function () {
  22758. this._target.state = this.value;
  22759. };
  22760. return SetStateAction;
  22761. })(BABYLON.Action);
  22762. BABYLON.SetStateAction = SetStateAction;
  22763. var SetValueAction = (function (_super) {
  22764. __extends(SetValueAction, _super);
  22765. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22766. _super.call(this, triggerOptions, condition);
  22767. this.propertyPath = propertyPath;
  22768. this.value = value;
  22769. this._target = target;
  22770. }
  22771. SetValueAction.prototype._prepare = function () {
  22772. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22773. this._property = this._getProperty(this.propertyPath);
  22774. };
  22775. SetValueAction.prototype.execute = function () {
  22776. this._target[this._property] = this.value;
  22777. };
  22778. return SetValueAction;
  22779. })(BABYLON.Action);
  22780. BABYLON.SetValueAction = SetValueAction;
  22781. var IncrementValueAction = (function (_super) {
  22782. __extends(IncrementValueAction, _super);
  22783. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22784. _super.call(this, triggerOptions, condition);
  22785. this.propertyPath = propertyPath;
  22786. this.value = value;
  22787. this._target = target;
  22788. }
  22789. IncrementValueAction.prototype._prepare = function () {
  22790. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22791. this._property = this._getProperty(this.propertyPath);
  22792. if (typeof this._target[this._property] !== "number") {
  22793. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22794. }
  22795. };
  22796. IncrementValueAction.prototype.execute = function () {
  22797. this._target[this._property] += this.value;
  22798. };
  22799. return IncrementValueAction;
  22800. })(BABYLON.Action);
  22801. BABYLON.IncrementValueAction = IncrementValueAction;
  22802. var PlayAnimationAction = (function (_super) {
  22803. __extends(PlayAnimationAction, _super);
  22804. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22805. _super.call(this, triggerOptions, condition);
  22806. this.from = from;
  22807. this.to = to;
  22808. this.loop = loop;
  22809. this._target = target;
  22810. }
  22811. PlayAnimationAction.prototype._prepare = function () {
  22812. };
  22813. PlayAnimationAction.prototype.execute = function () {
  22814. var scene = this._actionManager.getScene();
  22815. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22816. };
  22817. return PlayAnimationAction;
  22818. })(BABYLON.Action);
  22819. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22820. var StopAnimationAction = (function (_super) {
  22821. __extends(StopAnimationAction, _super);
  22822. function StopAnimationAction(triggerOptions, target, condition) {
  22823. _super.call(this, triggerOptions, condition);
  22824. this._target = target;
  22825. }
  22826. StopAnimationAction.prototype._prepare = function () {
  22827. };
  22828. StopAnimationAction.prototype.execute = function () {
  22829. var scene = this._actionManager.getScene();
  22830. scene.stopAnimation(this._target);
  22831. };
  22832. return StopAnimationAction;
  22833. })(BABYLON.Action);
  22834. BABYLON.StopAnimationAction = StopAnimationAction;
  22835. var DoNothingAction = (function (_super) {
  22836. __extends(DoNothingAction, _super);
  22837. function DoNothingAction(triggerOptions, condition) {
  22838. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22839. _super.call(this, triggerOptions, condition);
  22840. }
  22841. DoNothingAction.prototype.execute = function () {
  22842. };
  22843. return DoNothingAction;
  22844. })(BABYLON.Action);
  22845. BABYLON.DoNothingAction = DoNothingAction;
  22846. var CombineAction = (function (_super) {
  22847. __extends(CombineAction, _super);
  22848. function CombineAction(triggerOptions, children, condition) {
  22849. _super.call(this, triggerOptions, condition);
  22850. this.children = children;
  22851. }
  22852. CombineAction.prototype._prepare = function () {
  22853. for (var index = 0; index < this.children.length; index++) {
  22854. this.children[index]._actionManager = this._actionManager;
  22855. this.children[index]._prepare();
  22856. }
  22857. };
  22858. CombineAction.prototype.execute = function (evt) {
  22859. for (var index = 0; index < this.children.length; index++) {
  22860. this.children[index].execute(evt);
  22861. }
  22862. };
  22863. return CombineAction;
  22864. })(BABYLON.Action);
  22865. BABYLON.CombineAction = CombineAction;
  22866. var ExecuteCodeAction = (function (_super) {
  22867. __extends(ExecuteCodeAction, _super);
  22868. function ExecuteCodeAction(triggerOptions, func, condition) {
  22869. _super.call(this, triggerOptions, condition);
  22870. this.func = func;
  22871. }
  22872. ExecuteCodeAction.prototype.execute = function (evt) {
  22873. this.func(evt);
  22874. };
  22875. return ExecuteCodeAction;
  22876. })(BABYLON.Action);
  22877. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22878. var SetParentAction = (function (_super) {
  22879. __extends(SetParentAction, _super);
  22880. function SetParentAction(triggerOptions, target, parent, condition) {
  22881. _super.call(this, triggerOptions, condition);
  22882. this._target = target;
  22883. this._parent = parent;
  22884. }
  22885. SetParentAction.prototype._prepare = function () {
  22886. };
  22887. SetParentAction.prototype.execute = function () {
  22888. if (this._target.parent === this._parent) {
  22889. return;
  22890. }
  22891. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22892. invertParentWorldMatrix.invert();
  22893. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22894. this._target.parent = this._parent;
  22895. };
  22896. return SetParentAction;
  22897. })(BABYLON.Action);
  22898. BABYLON.SetParentAction = SetParentAction;
  22899. })(BABYLON || (BABYLON = {}));
  22900. //# sourceMappingURL=babylon.directActions.js.map
  22901. var BABYLON;
  22902. (function (BABYLON) {
  22903. var Geometry = (function () {
  22904. function Geometry(id, scene, vertexData, updatable, mesh) {
  22905. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22906. this._totalVertices = 0;
  22907. this._indices = [];
  22908. this.id = id;
  22909. this._engine = scene.getEngine();
  22910. this._meshes = [];
  22911. this._scene = scene;
  22912. // vertexData
  22913. if (vertexData) {
  22914. this.setAllVerticesData(vertexData, updatable);
  22915. } else {
  22916. this._totalVertices = 0;
  22917. this._indices = [];
  22918. }
  22919. // applyToMesh
  22920. if (mesh) {
  22921. this.applyToMesh(mesh);
  22922. }
  22923. }
  22924. Geometry.prototype.getScene = function () {
  22925. return this._scene;
  22926. };
  22927. Geometry.prototype.getEngine = function () {
  22928. return this._engine;
  22929. };
  22930. Geometry.prototype.isReady = function () {
  22931. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22932. };
  22933. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22934. vertexData.applyToGeometry(this, updatable);
  22935. };
  22936. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22937. this._vertexBuffers = this._vertexBuffers || {};
  22938. if (this._vertexBuffers[kind]) {
  22939. this._vertexBuffers[kind].dispose();
  22940. }
  22941. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22942. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22943. stride = this._vertexBuffers[kind].getStrideSize();
  22944. this._totalVertices = data.length / stride;
  22945. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22946. var meshes = this._meshes;
  22947. var numOfMeshes = meshes.length;
  22948. for (var index = 0; index < numOfMeshes; index++) {
  22949. var mesh = meshes[index];
  22950. mesh._resetPointsArrayCache();
  22951. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22952. mesh._createGlobalSubMesh();
  22953. mesh.computeWorldMatrix(true);
  22954. }
  22955. }
  22956. };
  22957. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22958. var vertexBuffer = this.getVertexBuffer(kind);
  22959. if (!vertexBuffer) {
  22960. return;
  22961. }
  22962. vertexBuffer.updateDirectly(data, offset);
  22963. };
  22964. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22965. var vertexBuffer = this.getVertexBuffer(kind);
  22966. if (!vertexBuffer) {
  22967. return;
  22968. }
  22969. vertexBuffer.update(data);
  22970. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22971. var extend;
  22972. var stride = vertexBuffer.getStrideSize();
  22973. this._totalVertices = data.length / stride;
  22974. if (updateExtends) {
  22975. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22976. }
  22977. var meshes = this._meshes;
  22978. var numOfMeshes = meshes.length;
  22979. for (var index = 0; index < numOfMeshes; index++) {
  22980. var mesh = meshes[index];
  22981. mesh._resetPointsArrayCache();
  22982. if (updateExtends) {
  22983. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22984. }
  22985. }
  22986. }
  22987. };
  22988. Geometry.prototype.getTotalVertices = function () {
  22989. if (!this.isReady()) {
  22990. return 0;
  22991. }
  22992. return this._totalVertices;
  22993. };
  22994. Geometry.prototype.getVerticesData = function (kind) {
  22995. var vertexBuffer = this.getVertexBuffer(kind);
  22996. if (!vertexBuffer) {
  22997. return null;
  22998. }
  22999. return vertexBuffer.getData();
  23000. };
  23001. Geometry.prototype.getVertexBuffer = function (kind) {
  23002. if (!this.isReady()) {
  23003. return null;
  23004. }
  23005. return this._vertexBuffers[kind];
  23006. };
  23007. Geometry.prototype.getVertexBuffers = function () {
  23008. if (!this.isReady()) {
  23009. return null;
  23010. }
  23011. return this._vertexBuffers;
  23012. };
  23013. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23014. if (!this._vertexBuffers) {
  23015. if (this._delayInfo) {
  23016. return this._delayInfo.indexOf(kind) !== -1;
  23017. }
  23018. return false;
  23019. }
  23020. return this._vertexBuffers[kind] !== undefined;
  23021. };
  23022. Geometry.prototype.getVerticesDataKinds = function () {
  23023. var result = [];
  23024. if (!this._vertexBuffers && this._delayInfo) {
  23025. for (var kind in this._delayInfo) {
  23026. result.push(kind);
  23027. }
  23028. } else {
  23029. for (kind in this._vertexBuffers) {
  23030. result.push(kind);
  23031. }
  23032. }
  23033. return result;
  23034. };
  23035. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23036. if (this._indexBuffer) {
  23037. this._engine._releaseBuffer(this._indexBuffer);
  23038. }
  23039. this._indices = indices;
  23040. if (this._meshes.length !== 0 && this._indices) {
  23041. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23042. }
  23043. if (totalVertices !== undefined) {
  23044. this._totalVertices = totalVertices;
  23045. }
  23046. var meshes = this._meshes;
  23047. var numOfMeshes = meshes.length;
  23048. for (var index = 0; index < numOfMeshes; index++) {
  23049. meshes[index]._createGlobalSubMesh();
  23050. }
  23051. };
  23052. Geometry.prototype.getTotalIndices = function () {
  23053. if (!this.isReady()) {
  23054. return 0;
  23055. }
  23056. return this._indices.length;
  23057. };
  23058. Geometry.prototype.getIndices = function () {
  23059. if (!this.isReady()) {
  23060. return null;
  23061. }
  23062. return this._indices;
  23063. };
  23064. Geometry.prototype.getIndexBuffer = function () {
  23065. if (!this.isReady()) {
  23066. return null;
  23067. }
  23068. return this._indexBuffer;
  23069. };
  23070. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23071. var meshes = this._meshes;
  23072. var index = meshes.indexOf(mesh);
  23073. if (index === -1) {
  23074. return;
  23075. }
  23076. for (var kind in this._vertexBuffers) {
  23077. this._vertexBuffers[kind].dispose();
  23078. }
  23079. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23080. this._indexBuffer = null;
  23081. }
  23082. meshes.splice(index, 1);
  23083. mesh._geometry = null;
  23084. if (meshes.length === 0 && shouldDispose) {
  23085. this.dispose();
  23086. }
  23087. };
  23088. Geometry.prototype.applyToMesh = function (mesh) {
  23089. if (mesh._geometry === this) {
  23090. return;
  23091. }
  23092. var previousGeometry = mesh._geometry;
  23093. if (previousGeometry) {
  23094. previousGeometry.releaseForMesh(mesh);
  23095. }
  23096. var meshes = this._meshes;
  23097. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23098. mesh._geometry = this;
  23099. this._scene.pushGeometry(this);
  23100. meshes.push(mesh);
  23101. if (this.isReady()) {
  23102. this._applyToMesh(mesh);
  23103. } else {
  23104. mesh._boundingInfo = this._boundingInfo;
  23105. }
  23106. };
  23107. Geometry.prototype._applyToMesh = function (mesh) {
  23108. var numOfMeshes = this._meshes.length;
  23109. for (var kind in this._vertexBuffers) {
  23110. if (numOfMeshes === 1) {
  23111. this._vertexBuffers[kind].create();
  23112. }
  23113. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23114. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23115. mesh._resetPointsArrayCache();
  23116. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23117. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23118. mesh._createGlobalSubMesh();
  23119. //bounding info was just created again, world matrix should be applied again.
  23120. mesh._updateBoundingInfo();
  23121. }
  23122. }
  23123. // indexBuffer
  23124. if (numOfMeshes === 1 && this._indices) {
  23125. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23126. }
  23127. if (this._indexBuffer) {
  23128. this._indexBuffer.references = numOfMeshes;
  23129. }
  23130. };
  23131. Geometry.prototype.load = function (scene, onLoaded) {
  23132. var _this = this;
  23133. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23134. return;
  23135. }
  23136. if (this.isReady()) {
  23137. if (onLoaded) {
  23138. onLoaded();
  23139. }
  23140. return;
  23141. }
  23142. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23143. scene._addPendingData(this);
  23144. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23145. _this._delayLoadingFunction(JSON.parse(data), _this);
  23146. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23147. _this._delayInfo = [];
  23148. scene._removePendingData(_this);
  23149. var meshes = _this._meshes;
  23150. var numOfMeshes = meshes.length;
  23151. for (var index = 0; index < numOfMeshes; index++) {
  23152. _this._applyToMesh(meshes[index]);
  23153. }
  23154. if (onLoaded) {
  23155. onLoaded();
  23156. }
  23157. }, function () {
  23158. }, scene.database);
  23159. };
  23160. Geometry.prototype.dispose = function () {
  23161. var meshes = this._meshes;
  23162. var numOfMeshes = meshes.length;
  23163. var index;
  23164. for (index = 0; index < numOfMeshes; index++) {
  23165. this.releaseForMesh(meshes[index]);
  23166. }
  23167. this._meshes = [];
  23168. for (var kind in this._vertexBuffers) {
  23169. this._vertexBuffers[kind].dispose();
  23170. }
  23171. this._vertexBuffers = [];
  23172. this._totalVertices = 0;
  23173. if (this._indexBuffer) {
  23174. this._engine._releaseBuffer(this._indexBuffer);
  23175. }
  23176. this._indexBuffer = null;
  23177. this._indices = [];
  23178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23179. this.delayLoadingFile = null;
  23180. this._delayLoadingFunction = null;
  23181. this._delayInfo = [];
  23182. this._boundingInfo = null; // todo: .dispose()
  23183. var geometries = this._scene.getGeometries();
  23184. index = geometries.indexOf(this);
  23185. if (index > -1) {
  23186. geometries.splice(index, 1);
  23187. }
  23188. };
  23189. Geometry.prototype.copy = function (id) {
  23190. var vertexData = new BABYLON.VertexData();
  23191. vertexData.indices = [];
  23192. var indices = this.getIndices();
  23193. for (var index = 0; index < indices.length; index++) {
  23194. vertexData.indices.push(indices[index]);
  23195. }
  23196. var updatable = false;
  23197. var stopChecking = false;
  23198. for (var kind in this._vertexBuffers) {
  23199. vertexData.set(this.getVerticesData(kind), kind);
  23200. if (!stopChecking) {
  23201. updatable = this.getVertexBuffer(kind).isUpdatable();
  23202. stopChecking = !updatable;
  23203. }
  23204. }
  23205. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23206. geometry.delayLoadState = this.delayLoadState;
  23207. geometry.delayLoadingFile = this.delayLoadingFile;
  23208. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23209. for (kind in this._delayInfo) {
  23210. geometry._delayInfo = geometry._delayInfo || [];
  23211. geometry._delayInfo.push(kind);
  23212. }
  23213. // Bounding info
  23214. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23215. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23216. return geometry;
  23217. };
  23218. // Statics
  23219. Geometry.ExtractFromMesh = function (mesh, id) {
  23220. var geometry = mesh._geometry;
  23221. if (!geometry) {
  23222. return null;
  23223. }
  23224. return geometry.copy(id);
  23225. };
  23226. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23227. // be aware Math.random() could cause collisions
  23228. Geometry.RandomId = function () {
  23229. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23230. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23231. return v.toString(16);
  23232. });
  23233. };
  23234. return Geometry;
  23235. })();
  23236. BABYLON.Geometry = Geometry;
  23237. (function (Geometry) {
  23238. /////// Primitives //////////////////////////////////////////////
  23239. (function (Primitives) {
  23240. /// Abstract class
  23241. var _Primitive = (function (_super) {
  23242. __extends(_Primitive, _super);
  23243. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23244. this._beingRegenerated = true;
  23245. this._canBeRegenerated = canBeRegenerated;
  23246. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23247. this._beingRegenerated = false;
  23248. }
  23249. _Primitive.prototype.canBeRegenerated = function () {
  23250. return this._canBeRegenerated;
  23251. };
  23252. _Primitive.prototype.regenerate = function () {
  23253. if (!this._canBeRegenerated) {
  23254. return;
  23255. }
  23256. this._beingRegenerated = true;
  23257. this.setAllVerticesData(this._regenerateVertexData(), false);
  23258. this._beingRegenerated = false;
  23259. };
  23260. _Primitive.prototype.asNewGeometry = function (id) {
  23261. return _super.prototype.copy.call(this, id);
  23262. };
  23263. // overrides
  23264. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23265. if (!this._beingRegenerated) {
  23266. return;
  23267. }
  23268. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23269. };
  23270. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23271. if (!this._beingRegenerated) {
  23272. return;
  23273. }
  23274. _super.prototype.setVerticesData.call(this, kind, data, false);
  23275. };
  23276. // to override
  23277. // protected
  23278. _Primitive.prototype._regenerateVertexData = function () {
  23279. throw new Error("Abstract method");
  23280. };
  23281. _Primitive.prototype.copy = function (id) {
  23282. throw new Error("Must be overriden in sub-classes.");
  23283. };
  23284. return _Primitive;
  23285. })(Geometry);
  23286. Primitives._Primitive = _Primitive;
  23287. var Box = (function (_super) {
  23288. __extends(Box, _super);
  23289. function Box(id, scene, size, canBeRegenerated, mesh) {
  23290. this.size = size;
  23291. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23292. }
  23293. Box.prototype._regenerateVertexData = function () {
  23294. return BABYLON.VertexData.CreateBox(this.size);
  23295. };
  23296. Box.prototype.copy = function (id) {
  23297. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23298. };
  23299. return Box;
  23300. })(_Primitive);
  23301. Primitives.Box = Box;
  23302. var Sphere = (function (_super) {
  23303. __extends(Sphere, _super);
  23304. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23305. this.segments = segments;
  23306. this.diameter = diameter;
  23307. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23308. }
  23309. Sphere.prototype._regenerateVertexData = function () {
  23310. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23311. };
  23312. Sphere.prototype.copy = function (id) {
  23313. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23314. };
  23315. return Sphere;
  23316. })(_Primitive);
  23317. Primitives.Sphere = Sphere;
  23318. var Cylinder = (function (_super) {
  23319. __extends(Cylinder, _super);
  23320. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23321. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  23322. this.height = height;
  23323. this.diameterTop = diameterTop;
  23324. this.diameterBottom = diameterBottom;
  23325. this.tessellation = tessellation;
  23326. this.subdivisions = subdivisions;
  23327. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23328. }
  23329. Cylinder.prototype._regenerateVertexData = function () {
  23330. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23331. };
  23332. Cylinder.prototype.copy = function (id) {
  23333. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23334. };
  23335. return Cylinder;
  23336. })(_Primitive);
  23337. Primitives.Cylinder = Cylinder;
  23338. var Torus = (function (_super) {
  23339. __extends(Torus, _super);
  23340. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23341. this.diameter = diameter;
  23342. this.thickness = thickness;
  23343. this.tessellation = tessellation;
  23344. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23345. }
  23346. Torus.prototype._regenerateVertexData = function () {
  23347. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23348. };
  23349. Torus.prototype.copy = function (id) {
  23350. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23351. };
  23352. return Torus;
  23353. })(_Primitive);
  23354. Primitives.Torus = Torus;
  23355. var Ground = (function (_super) {
  23356. __extends(Ground, _super);
  23357. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23358. this.width = width;
  23359. this.height = height;
  23360. this.subdivisions = subdivisions;
  23361. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23362. }
  23363. Ground.prototype._regenerateVertexData = function () {
  23364. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23365. };
  23366. Ground.prototype.copy = function (id) {
  23367. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23368. };
  23369. return Ground;
  23370. })(_Primitive);
  23371. Primitives.Ground = Ground;
  23372. var TiledGround = (function (_super) {
  23373. __extends(TiledGround, _super);
  23374. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23375. this.xmin = xmin;
  23376. this.zmin = zmin;
  23377. this.xmax = xmax;
  23378. this.zmax = zmax;
  23379. this.subdivisions = subdivisions;
  23380. this.precision = precision;
  23381. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23382. }
  23383. TiledGround.prototype._regenerateVertexData = function () {
  23384. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23385. };
  23386. TiledGround.prototype.copy = function (id) {
  23387. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23388. };
  23389. return TiledGround;
  23390. })(_Primitive);
  23391. Primitives.TiledGround = TiledGround;
  23392. var Plane = (function (_super) {
  23393. __extends(Plane, _super);
  23394. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23395. this.size = size;
  23396. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23397. }
  23398. Plane.prototype._regenerateVertexData = function () {
  23399. return BABYLON.VertexData.CreatePlane(this.size);
  23400. };
  23401. Plane.prototype.copy = function (id) {
  23402. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23403. };
  23404. return Plane;
  23405. })(_Primitive);
  23406. Primitives.Plane = Plane;
  23407. var TorusKnot = (function (_super) {
  23408. __extends(TorusKnot, _super);
  23409. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23410. this.radius = radius;
  23411. this.tube = tube;
  23412. this.radialSegments = radialSegments;
  23413. this.tubularSegments = tubularSegments;
  23414. this.p = p;
  23415. this.q = q;
  23416. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23417. }
  23418. TorusKnot.prototype._regenerateVertexData = function () {
  23419. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23420. };
  23421. TorusKnot.prototype.copy = function (id) {
  23422. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23423. };
  23424. return TorusKnot;
  23425. })(_Primitive);
  23426. Primitives.TorusKnot = TorusKnot;
  23427. })(Geometry.Primitives || (Geometry.Primitives = {}));
  23428. var Primitives = Geometry.Primitives;
  23429. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  23430. var Geometry = BABYLON.Geometry;
  23431. })(BABYLON || (BABYLON = {}));
  23432. //# sourceMappingURL=babylon.geometry.js.map
  23433. var BABYLON;
  23434. (function (BABYLON) {
  23435. var Gamepads = (function () {
  23436. function Gamepads(ongamedpadconnected) {
  23437. var _this = this;
  23438. this.babylonGamepads = [];
  23439. this.oneGamepadConnected = false;
  23440. this.isMonitoring = false;
  23441. this.gamepadEventSupported = 'GamepadEvent' in window;
  23442. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23443. 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=";
  23444. this._callbackGamepadConnected = ongamedpadconnected;
  23445. if (this.gamepadSupportAvailable) {
  23446. // Checking if the gamepad connected event is supported (like in Firefox)
  23447. if (this.gamepadEventSupported) {
  23448. window.addEventListener('gamepadconnected', function (evt) {
  23449. _this._onGamepadConnected(evt);
  23450. }, false);
  23451. window.addEventListener('gamepaddisconnected', function (evt) {
  23452. _this._onGamepadDisconnected(evt);
  23453. }, false);
  23454. } else {
  23455. this._startMonitoringGamepads();
  23456. }
  23457. if (!this.oneGamepadConnected) {
  23458. this._insertGamepadDOMInstructions();
  23459. }
  23460. } else {
  23461. this._insertGamepadDOMNotSupported();
  23462. }
  23463. }
  23464. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23465. Gamepads.gamepadDOMInfo = document.createElement("div");
  23466. var buttonAImage = document.createElement("img");
  23467. buttonAImage.src = this.buttonADataURL;
  23468. var spanMessage = document.createElement("span");
  23469. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23470. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23471. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23472. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23473. Gamepads.gamepadDOMInfo.style.width = "100%";
  23474. Gamepads.gamepadDOMInfo.style.height = "48px";
  23475. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23476. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23477. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23478. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23479. buttonAImage.style.position = "relative";
  23480. buttonAImage.style.bottom = "8px";
  23481. spanMessage.style.position = "relative";
  23482. spanMessage.style.fontSize = "32px";
  23483. spanMessage.style.bottom = "32px";
  23484. spanMessage.style.color = "green";
  23485. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23486. };
  23487. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  23488. Gamepads.gamepadDOMInfo = document.createElement("div");
  23489. var spanMessage = document.createElement("span");
  23490. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  23491. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23492. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23493. Gamepads.gamepadDOMInfo.style.width = "100%";
  23494. Gamepads.gamepadDOMInfo.style.height = "40px";
  23495. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23496. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23497. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23498. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23499. spanMessage.style.position = "relative";
  23500. spanMessage.style.fontSize = "32px";
  23501. spanMessage.style.color = "red";
  23502. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23503. };
  23504. Gamepads.prototype.dispose = function () {
  23505. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23506. };
  23507. Gamepads.prototype._onGamepadConnected = function (evt) {
  23508. var newGamepad = this._addNewGamepad(evt.gamepad);
  23509. if (this._callbackGamepadConnected)
  23510. this._callbackGamepadConnected(newGamepad);
  23511. this._startMonitoringGamepads();
  23512. };
  23513. Gamepads.prototype._addNewGamepad = function (gamepad) {
  23514. if (!this.oneGamepadConnected) {
  23515. this.oneGamepadConnected = true;
  23516. if (Gamepads.gamepadDOMInfo) {
  23517. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23518. Gamepads.gamepadDOMInfo = null;
  23519. }
  23520. }
  23521. var newGamepad;
  23522. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  23523. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  23524. } else {
  23525. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  23526. }
  23527. this.babylonGamepads.push(newGamepad);
  23528. return newGamepad;
  23529. };
  23530. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  23531. for (var i in this.babylonGamepads) {
  23532. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  23533. this.babylonGamepads.splice(i, 1);
  23534. break;
  23535. }
  23536. }
  23537. // If no gamepads are left, stop the polling loop.
  23538. if (this.babylonGamepads.length == 0) {
  23539. this._stopMonitoringGamepads();
  23540. }
  23541. };
  23542. Gamepads.prototype._startMonitoringGamepads = function () {
  23543. if (!this.isMonitoring) {
  23544. this.isMonitoring = true;
  23545. this._checkGamepadsStatus();
  23546. }
  23547. };
  23548. Gamepads.prototype._stopMonitoringGamepads = function () {
  23549. this.isMonitoring = false;
  23550. };
  23551. Gamepads.prototype._checkGamepadsStatus = function () {
  23552. var _this = this;
  23553. // updating gamepad objects
  23554. this._updateGamepadObjects();
  23555. for (var i in this.babylonGamepads) {
  23556. this.babylonGamepads[i].update();
  23557. }
  23558. if (this.isMonitoring) {
  23559. if (window.requestAnimationFrame) {
  23560. window.requestAnimationFrame(function () {
  23561. _this._checkGamepadsStatus();
  23562. });
  23563. } else if (window.mozRequestAnimationFrame) {
  23564. window.mozRequestAnimationFrame(function () {
  23565. _this._checkGamepadsStatus();
  23566. });
  23567. } else if (window.webkitRequestAnimationFrame) {
  23568. window.webkitRequestAnimationFrame(function () {
  23569. _this._checkGamepadsStatus();
  23570. });
  23571. }
  23572. }
  23573. };
  23574. // This function is called only on Chrome, which does not yet support
  23575. // connection/disconnection events, but requires you to monitor
  23576. // an array for changes.
  23577. Gamepads.prototype._updateGamepadObjects = function () {
  23578. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  23579. for (var i = 0; i < gamepads.length; i++) {
  23580. if (gamepads[i]) {
  23581. if (!(gamepads[i].index in this.babylonGamepads)) {
  23582. var newGamepad = this._addNewGamepad(gamepads[i]);
  23583. if (this._callbackGamepadConnected) {
  23584. this._callbackGamepadConnected(newGamepad);
  23585. }
  23586. } else {
  23587. this.babylonGamepads[i].browserGamepad = gamepads[i];
  23588. }
  23589. }
  23590. }
  23591. };
  23592. return Gamepads;
  23593. })();
  23594. BABYLON.Gamepads = Gamepads;
  23595. var StickValues = (function () {
  23596. function StickValues(x, y) {
  23597. this.x = x;
  23598. this.y = y;
  23599. }
  23600. return StickValues;
  23601. })();
  23602. BABYLON.StickValues = StickValues;
  23603. var Gamepad = (function () {
  23604. function Gamepad(id, index, browserGamepad) {
  23605. this.id = id;
  23606. this.index = index;
  23607. this.browserGamepad = browserGamepad;
  23608. if (this.browserGamepad.axes.length >= 2) {
  23609. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23610. }
  23611. if (this.browserGamepad.axes.length >= 4) {
  23612. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23613. }
  23614. }
  23615. Gamepad.prototype.onleftstickchanged = function (callback) {
  23616. this._onleftstickchanged = callback;
  23617. };
  23618. Gamepad.prototype.onrightstickchanged = function (callback) {
  23619. this._onrightstickchanged = callback;
  23620. };
  23621. Object.defineProperty(Gamepad.prototype, "leftStick", {
  23622. get: function () {
  23623. return this._leftStick;
  23624. },
  23625. set: function (newValues) {
  23626. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  23627. this._onleftstickchanged(newValues);
  23628. }
  23629. this._leftStick = newValues;
  23630. },
  23631. enumerable: true,
  23632. configurable: true
  23633. });
  23634. Object.defineProperty(Gamepad.prototype, "rightStick", {
  23635. get: function () {
  23636. return this._rightStick;
  23637. },
  23638. set: function (newValues) {
  23639. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  23640. this._onrightstickchanged(newValues);
  23641. }
  23642. this._rightStick = newValues;
  23643. },
  23644. enumerable: true,
  23645. configurable: true
  23646. });
  23647. Gamepad.prototype.update = function () {
  23648. if (this._leftStick) {
  23649. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23650. }
  23651. if (this._rightStick) {
  23652. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23653. }
  23654. };
  23655. return Gamepad;
  23656. })();
  23657. BABYLON.Gamepad = Gamepad;
  23658. var GenericPad = (function (_super) {
  23659. __extends(GenericPad, _super);
  23660. function GenericPad(id, index, gamepad) {
  23661. _super.call(this, id, index, gamepad);
  23662. this.id = id;
  23663. this.index = index;
  23664. this.gamepad = gamepad;
  23665. this._buttons = new Array(gamepad.buttons.length);
  23666. }
  23667. GenericPad.prototype.onbuttondown = function (callback) {
  23668. this._onbuttondown = callback;
  23669. };
  23670. GenericPad.prototype.onbuttonup = function (callback) {
  23671. this._onbuttonup = callback;
  23672. };
  23673. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  23674. if (newValue !== currentValue) {
  23675. if (this._onbuttondown && newValue === 1) {
  23676. this._onbuttondown(buttonIndex);
  23677. }
  23678. if (this._onbuttonup && newValue === 0) {
  23679. this._onbuttonup(buttonIndex);
  23680. }
  23681. }
  23682. return newValue;
  23683. };
  23684. GenericPad.prototype.update = function () {
  23685. _super.prototype.update.call(this);
  23686. for (var index = 0; index < this._buttons.length; index++) {
  23687. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23688. }
  23689. };
  23690. return GenericPad;
  23691. })(Gamepad);
  23692. BABYLON.GenericPad = GenericPad;
  23693. (function (Xbox360Button) {
  23694. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23695. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23696. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23697. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23698. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23699. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23700. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23701. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23702. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23703. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23704. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23705. var Xbox360Button = BABYLON.Xbox360Button;
  23706. (function (Xbox360Dpad) {
  23707. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23708. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23709. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23710. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23711. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23712. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23713. var Xbox360Pad = (function (_super) {
  23714. __extends(Xbox360Pad, _super);
  23715. function Xbox360Pad() {
  23716. _super.apply(this, arguments);
  23717. this._leftTrigger = 0;
  23718. this._rightTrigger = 0;
  23719. this._buttonA = 0;
  23720. this._buttonB = 0;
  23721. this._buttonX = 0;
  23722. this._buttonY = 0;
  23723. this._buttonBack = 0;
  23724. this._buttonStart = 0;
  23725. this._buttonLB = 0;
  23726. this._buttonRB = 0;
  23727. this._buttonLeftStick = 0;
  23728. this._buttonRightStick = 0;
  23729. this._dPadUp = 0;
  23730. this._dPadDown = 0;
  23731. this._dPadLeft = 0;
  23732. this._dPadRight = 0;
  23733. }
  23734. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23735. this._onlefttriggerchanged = callback;
  23736. };
  23737. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23738. this._onrighttriggerchanged = callback;
  23739. };
  23740. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23741. get: function () {
  23742. return this._leftTrigger;
  23743. },
  23744. set: function (newValue) {
  23745. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23746. this._onlefttriggerchanged(newValue);
  23747. }
  23748. this._leftTrigger = newValue;
  23749. },
  23750. enumerable: true,
  23751. configurable: true
  23752. });
  23753. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23754. get: function () {
  23755. return this._rightTrigger;
  23756. },
  23757. set: function (newValue) {
  23758. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23759. this._onrighttriggerchanged(newValue);
  23760. }
  23761. this._rightTrigger = newValue;
  23762. },
  23763. enumerable: true,
  23764. configurable: true
  23765. });
  23766. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23767. this._onbuttondown = callback;
  23768. };
  23769. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23770. this._onbuttonup = callback;
  23771. };
  23772. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23773. this._ondpaddown = callback;
  23774. };
  23775. Xbox360Pad.prototype.ondpadup = function (callback) {
  23776. this._ondpadup = callback;
  23777. };
  23778. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23779. if (newValue !== currentValue) {
  23780. if (this._onbuttondown && newValue === 1) {
  23781. this._onbuttondown(buttonType);
  23782. }
  23783. if (this._onbuttonup && newValue === 0) {
  23784. this._onbuttonup(buttonType);
  23785. }
  23786. }
  23787. return newValue;
  23788. };
  23789. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23790. if (newValue !== currentValue) {
  23791. if (this._ondpaddown && newValue === 1) {
  23792. this._ondpaddown(buttonType);
  23793. }
  23794. if (this._ondpadup && newValue === 0) {
  23795. this._ondpadup(buttonType);
  23796. }
  23797. }
  23798. return newValue;
  23799. };
  23800. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23801. get: function () {
  23802. return this._buttonA;
  23803. },
  23804. set: function (value) {
  23805. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23806. },
  23807. enumerable: true,
  23808. configurable: true
  23809. });
  23810. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23811. get: function () {
  23812. return this._buttonB;
  23813. },
  23814. set: function (value) {
  23815. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23816. },
  23817. enumerable: true,
  23818. configurable: true
  23819. });
  23820. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23821. get: function () {
  23822. return this._buttonX;
  23823. },
  23824. set: function (value) {
  23825. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23826. },
  23827. enumerable: true,
  23828. configurable: true
  23829. });
  23830. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23831. get: function () {
  23832. return this._buttonY;
  23833. },
  23834. set: function (value) {
  23835. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23836. },
  23837. enumerable: true,
  23838. configurable: true
  23839. });
  23840. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23841. get: function () {
  23842. return this._buttonStart;
  23843. },
  23844. set: function (value) {
  23845. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23846. },
  23847. enumerable: true,
  23848. configurable: true
  23849. });
  23850. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23851. get: function () {
  23852. return this._buttonBack;
  23853. },
  23854. set: function (value) {
  23855. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23856. },
  23857. enumerable: true,
  23858. configurable: true
  23859. });
  23860. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23861. get: function () {
  23862. return this._buttonLB;
  23863. },
  23864. set: function (value) {
  23865. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23871. get: function () {
  23872. return this._buttonRB;
  23873. },
  23874. set: function (value) {
  23875. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23881. get: function () {
  23882. return this._buttonLeftStick;
  23883. },
  23884. set: function (value) {
  23885. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23886. },
  23887. enumerable: true,
  23888. configurable: true
  23889. });
  23890. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23891. get: function () {
  23892. return this._buttonRightStick;
  23893. },
  23894. set: function (value) {
  23895. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23896. },
  23897. enumerable: true,
  23898. configurable: true
  23899. });
  23900. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23901. get: function () {
  23902. return this._dPadUp;
  23903. },
  23904. set: function (value) {
  23905. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23906. },
  23907. enumerable: true,
  23908. configurable: true
  23909. });
  23910. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23911. get: function () {
  23912. return this._dPadDown;
  23913. },
  23914. set: function (value) {
  23915. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23916. },
  23917. enumerable: true,
  23918. configurable: true
  23919. });
  23920. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23921. get: function () {
  23922. return this._dPadLeft;
  23923. },
  23924. set: function (value) {
  23925. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23926. },
  23927. enumerable: true,
  23928. configurable: true
  23929. });
  23930. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23931. get: function () {
  23932. return this._dPadRight;
  23933. },
  23934. set: function (value) {
  23935. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23936. },
  23937. enumerable: true,
  23938. configurable: true
  23939. });
  23940. Xbox360Pad.prototype.update = function () {
  23941. _super.prototype.update.call(this);
  23942. this.buttonA = this.browserGamepad.buttons[0].value;
  23943. this.buttonB = this.browserGamepad.buttons[1].value;
  23944. this.buttonX = this.browserGamepad.buttons[2].value;
  23945. this.buttonY = this.browserGamepad.buttons[3].value;
  23946. this.buttonLB = this.browserGamepad.buttons[4].value;
  23947. this.buttonRB = this.browserGamepad.buttons[5].value;
  23948. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23949. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23950. this.buttonBack = this.browserGamepad.buttons[8].value;
  23951. this.buttonStart = this.browserGamepad.buttons[9].value;
  23952. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23953. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23954. this.dPadUp = this.browserGamepad.buttons[12].value;
  23955. this.dPadDown = this.browserGamepad.buttons[13].value;
  23956. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23957. this.dPadRight = this.browserGamepad.buttons[15].value;
  23958. };
  23959. return Xbox360Pad;
  23960. })(Gamepad);
  23961. BABYLON.Xbox360Pad = Xbox360Pad;
  23962. })(BABYLON || (BABYLON = {}));
  23963. //# sourceMappingURL=babylon.gamepads.js.map
  23964. var BABYLON;
  23965. (function (BABYLON) {
  23966. // We're mainly based on the logic defined into the FreeCamera code
  23967. var GamepadCamera = (function (_super) {
  23968. __extends(GamepadCamera, _super);
  23969. function GamepadCamera(name, position, scene) {
  23970. var _this = this;
  23971. _super.call(this, name, position, scene);
  23972. this.angularSensibility = 200;
  23973. this.moveSensibility = 75;
  23974. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23975. _this._onNewGameConnected(gamepad);
  23976. });
  23977. }
  23978. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23979. // Only the first gamepad can control the camera
  23980. if (gamepad.index === 0) {
  23981. this._gamepad = gamepad;
  23982. }
  23983. };
  23984. GamepadCamera.prototype._checkInputs = function () {
  23985. if (!this._gamepad) {
  23986. return;
  23987. }
  23988. var LSValues = this._gamepad.leftStick;
  23989. var normalizedLX = LSValues.x / this.moveSensibility;
  23990. var normalizedLY = LSValues.y / this.moveSensibility;
  23991. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23992. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23993. var RSValues = this._gamepad.rightStick;
  23994. var normalizedRX = RSValues.x / this.angularSensibility;
  23995. var normalizedRY = RSValues.y / this.angularSensibility;
  23996. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23997. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23998. ;
  23999. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24000. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  24001. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24002. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24003. };
  24004. GamepadCamera.prototype.dispose = function () {
  24005. this._gamepads.dispose();
  24006. _super.prototype.dispose.call(this);
  24007. };
  24008. return GamepadCamera;
  24009. })(BABYLON.FreeCamera);
  24010. BABYLON.GamepadCamera = GamepadCamera;
  24011. })(BABYLON || (BABYLON = {}));
  24012. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24013. var BABYLON;
  24014. (function (BABYLON) {
  24015. var LinesMesh = (function (_super) {
  24016. __extends(LinesMesh, _super);
  24017. function LinesMesh(name, scene, updatable) {
  24018. if (typeof updatable === "undefined") { updatable = false; }
  24019. _super.call(this, name, scene);
  24020. this.color = new BABYLON.Color3(1, 1, 1);
  24021. this.alpha = 1;
  24022. this._indices = new Array();
  24023. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24024. attributes: ["position"],
  24025. uniforms: ["worldViewProjection", "color"],
  24026. needAlphaBlending: true
  24027. });
  24028. }
  24029. Object.defineProperty(LinesMesh.prototype, "material", {
  24030. get: function () {
  24031. return this._colorShader;
  24032. },
  24033. enumerable: true,
  24034. configurable: true
  24035. });
  24036. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24037. get: function () {
  24038. return false;
  24039. },
  24040. enumerable: true,
  24041. configurable: true
  24042. });
  24043. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24044. get: function () {
  24045. return false;
  24046. },
  24047. enumerable: true,
  24048. configurable: true
  24049. });
  24050. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24051. var engine = this.getScene().getEngine();
  24052. var indexToBind = this._geometry.getIndexBuffer();
  24053. // VBOs
  24054. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24055. // Color
  24056. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24057. };
  24058. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24059. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24060. return;
  24061. }
  24062. var engine = this.getScene().getEngine();
  24063. // Draw order
  24064. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24065. };
  24066. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24067. return null;
  24068. };
  24069. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24070. this._colorShader.dispose();
  24071. _super.prototype.dispose.call(this, doNotRecurse);
  24072. };
  24073. return LinesMesh;
  24074. })(BABYLON.Mesh);
  24075. BABYLON.LinesMesh = LinesMesh;
  24076. })(BABYLON || (BABYLON = {}));
  24077. //# sourceMappingURL=babylon.linesMesh.js.map
  24078. var BABYLON;
  24079. (function (BABYLON) {
  24080. var OutlineRenderer = (function () {
  24081. function OutlineRenderer(scene) {
  24082. this._scene = scene;
  24083. }
  24084. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24085. if (typeof useOverlay === "undefined") { useOverlay = false; }
  24086. var scene = this._scene;
  24087. var engine = this._scene.getEngine();
  24088. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24089. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24090. return;
  24091. }
  24092. var mesh = subMesh.getRenderingMesh();
  24093. var material = subMesh.getMaterial();
  24094. engine.enableEffect(this._effect);
  24095. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24096. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24097. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24098. // Bones
  24099. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  24100. if (useBones) {
  24101. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24102. }
  24103. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24104. // Alpha test
  24105. if (material && material.needAlphaTesting()) {
  24106. var alphaTexture = material.getAlphaTestTexture();
  24107. this._effect.setTexture("diffuseSampler", alphaTexture);
  24108. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24109. }
  24110. if (hardwareInstancedRendering) {
  24111. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  24112. } else {
  24113. if (batch.renderSelf[subMesh._id]) {
  24114. this._effect.setMatrix("world", mesh.getWorldMatrix());
  24115. // Draw
  24116. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24117. }
  24118. if (batch.visibleInstances[subMesh._id]) {
  24119. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24120. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24121. this._effect.setMatrix("world", instance.getWorldMatrix());
  24122. // Draw
  24123. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24124. }
  24125. }
  24126. }
  24127. };
  24128. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24129. var defines = [];
  24130. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24131. var mesh = subMesh.getMesh();
  24132. var material = subMesh.getMaterial();
  24133. // Alpha test
  24134. if (material && material.needAlphaTesting()) {
  24135. defines.push("#define ALPHATEST");
  24136. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24137. attribs.push(BABYLON.VertexBuffer.UVKind);
  24138. defines.push("#define UV1");
  24139. }
  24140. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24141. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24142. defines.push("#define UV2");
  24143. }
  24144. }
  24145. // Bones
  24146. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24149. defines.push("#define BONES");
  24150. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24151. }
  24152. // Instances
  24153. if (useInstances) {
  24154. defines.push("#define INSTANCES");
  24155. attribs.push("world0");
  24156. attribs.push("world1");
  24157. attribs.push("world2");
  24158. attribs.push("world3");
  24159. }
  24160. // Get correct effect
  24161. var join = defines.join("\n");
  24162. if (this._cachedDefines != join) {
  24163. this._cachedDefines = join;
  24164. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24165. }
  24166. return this._effect.isReady();
  24167. };
  24168. return OutlineRenderer;
  24169. })();
  24170. BABYLON.OutlineRenderer = OutlineRenderer;
  24171. })(BABYLON || (BABYLON = {}));
  24172. //# sourceMappingURL=babylon.outlineRenderer.js.map
  24173. var BABYLON;
  24174. (function (BABYLON) {
  24175. var MeshAssetTask = (function () {
  24176. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24177. this.name = name;
  24178. this.meshesNames = meshesNames;
  24179. this.rootUrl = rootUrl;
  24180. this.sceneFilename = sceneFilename;
  24181. this.isCompleted = false;
  24182. }
  24183. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24184. var _this = this;
  24185. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24186. _this.loadedMeshes = meshes;
  24187. _this.loadedParticleSystems = particleSystems;
  24188. _this.loadedSkeletons = skeletons;
  24189. _this.isCompleted = true;
  24190. if (_this.onSuccess) {
  24191. _this.onSuccess(_this);
  24192. }
  24193. onSuccess();
  24194. }, null, function () {
  24195. if (_this.onError) {
  24196. _this.onError(_this);
  24197. }
  24198. onError();
  24199. });
  24200. };
  24201. return MeshAssetTask;
  24202. })();
  24203. BABYLON.MeshAssetTask = MeshAssetTask;
  24204. var TextFileAssetTask = (function () {
  24205. function TextFileAssetTask(name, url) {
  24206. this.name = name;
  24207. this.url = url;
  24208. this.isCompleted = false;
  24209. }
  24210. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24211. var _this = this;
  24212. BABYLON.Tools.LoadFile(this.url, function (data) {
  24213. _this.text = data;
  24214. _this.isCompleted = true;
  24215. if (_this.onSuccess) {
  24216. _this.onSuccess(_this);
  24217. }
  24218. onSuccess();
  24219. }, null, scene.database, false, function () {
  24220. if (_this.onError) {
  24221. _this.onError(_this);
  24222. }
  24223. onError();
  24224. });
  24225. };
  24226. return TextFileAssetTask;
  24227. })();
  24228. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24229. var BinaryFileAssetTask = (function () {
  24230. function BinaryFileAssetTask(name, url) {
  24231. this.name = name;
  24232. this.url = url;
  24233. this.isCompleted = false;
  24234. }
  24235. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24236. var _this = this;
  24237. BABYLON.Tools.LoadFile(this.url, function (data) {
  24238. _this.data = data;
  24239. _this.isCompleted = true;
  24240. if (_this.onSuccess) {
  24241. _this.onSuccess(_this);
  24242. }
  24243. onSuccess();
  24244. }, null, scene.database, true, function () {
  24245. if (_this.onError) {
  24246. _this.onError(_this);
  24247. }
  24248. onError();
  24249. });
  24250. };
  24251. return BinaryFileAssetTask;
  24252. })();
  24253. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24254. var ImageAssetTask = (function () {
  24255. function ImageAssetTask(name, url) {
  24256. this.name = name;
  24257. this.url = url;
  24258. this.isCompleted = false;
  24259. }
  24260. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24261. var _this = this;
  24262. var img = new Image();
  24263. img.onload = function () {
  24264. _this.image = img;
  24265. _this.isCompleted = true;
  24266. if (_this.onSuccess) {
  24267. _this.onSuccess(_this);
  24268. }
  24269. onSuccess();
  24270. };
  24271. img.onerror = function () {
  24272. if (_this.onError) {
  24273. _this.onError(_this);
  24274. }
  24275. onError();
  24276. };
  24277. img.src = this.url;
  24278. };
  24279. return ImageAssetTask;
  24280. })();
  24281. BABYLON.ImageAssetTask = ImageAssetTask;
  24282. var TextureAssetTask = (function () {
  24283. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24284. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24285. this.name = name;
  24286. this.url = url;
  24287. this.noMipmap = noMipmap;
  24288. this.invertY = invertY;
  24289. this.samplingMode = samplingMode;
  24290. this.isCompleted = false;
  24291. }
  24292. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24293. var _this = this;
  24294. var onload = function () {
  24295. _this.isCompleted = true;
  24296. if (_this.onSuccess) {
  24297. _this.onSuccess(_this);
  24298. }
  24299. onSuccess();
  24300. };
  24301. var onerror = function () {
  24302. if (_this.onError) {
  24303. _this.onError(_this);
  24304. }
  24305. onError();
  24306. };
  24307. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24308. };
  24309. return TextureAssetTask;
  24310. })();
  24311. BABYLON.TextureAssetTask = TextureAssetTask;
  24312. var AssetsManager = (function () {
  24313. function AssetsManager(scene) {
  24314. this._tasks = new Array();
  24315. this._waitingTasksCount = 0;
  24316. this.useDefaultLoadingScreen = true;
  24317. this._scene = scene;
  24318. }
  24319. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24320. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24321. this._tasks.push(task);
  24322. return task;
  24323. };
  24324. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24325. var task = new TextFileAssetTask(taskName, url);
  24326. this._tasks.push(task);
  24327. return task;
  24328. };
  24329. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24330. var task = new BinaryFileAssetTask(taskName, url);
  24331. this._tasks.push(task);
  24332. return task;
  24333. };
  24334. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24335. var task = new ImageAssetTask(taskName, url);
  24336. this._tasks.push(task);
  24337. return task;
  24338. };
  24339. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24340. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24341. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24342. this._tasks.push(task);
  24343. return task;
  24344. };
  24345. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24346. this._waitingTasksCount--;
  24347. if (this._waitingTasksCount === 0) {
  24348. if (this.onFinish) {
  24349. this.onFinish(this._tasks);
  24350. }
  24351. this._scene.getEngine().hideLoadingUI();
  24352. }
  24353. };
  24354. AssetsManager.prototype._runTask = function (task) {
  24355. var _this = this;
  24356. task.run(this._scene, function () {
  24357. if (_this.onTaskSuccess) {
  24358. _this.onTaskSuccess(task);
  24359. }
  24360. _this._decreaseWaitingTasksCount();
  24361. }, function () {
  24362. if (_this.onTaskError) {
  24363. _this.onTaskError(task);
  24364. }
  24365. _this._decreaseWaitingTasksCount();
  24366. });
  24367. };
  24368. AssetsManager.prototype.reset = function () {
  24369. this._tasks = new Array();
  24370. return this;
  24371. };
  24372. AssetsManager.prototype.load = function () {
  24373. this._waitingTasksCount = this._tasks.length;
  24374. if (this._waitingTasksCount === 0) {
  24375. if (this.onFinish) {
  24376. this.onFinish(this._tasks);
  24377. }
  24378. return this;
  24379. }
  24380. if (this.useDefaultLoadingScreen) {
  24381. this._scene.getEngine().displayLoadingUI();
  24382. }
  24383. for (var index = 0; index < this._tasks.length; index++) {
  24384. var task = this._tasks[index];
  24385. this._runTask(task);
  24386. }
  24387. return this;
  24388. };
  24389. return AssetsManager;
  24390. })();
  24391. BABYLON.AssetsManager = AssetsManager;
  24392. })(BABYLON || (BABYLON = {}));
  24393. //# sourceMappingURL=babylon.assetsManager.js.map
  24394. var BABYLON;
  24395. (function (BABYLON) {
  24396. var VRDeviceOrientationCamera = (function (_super) {
  24397. __extends(VRDeviceOrientationCamera, _super);
  24398. function VRDeviceOrientationCamera(name, position, scene) {
  24399. _super.call(this, name, position, scene);
  24400. this._alpha = 0;
  24401. this._beta = 0;
  24402. this._gamma = 0;
  24403. }
  24404. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24405. this._alpha = +evt.alpha | 0;
  24406. this._beta = +evt.beta | 0;
  24407. this._gamma = +evt.gamma | 0;
  24408. if (this._gamma < 0) {
  24409. this._gamma = 90 + this._gamma;
  24410. } else {
  24411. // Incline it in the correct angle.
  24412. this._gamma = 270 - this._gamma;
  24413. }
  24414. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24415. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24416. this.rotation.z = this._beta / 180.0 * Math.PI;
  24417. };
  24418. return VRDeviceOrientationCamera;
  24419. })(BABYLON.OculusCamera);
  24420. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24421. })(BABYLON || (BABYLON = {}));
  24422. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24423. var BABYLON;
  24424. (function (BABYLON) {
  24425. var WebVRCamera = (function (_super) {
  24426. __extends(WebVRCamera, _super);
  24427. function WebVRCamera(name, position, scene) {
  24428. _super.call(this, name, position, scene);
  24429. this._hmdDevice = null;
  24430. this._sensorDevice = null;
  24431. this._cacheState = null;
  24432. this._cacheQuaternion = new BABYLON.Quaternion();
  24433. this._cacheRotation = BABYLON.Vector3.Zero();
  24434. this._vrEnabled = false;
  24435. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24436. }
  24437. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24438. var size = devices.length;
  24439. var i = 0;
  24440. // Reset devices.
  24441. this._sensorDevice = null;
  24442. this._hmdDevice = null;
  24443. while (i < size && this._hmdDevice === null) {
  24444. if (devices[i] instanceof HMDVRDevice) {
  24445. this._hmdDevice = devices[i];
  24446. }
  24447. i++;
  24448. }
  24449. i = 0;
  24450. while (i < size && this._sensorDevice === null) {
  24451. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24452. this._sensorDevice = devices[i];
  24453. }
  24454. i++;
  24455. }
  24456. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24457. };
  24458. WebVRCamera.prototype._update = function () {
  24459. if (this._vrEnabled) {
  24460. this._cacheState = this._sensorDevice.getState();
  24461. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24462. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24463. this.rotation.x = -this._cacheRotation.z;
  24464. this.rotation.y = -this._cacheRotation.y;
  24465. this.rotation.z = this._cacheRotation.x;
  24466. }
  24467. _super.prototype._update.call(this);
  24468. };
  24469. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24470. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24471. if (navigator.getVRDevices) {
  24472. navigator.getVRDevices().then(this._getWebVRDevices);
  24473. } else if (navigator.mozGetVRDevices) {
  24474. navigator.mozGetVRDevices(this._getWebVRDevices);
  24475. }
  24476. };
  24477. WebVRCamera.prototype.detachControl = function (element) {
  24478. _super.prototype.detachControl.call(this, element);
  24479. this._vrEnabled = false;
  24480. };
  24481. return WebVRCamera;
  24482. })(BABYLON.OculusCamera);
  24483. BABYLON.WebVRCamera = WebVRCamera;
  24484. })(BABYLON || (BABYLON = {}));
  24485. //# sourceMappingURL=babylon.webVRCamera.js.map
  24486. var BABYLON;
  24487. (function (BABYLON) {
  24488. // Standard optimizations
  24489. var SceneOptimization = (function () {
  24490. function SceneOptimization(priority) {
  24491. if (typeof priority === "undefined") { priority = 0; }
  24492. this.priority = priority;
  24493. this.apply = function (scene) {
  24494. return true;
  24495. };
  24496. }
  24497. return SceneOptimization;
  24498. })();
  24499. BABYLON.SceneOptimization = SceneOptimization;
  24500. var TextureOptimization = (function (_super) {
  24501. __extends(TextureOptimization, _super);
  24502. function TextureOptimization(priority, maximumSize) {
  24503. if (typeof priority === "undefined") { priority = 0; }
  24504. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  24505. var _this = this;
  24506. _super.call(this, priority);
  24507. this.priority = priority;
  24508. this.maximumSize = maximumSize;
  24509. this.apply = function (scene) {
  24510. var allDone = true;
  24511. for (var index = 0; index < scene.textures.length; index++) {
  24512. var texture = scene.textures[index];
  24513. if (!texture.canRescale) {
  24514. continue;
  24515. }
  24516. var currentSize = texture.getSize();
  24517. var maxDimension = Math.max(currentSize.width, currentSize.height);
  24518. if (maxDimension > _this.maximumSize) {
  24519. texture.scale(0.5);
  24520. allDone = false;
  24521. }
  24522. }
  24523. return allDone;
  24524. };
  24525. }
  24526. return TextureOptimization;
  24527. })(SceneOptimization);
  24528. BABYLON.TextureOptimization = TextureOptimization;
  24529. var HardwareScalingOptimization = (function (_super) {
  24530. __extends(HardwareScalingOptimization, _super);
  24531. function HardwareScalingOptimization(priority, maximumScale) {
  24532. if (typeof priority === "undefined") { priority = 0; }
  24533. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  24534. var _this = this;
  24535. _super.call(this, priority);
  24536. this.priority = priority;
  24537. this.maximumScale = maximumScale;
  24538. this._currentScale = 1;
  24539. this.apply = function (scene) {
  24540. _this._currentScale++;
  24541. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  24542. return _this._currentScale >= _this.maximumScale;
  24543. };
  24544. }
  24545. return HardwareScalingOptimization;
  24546. })(SceneOptimization);
  24547. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  24548. var ShadowsOptimization = (function (_super) {
  24549. __extends(ShadowsOptimization, _super);
  24550. function ShadowsOptimization() {
  24551. _super.apply(this, arguments);
  24552. this.apply = function (scene) {
  24553. scene.shadowsEnabled = false;
  24554. return true;
  24555. };
  24556. }
  24557. return ShadowsOptimization;
  24558. })(SceneOptimization);
  24559. BABYLON.ShadowsOptimization = ShadowsOptimization;
  24560. var PostProcessesOptimization = (function (_super) {
  24561. __extends(PostProcessesOptimization, _super);
  24562. function PostProcessesOptimization() {
  24563. _super.apply(this, arguments);
  24564. this.apply = function (scene) {
  24565. scene.postProcessesEnabled = false;
  24566. return true;
  24567. };
  24568. }
  24569. return PostProcessesOptimization;
  24570. })(SceneOptimization);
  24571. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  24572. var LensFlaresOptimization = (function (_super) {
  24573. __extends(LensFlaresOptimization, _super);
  24574. function LensFlaresOptimization() {
  24575. _super.apply(this, arguments);
  24576. this.apply = function (scene) {
  24577. scene.lensFlaresEnabled = false;
  24578. return true;
  24579. };
  24580. }
  24581. return LensFlaresOptimization;
  24582. })(SceneOptimization);
  24583. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  24584. var ParticlesOptimization = (function (_super) {
  24585. __extends(ParticlesOptimization, _super);
  24586. function ParticlesOptimization() {
  24587. _super.apply(this, arguments);
  24588. this.apply = function (scene) {
  24589. scene.particlesEnabled = false;
  24590. return true;
  24591. };
  24592. }
  24593. return ParticlesOptimization;
  24594. })(SceneOptimization);
  24595. BABYLON.ParticlesOptimization = ParticlesOptimization;
  24596. var RenderTargetsOptimization = (function (_super) {
  24597. __extends(RenderTargetsOptimization, _super);
  24598. function RenderTargetsOptimization() {
  24599. _super.apply(this, arguments);
  24600. this.apply = function (scene) {
  24601. scene.renderTargetsEnabled = false;
  24602. return true;
  24603. };
  24604. }
  24605. return RenderTargetsOptimization;
  24606. })(SceneOptimization);
  24607. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  24608. var MergeMeshesOptimization = (function (_super) {
  24609. __extends(MergeMeshesOptimization, _super);
  24610. function MergeMeshesOptimization() {
  24611. _super.apply(this, arguments);
  24612. var _this = this;
  24613. this._canBeMerged = function (abstractMesh) {
  24614. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  24615. return false;
  24616. }
  24617. var mesh = abstractMesh;
  24618. if (!mesh.isVisible || !mesh.isEnabled()) {
  24619. return false;
  24620. }
  24621. if (mesh.instances.length > 0) {
  24622. return false;
  24623. }
  24624. if (mesh.skeleton || mesh.hasLODLevels) {
  24625. return false;
  24626. }
  24627. return true;
  24628. };
  24629. this.apply = function (scene) {
  24630. var globalPool = scene.meshes.slice(0);
  24631. var globalLength = globalPool.length;
  24632. for (var index = 0; index < globalLength; index++) {
  24633. var currentPool = new Array();
  24634. var current = globalPool[index];
  24635. // Checks
  24636. if (!_this._canBeMerged(current)) {
  24637. continue;
  24638. }
  24639. currentPool.push(current);
  24640. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  24641. var otherMesh = globalPool[subIndex];
  24642. if (!_this._canBeMerged(otherMesh)) {
  24643. continue;
  24644. }
  24645. if (otherMesh.material !== current.material) {
  24646. continue;
  24647. }
  24648. if (otherMesh.checkCollisions !== current.checkCollisions) {
  24649. continue;
  24650. }
  24651. currentPool.push(otherMesh);
  24652. globalLength--;
  24653. globalPool.splice(subIndex, 1);
  24654. subIndex--;
  24655. }
  24656. if (currentPool.length < 2) {
  24657. continue;
  24658. }
  24659. // Merge meshes
  24660. BABYLON.Mesh.MergeMeshes(currentPool);
  24661. }
  24662. return true;
  24663. };
  24664. }
  24665. return MergeMeshesOptimization;
  24666. })(SceneOptimization);
  24667. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  24668. // Options
  24669. var SceneOptimizerOptions = (function () {
  24670. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  24671. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  24672. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  24673. this.targetFrameRate = targetFrameRate;
  24674. this.trackerDuration = trackerDuration;
  24675. this.optimizations = new Array();
  24676. }
  24677. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24678. var result = new SceneOptimizerOptions(targetFrameRate);
  24679. var priority = 0;
  24680. result.optimizations.push(new MergeMeshesOptimization(priority));
  24681. result.optimizations.push(new ShadowsOptimization(priority));
  24682. result.optimizations.push(new LensFlaresOptimization(priority));
  24683. // Next priority
  24684. priority++;
  24685. result.optimizations.push(new PostProcessesOptimization(priority));
  24686. result.optimizations.push(new ParticlesOptimization(priority));
  24687. // Next priority
  24688. priority++;
  24689. result.optimizations.push(new TextureOptimization(priority, 1024));
  24690. return result;
  24691. };
  24692. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24693. var result = new SceneOptimizerOptions(targetFrameRate);
  24694. var priority = 0;
  24695. result.optimizations.push(new MergeMeshesOptimization(priority));
  24696. result.optimizations.push(new ShadowsOptimization(priority));
  24697. result.optimizations.push(new LensFlaresOptimization(priority));
  24698. // Next priority
  24699. priority++;
  24700. result.optimizations.push(new PostProcessesOptimization(priority));
  24701. result.optimizations.push(new ParticlesOptimization(priority));
  24702. // Next priority
  24703. priority++;
  24704. result.optimizations.push(new TextureOptimization(priority, 512));
  24705. // Next priority
  24706. priority++;
  24707. result.optimizations.push(new RenderTargetsOptimization(priority));
  24708. // Next priority
  24709. priority++;
  24710. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24711. return result;
  24712. };
  24713. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24714. var result = new SceneOptimizerOptions(targetFrameRate);
  24715. var priority = 0;
  24716. result.optimizations.push(new MergeMeshesOptimization(priority));
  24717. result.optimizations.push(new ShadowsOptimization(priority));
  24718. result.optimizations.push(new LensFlaresOptimization(priority));
  24719. // Next priority
  24720. priority++;
  24721. result.optimizations.push(new PostProcessesOptimization(priority));
  24722. result.optimizations.push(new ParticlesOptimization(priority));
  24723. // Next priority
  24724. priority++;
  24725. result.optimizations.push(new TextureOptimization(priority, 256));
  24726. // Next priority
  24727. priority++;
  24728. result.optimizations.push(new RenderTargetsOptimization(priority));
  24729. // Next priority
  24730. priority++;
  24731. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24732. return result;
  24733. };
  24734. return SceneOptimizerOptions;
  24735. })();
  24736. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24737. // Scene optimizer tool
  24738. var SceneOptimizer = (function () {
  24739. function SceneOptimizer() {
  24740. }
  24741. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24742. // TODO: add an epsilon
  24743. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24744. if (onSuccess) {
  24745. onSuccess();
  24746. }
  24747. return;
  24748. }
  24749. // Apply current level of optimizations
  24750. var allDone = true;
  24751. var noOptimizationApplied = true;
  24752. for (var index = 0; index < options.optimizations.length; index++) {
  24753. var optimization = options.optimizations[index];
  24754. if (optimization.priority === currentPriorityLevel) {
  24755. noOptimizationApplied = false;
  24756. allDone = allDone && optimization.apply(scene);
  24757. }
  24758. }
  24759. // If no optimization was applied, this is a failure :(
  24760. if (noOptimizationApplied) {
  24761. if (onFailure) {
  24762. onFailure();
  24763. }
  24764. return;
  24765. }
  24766. // If all optimizations were done, move to next level
  24767. if (allDone) {
  24768. currentPriorityLevel++;
  24769. }
  24770. // Let's the system running for a specific amount of time before checking FPS
  24771. scene.executeWhenReady(function () {
  24772. setTimeout(function () {
  24773. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24774. }, options.trackerDuration);
  24775. });
  24776. };
  24777. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24778. if (!options) {
  24779. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24780. }
  24781. // Let's the system running for a specific amount of time before checking FPS
  24782. scene.executeWhenReady(function () {
  24783. setTimeout(function () {
  24784. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24785. }, options.trackerDuration);
  24786. });
  24787. };
  24788. return SceneOptimizer;
  24789. })();
  24790. BABYLON.SceneOptimizer = SceneOptimizer;
  24791. })(BABYLON || (BABYLON = {}));
  24792. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24793. var BABYLON;
  24794. (function (BABYLON) {
  24795. (function (Internals) {
  24796. var MeshLODLevel = (function () {
  24797. function MeshLODLevel(distance, mesh) {
  24798. this.distance = distance;
  24799. this.mesh = mesh;
  24800. }
  24801. return MeshLODLevel;
  24802. })();
  24803. Internals.MeshLODLevel = MeshLODLevel;
  24804. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24805. var Internals = BABYLON.Internals;
  24806. })(BABYLON || (BABYLON = {}));
  24807. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24808. var BABYLON;
  24809. (function (BABYLON) {
  24810. var AudioEngine = (function () {
  24811. function AudioEngine() {
  24812. this.audioContext = null;
  24813. this.canUseWebAudio = false;
  24814. try {
  24815. if (typeof AudioContext !== 'undefined') {
  24816. this.audioContext = new AudioContext();
  24817. this.canUseWebAudio = true;
  24818. } else if (typeof webkitAudioContext !== 'undefined') {
  24819. this.audioContext = new webkitAudioContext();
  24820. this.canUseWebAudio = true;
  24821. }
  24822. } catch (e) {
  24823. this.canUseWebAudio = false;
  24824. BABYLON.Tools.Error("Your browser doesn't support Web Audio.");
  24825. }
  24826. // create a global volume gain node
  24827. if (this.canUseWebAudio) {
  24828. this.masterGain = this.audioContext.createGain();
  24829. this.masterGain.gain.value = 1;
  24830. this.masterGain.connect(this.audioContext.destination);
  24831. }
  24832. }
  24833. AudioEngine.prototype.getGlobalVolume = function () {
  24834. if (this.canUseWebAudio) {
  24835. return this.masterGain.gain.value;
  24836. } else {
  24837. return -1;
  24838. }
  24839. };
  24840. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24841. if (this.canUseWebAudio) {
  24842. this.masterGain.gain.value = newVolume;
  24843. }
  24844. };
  24845. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  24846. if (this.canUseWebAudio) {
  24847. this.masterGain.disconnect();
  24848. analyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  24849. }
  24850. };
  24851. return AudioEngine;
  24852. })();
  24853. BABYLON.AudioEngine = AudioEngine;
  24854. })(BABYLON || (BABYLON = {}));
  24855. //# sourceMappingURL=babylon.audioengine.js.map
  24856. var BABYLON;
  24857. (function (BABYLON) {
  24858. var Sound = (function () {
  24859. /**
  24860. * Create a sound and attach it to a scene
  24861. * @param name Name of your sound
  24862. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  24863. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24864. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  24865. */
  24866. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  24867. var _this = this;
  24868. this.autoplay = false;
  24869. this.loop = false;
  24870. this.useCustomAttenuation = false;
  24871. this.spatialSound = false;
  24872. this.refDistance = 1;
  24873. this.rolloffFactor = 1;
  24874. this.maxDistance = 100;
  24875. this.distanceModel = "linear";
  24876. this.panningModel = "HRTF";
  24877. this.startTime = 0;
  24878. this.startOffset = 0;
  24879. this._position = BABYLON.Vector3.Zero();
  24880. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24881. this._volume = 1;
  24882. this._isLoaded = false;
  24883. this._isReadyToPlay = false;
  24884. this._isPlaying = false;
  24885. this._isDirectional = false;
  24886. // Used if you'd like to create a directional sound.
  24887. // If not set, the sound will be omnidirectional
  24888. this._coneInnerAngle = 360;
  24889. this._coneOuterAngle = 360;
  24890. this._coneOuterGain = 0;
  24891. this._name = name;
  24892. this._scene = scene;
  24893. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24894. this._readyToPlayCallback = readyToPlayCallback;
  24895. // Default custom attenuation function is a linear attenuation
  24896. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  24897. if (currentDistance < maxDistance) {
  24898. return currentVolume * (1 - currentDistance / maxDistance);
  24899. } else {
  24900. return 0;
  24901. }
  24902. };
  24903. if (options) {
  24904. this.autoplay = options.autoplay || false;
  24905. this.loop = options.loop || false;
  24906. this._volume = options.volume || 1;
  24907. this.spatialSound = options.spatialSound || false;
  24908. this.maxDistance = options.maxDistance || 100;
  24909. this.useCustomAttenuation = options.useCustomAttenation || false;
  24910. this.rolloffFactor = options.rolloffFactor || 1;
  24911. this.refDistance = options.refDistance || 1;
  24912. this.distanceModel = options.distanceModel || "linear";
  24913. this.panningModel = options.panningModel || "HRTF";
  24914. }
  24915. if (this._audioEngine.canUseWebAudio) {
  24916. this._soundGain = this._audioEngine.audioContext.createGain();
  24917. this._soundGain.gain.value = this._volume;
  24918. if (this.spatialSound) {
  24919. this._createSpatialParameters();
  24920. } else {
  24921. this._audioNode = this._soundGain;
  24922. }
  24923. this._scene.mainSoundTrack.AddSound(this);
  24924. if (typeof (urlOrArrayBuffer) === "string") {
  24925. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  24926. _this._soundLoaded(data);
  24927. }, null, null, true);
  24928. } else {
  24929. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  24930. this._soundLoaded(urlOrArrayBuffer);
  24931. } else {
  24932. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  24933. }
  24934. }
  24935. }
  24936. }
  24937. Sound.prototype._soundLoaded = function (audioData) {
  24938. var _this = this;
  24939. this._isLoaded = true;
  24940. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24941. _this._audioBuffer = buffer;
  24942. _this._isReadyToPlay = true;
  24943. if (_this.autoplay) {
  24944. _this.play();
  24945. }
  24946. if (_this._readyToPlayCallback) {
  24947. _this._readyToPlayCallback();
  24948. }
  24949. }, function (error) {
  24950. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24951. });
  24952. };
  24953. Sound.prototype.updateOptions = function (options) {
  24954. if (options) {
  24955. this.loop = options.loop || this.loop;
  24956. this.maxDistance = options.maxDistance || this.maxDistance;
  24957. this.useCustomAttenuation = options.useCustomAttenation || this.useCustomAttenuation;
  24958. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  24959. this.refDistance = options.refDistance || this.refDistance;
  24960. this.distanceModel = options.distanceModel || this.distanceModel;
  24961. this.panningModel = options.panningModel || this.panningModel;
  24962. }
  24963. };
  24964. Sound.prototype._createSpatialParameters = function () {
  24965. if (this._audioEngine.canUseWebAudio) {
  24966. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24967. if (this.useCustomAttenuation) {
  24968. // Tricks to disable in a way embedded Web Audio attenuation
  24969. this._soundPanner.distanceModel = "linear";
  24970. this._soundPanner.maxDistance = Number.MAX_VALUE;
  24971. this._soundPanner.refDistance = 1;
  24972. this._soundPanner.rolloffFactor = 1;
  24973. this._soundPanner.panningModel = "HRTF";
  24974. } else {
  24975. this._soundPanner.distanceModel = this.distanceModel;
  24976. this._soundPanner.maxDistance = this.maxDistance;
  24977. this._soundPanner.refDistance = this.refDistance;
  24978. this._soundPanner.rolloffFactor = this.rolloffFactor;
  24979. this._soundPanner.panningModel = this.panningModel;
  24980. }
  24981. this._soundPanner.connect(this._soundGain);
  24982. this._audioNode = this._soundPanner;
  24983. }
  24984. };
  24985. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24986. if (this._audioEngine.canUseWebAudio) {
  24987. this._audioNode.disconnect();
  24988. this._audioNode.connect(soundTrackAudioNode);
  24989. }
  24990. };
  24991. /**
  24992. * Transform this sound into a directional source
  24993. * @param coneInnerAngle Size of the inner cone in degree
  24994. * @param coneOuterAngle Size of the outer cone in degree
  24995. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24996. */
  24997. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24998. if (coneOuterAngle < coneInnerAngle) {
  24999. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25000. return;
  25001. }
  25002. this._coneInnerAngle = coneInnerAngle;
  25003. this._coneOuterAngle = coneOuterAngle;
  25004. this._coneOuterGain = coneOuterGain;
  25005. this._isDirectional = true;
  25006. if (this._isPlaying && this.loop) {
  25007. this.stop();
  25008. this.play();
  25009. }
  25010. };
  25011. Sound.prototype.setPosition = function (newPosition) {
  25012. this._position = newPosition;
  25013. if (this._isPlaying && this.spatialSound) {
  25014. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25015. }
  25016. };
  25017. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25018. this._localDirection = newLocalDirection;
  25019. if (this._connectedMesh && this._isPlaying) {
  25020. this._updateDirection();
  25021. }
  25022. };
  25023. Sound.prototype._updateDirection = function () {
  25024. var mat = this._connectedMesh.getWorldMatrix();
  25025. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25026. direction.normalize();
  25027. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25028. };
  25029. Sound.prototype.updateDistanceFromListener = function () {
  25030. if (this._connectedMesh && this.useCustomAttenuation) {
  25031. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25032. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25033. }
  25034. };
  25035. Sound.prototype.setAttenuationFunction = function (callback) {
  25036. this._customAttenuationFunction = callback;
  25037. };
  25038. /**
  25039. * Play the sound
  25040. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25041. */
  25042. Sound.prototype.play = function (time) {
  25043. if (this._isReadyToPlay) {
  25044. try {
  25045. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25046. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  25047. this._soundSource.buffer = this._audioBuffer;
  25048. if (this.spatialSound) {
  25049. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25050. if (this._isDirectional) {
  25051. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25052. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25053. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25054. if (this._connectedMesh) {
  25055. this._updateDirection();
  25056. } else {
  25057. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25058. }
  25059. }
  25060. }
  25061. this._soundSource.connect(this._audioNode);
  25062. this._soundSource.loop = this.loop;
  25063. this.startTime = startTime;
  25064. this._soundSource.start(startTime, this.startOffset % this._soundSource.buffer.duration);
  25065. this._isPlaying = true;
  25066. } catch (ex) {
  25067. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  25068. }
  25069. }
  25070. };
  25071. /**
  25072. * Stop the sound
  25073. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25074. */
  25075. Sound.prototype.stop = function (time) {
  25076. if (this._isPlaying) {
  25077. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25078. this._soundSource.stop(stopTime);
  25079. this._isPlaying = false;
  25080. }
  25081. };
  25082. Sound.prototype.pause = function () {
  25083. if (this._isPlaying) {
  25084. this._soundSource.stop(0);
  25085. this.startOffset += this._audioEngine.audioContext.currentTime - this.startTime;
  25086. }
  25087. };
  25088. Sound.prototype.setVolume = function (newVolume) {
  25089. this._volume = newVolume;
  25090. if (this._audioEngine.canUseWebAudio) {
  25091. this._soundGain.gain.value = newVolume;
  25092. }
  25093. };
  25094. Sound.prototype.getVolume = function () {
  25095. return this._volume;
  25096. };
  25097. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25098. var _this = this;
  25099. this._connectedMesh = meshToConnectTo;
  25100. if (!this.spatialSound) {
  25101. this._createSpatialParameters();
  25102. this.spatialSound = true;
  25103. if (this._isPlaying && this.loop) {
  25104. this.stop();
  25105. this.play();
  25106. }
  25107. }
  25108. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  25109. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  25110. });
  25111. };
  25112. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25113. this.setPosition(connectedMesh.position);
  25114. if (this._isDirectional && this._isPlaying) {
  25115. this._updateDirection();
  25116. }
  25117. };
  25118. return Sound;
  25119. })();
  25120. BABYLON.Sound = Sound;
  25121. })(BABYLON || (BABYLON = {}));
  25122. //# sourceMappingURL=babylon.sound.js.map
  25123. var BABYLON;
  25124. (function (BABYLON) {
  25125. var SoundTrack = (function () {
  25126. function SoundTrack(scene, options) {
  25127. this.id = -1;
  25128. this._isMainTrack = false;
  25129. this._scene = scene;
  25130. this._audioEngine = scene.getEngine().getAudioEngine();
  25131. this.soundCollection = new Array();
  25132. if (this._audioEngine.canUseWebAudio) {
  25133. this._trackGain = this._audioEngine.audioContext.createGain();
  25134. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  25135. //this._trackConvolver.connect(this._trackGain);
  25136. this._trackGain.connect(this._audioEngine.masterGain);
  25137. if (options) {
  25138. if (options.volume) {
  25139. this._trackGain.gain.value = options.volume;
  25140. }
  25141. if (options.mainTrack) {
  25142. this._isMainTrack = options.mainTrack;
  25143. }
  25144. }
  25145. }
  25146. if (!this._isMainTrack) {
  25147. this._scene.soundTracks.push(this);
  25148. this.id = this._scene.soundTracks.length - 1;
  25149. }
  25150. }
  25151. SoundTrack.prototype.AddSound = function (sound) {
  25152. sound.connectToSoundTrackAudioNode(this._trackGain);
  25153. if (sound.soundTrackId) {
  25154. if (sound.soundTrackId === -1) {
  25155. this._scene.mainSoundTrack.RemoveSound(sound);
  25156. } else {
  25157. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25158. }
  25159. }
  25160. this.soundCollection.push(sound);
  25161. sound.soundTrackId = this.id;
  25162. };
  25163. SoundTrack.prototype.RemoveSound = function (sound) {
  25164. var index = this.soundCollection.indexOf(sound);
  25165. if (index !== -1) {
  25166. this.soundCollection.splice(index, 1);
  25167. }
  25168. };
  25169. SoundTrack.prototype.setVolume = function (newVolume) {
  25170. if (this._audioEngine.canUseWebAudio) {
  25171. this._trackGain.gain.value = newVolume;
  25172. }
  25173. };
  25174. return SoundTrack;
  25175. })();
  25176. BABYLON.SoundTrack = SoundTrack;
  25177. })(BABYLON || (BABYLON = {}));
  25178. //# sourceMappingURL=babylon.soundtrack.js.map
  25179. var BABYLON;
  25180. (function (BABYLON) {
  25181. var DebugLayer = (function () {
  25182. function DebugLayer(scene) {
  25183. var _this = this;
  25184. this._enabled = false;
  25185. this._labelsEnabled = false;
  25186. this._displayStatistics = true;
  25187. this._displayTree = false;
  25188. this._displayLogs = false;
  25189. this._identityMatrix = BABYLON.Matrix.Identity();
  25190. this.axisRatio = 0.02;
  25191. this.accentColor = "orange";
  25192. this._scene = scene;
  25193. this._syncPositions = function () {
  25194. var engine = _this._scene.getEngine();
  25195. var canvasRect = engine.getRenderingCanvasClientRect();
  25196. if (_this._showUI) {
  25197. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  25198. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  25199. _this._statsDiv.style.width = "400px";
  25200. _this._statsDiv.style.height = "auto";
  25201. _this._statsSubsetDiv.style.maxHeight = "240px";
  25202. _this._optionsDiv.style.left = "0px";
  25203. _this._optionsDiv.style.top = "10px";
  25204. _this._optionsDiv.style.width = "200px";
  25205. _this._optionsDiv.style.height = "auto";
  25206. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  25207. _this._logDiv.style.left = "0px";
  25208. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  25209. _this._logDiv.style.width = "600px";
  25210. _this._logDiv.style.height = "160px";
  25211. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  25212. _this._treeDiv.style.top = "10px";
  25213. _this._treeDiv.style.width = "300px";
  25214. _this._treeDiv.style.height = "auto";
  25215. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  25216. }
  25217. _this._globalDiv.style.left = canvasRect.left + "px";
  25218. _this._globalDiv.style.top = canvasRect.top + "px";
  25219. _this._drawingCanvas.style.left = "0px";
  25220. _this._drawingCanvas.style.top = "0px";
  25221. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  25222. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  25223. var devicePixelRatio = window.devicePixelRatio || 1;
  25224. var context = _this._drawingContext;
  25225. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  25226. _this._ratio = devicePixelRatio / backingStoreRatio;
  25227. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  25228. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  25229. };
  25230. this._onCanvasClick = function (evt) {
  25231. _this._clickPosition = {
  25232. x: evt.clientX * _this._ratio,
  25233. y: evt.clientY * _this._ratio
  25234. };
  25235. };
  25236. this._syncData = function () {
  25237. if (_this._showUI) {
  25238. if (_this._displayStatistics) {
  25239. _this._displayStats();
  25240. _this._statsDiv.style.display = "";
  25241. } else {
  25242. _this._statsDiv.style.display = "none";
  25243. }
  25244. if (_this._displayLogs) {
  25245. _this._logDiv.style.display = "";
  25246. } else {
  25247. _this._logDiv.style.display = "none";
  25248. }
  25249. if (_this._displayTree) {
  25250. _this._treeDiv.style.display = "";
  25251. if (_this._needToRefreshMeshesTree) {
  25252. _this._needToRefreshMeshesTree = false;
  25253. _this._refreshMeshesTreeContent();
  25254. }
  25255. } else {
  25256. _this._treeDiv.style.display = "none";
  25257. }
  25258. }
  25259. if (_this._labelsEnabled || !_this._showUI) {
  25260. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  25261. var engine = _this._scene.getEngine();
  25262. var viewport = _this._scene.activeCamera.viewport;
  25263. var globalViewport = viewport.toGlobal(engine);
  25264. // Meshes
  25265. var meshes = _this._scene.getActiveMeshes();
  25266. for (var index = 0; index < meshes.length; index++) {
  25267. var mesh = meshes.data[index];
  25268. var position = mesh.getBoundingInfo().boundingSphere.center;
  25269. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25270. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25271. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25272. }
  25273. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25274. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25275. mesh.renderOverlay = !mesh.renderOverlay;
  25276. }, function () {
  25277. return mesh.renderOverlay ? 'red' : 'black';
  25278. });
  25279. }
  25280. }
  25281. // Cameras
  25282. var cameras = _this._scene.cameras;
  25283. for (index = 0; index < cameras.length; index++) {
  25284. var camera = cameras[index];
  25285. if (camera === _this._scene.activeCamera) {
  25286. continue;
  25287. }
  25288. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25289. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25290. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25291. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25292. _this._scene.activeCamera = camera;
  25293. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25294. }, function () {
  25295. return "purple";
  25296. });
  25297. }
  25298. }
  25299. // Lights
  25300. var lights = _this._scene.lights;
  25301. for (index = 0; index < lights.length; index++) {
  25302. var light = lights[index];
  25303. if (light.position) {
  25304. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25305. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25306. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25307. light.setEnabled(!light.isEnabled());
  25308. }, function () {
  25309. return light.isEnabled() ? "orange" : "gray";
  25310. });
  25311. }
  25312. }
  25313. }
  25314. }
  25315. _this._clickPosition = undefined;
  25316. };
  25317. }
  25318. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25319. while (this._treeSubsetDiv.hasChildNodes()) {
  25320. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25321. }
  25322. // Add meshes
  25323. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25324. sortedArray.sort(function (a, b) {
  25325. if (a.name === b.name) {
  25326. return 0;
  25327. }
  25328. return (a.name > b.name) ? 1 : -1;
  25329. });
  25330. for (var index = 0; index < sortedArray.length; index++) {
  25331. var mesh = sortedArray[index];
  25332. if (!mesh.isEnabled()) {
  25333. continue;
  25334. }
  25335. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25336. m.isVisible = element.checked;
  25337. }, mesh);
  25338. }
  25339. };
  25340. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25341. this._drawingContext.beginPath();
  25342. this._drawingContext.moveTo(zero.x, zero.y);
  25343. this._drawingContext.lineTo(unit.x, unit.y);
  25344. this._drawingContext.strokeStyle = color;
  25345. this._drawingContext.lineWidth = 4;
  25346. this._drawingContext.stroke();
  25347. this._drawingContext.font = "normal 14px Segoe UI";
  25348. this._drawingContext.fillStyle = color;
  25349. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25350. };
  25351. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25352. var position = mesh.getBoundingInfo().boundingSphere.center;
  25353. var worldMatrix = mesh.getWorldMatrix();
  25354. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  25355. var unit = (unprojectedVector.subtract(position)).length();
  25356. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25357. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25358. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25359. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25360. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25361. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25362. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25363. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25364. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25365. };
  25366. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25367. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25368. this._drawingContext.font = "normal 12px Segoe UI";
  25369. var textMetrics = this._drawingContext.measureText(text);
  25370. var centerX = projectedPosition.x - textMetrics.width / 2;
  25371. var centerY = projectedPosition.y;
  25372. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  25373. onClick();
  25374. }
  25375. this._drawingContext.beginPath();
  25376. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  25377. this._drawingContext.fillStyle = getFillStyle();
  25378. this._drawingContext.globalAlpha = 0.5;
  25379. this._drawingContext.fill();
  25380. this._drawingContext.globalAlpha = 1.0;
  25381. this._drawingContext.strokeStyle = '#FFFFFF';
  25382. this._drawingContext.lineWidth = 1;
  25383. this._drawingContext.stroke();
  25384. this._drawingContext.fillStyle = "#FFFFFF";
  25385. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  25386. this._drawingContext.beginPath();
  25387. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  25388. this._drawingContext.fill();
  25389. }
  25390. };
  25391. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  25392. if (!this._clickPosition) {
  25393. return false;
  25394. }
  25395. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  25396. return false;
  25397. }
  25398. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  25399. return false;
  25400. }
  25401. return true;
  25402. };
  25403. DebugLayer.prototype.isVisible = function () {
  25404. return this._enabled;
  25405. };
  25406. DebugLayer.prototype.hide = function () {
  25407. if (!this._enabled) {
  25408. return;
  25409. }
  25410. this._enabled = false;
  25411. var engine = this._scene.getEngine();
  25412. this._scene.unregisterAfterRender(this._syncData);
  25413. document.body.removeChild(this._globalDiv);
  25414. window.removeEventListener("resize", this._syncPositions);
  25415. this._scene.forceShowBoundingBoxes = false;
  25416. this._scene.forceWireframe = false;
  25417. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  25418. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  25419. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  25420. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  25421. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  25422. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  25423. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  25424. this._scene.shadowsEnabled = true;
  25425. this._scene.particlesEnabled = true;
  25426. this._scene.postProcessesEnabled = true;
  25427. this._scene.collisionsEnabled = true;
  25428. this._scene.lightsEnabled = true;
  25429. this._scene.texturesEnabled = true;
  25430. this._scene.lensFlaresEnabled = true;
  25431. this._scene.proceduralTexturesEnabled = true;
  25432. this._scene.renderTargetsEnabled = true;
  25433. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  25434. };
  25435. DebugLayer.prototype.show = function (showUI) {
  25436. if (typeof showUI === "undefined") { showUI = true; }
  25437. if (this._enabled) {
  25438. return;
  25439. }
  25440. this._enabled = true;
  25441. this._showUI = showUI;
  25442. var engine = this._scene.getEngine();
  25443. this._globalDiv = document.createElement("div");
  25444. document.body.appendChild(this._globalDiv);
  25445. this._generateDOMelements();
  25446. window.addEventListener("resize", this._syncPositions);
  25447. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  25448. this._syncPositions();
  25449. this._scene.registerAfterRender(this._syncData);
  25450. };
  25451. DebugLayer.prototype._clearLabels = function () {
  25452. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  25453. for (var index = 0; index < this._scene.meshes.length; index++) {
  25454. var mesh = this._scene.meshes[index];
  25455. mesh.renderOverlay = false;
  25456. }
  25457. };
  25458. DebugLayer.prototype._generateheader = function (root, text) {
  25459. var header = document.createElement("div");
  25460. header.innerHTML = text + "&nbsp;";
  25461. header.style.textAlign = "right";
  25462. header.style.width = "100%";
  25463. header.style.color = "white";
  25464. header.style.backgroundColor = "Black";
  25465. header.style.padding = "5px 5px 4px 0px";
  25466. header.style.marginLeft = "-5px";
  25467. header.style.fontWeight = "bold";
  25468. root.appendChild(header);
  25469. };
  25470. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  25471. var label = document.createElement("label");
  25472. label.innerHTML = title;
  25473. label.style.color = color;
  25474. root.appendChild(label);
  25475. root.appendChild(document.createElement("br"));
  25476. };
  25477. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  25478. if (typeof tag === "undefined") { tag = null; }
  25479. var label = document.createElement("label");
  25480. var boundingBoxesCheckbox = document.createElement("input");
  25481. boundingBoxesCheckbox.type = "checkbox";
  25482. boundingBoxesCheckbox.checked = initialState;
  25483. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25484. task(evt.target, tag);
  25485. });
  25486. label.appendChild(boundingBoxesCheckbox);
  25487. var container = document.createElement("span");
  25488. var leftPart = document.createElement("span");
  25489. var rightPart = document.createElement("span");
  25490. rightPart.style.cssFloat = "right";
  25491. leftPart.innerHTML = leftTitle;
  25492. rightPart.innerHTML = rightTitle;
  25493. rightPart.style.fontSize = "12px";
  25494. rightPart.style.maxWidth = "200px";
  25495. container.appendChild(leftPart);
  25496. container.appendChild(rightPart);
  25497. label.appendChild(container);
  25498. root.appendChild(label);
  25499. root.appendChild(document.createElement("br"));
  25500. };
  25501. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  25502. if (typeof tag === "undefined") { tag = null; }
  25503. var label = document.createElement("label");
  25504. var boundingBoxesCheckbox = document.createElement("input");
  25505. boundingBoxesCheckbox.type = "checkbox";
  25506. boundingBoxesCheckbox.checked = initialState;
  25507. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25508. task(evt.target, tag);
  25509. });
  25510. label.appendChild(boundingBoxesCheckbox);
  25511. label.appendChild(document.createTextNode(title));
  25512. root.appendChild(label);
  25513. root.appendChild(document.createElement("br"));
  25514. };
  25515. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  25516. if (typeof tag === "undefined") { tag = null; }
  25517. var label = document.createElement("label");
  25518. var boundingBoxesRadio = document.createElement("input");
  25519. boundingBoxesRadio.type = "radio";
  25520. boundingBoxesRadio.name = name;
  25521. boundingBoxesRadio.checked = initialState;
  25522. boundingBoxesRadio.addEventListener("change", function (evt) {
  25523. task(evt.target, tag);
  25524. });
  25525. label.appendChild(boundingBoxesRadio);
  25526. label.appendChild(document.createTextNode(title));
  25527. root.appendChild(label);
  25528. root.appendChild(document.createElement("br"));
  25529. };
  25530. DebugLayer.prototype._generateDOMelements = function () {
  25531. var _this = this;
  25532. this._globalDiv.id = "DebugLayer";
  25533. this._globalDiv.style.position = "absolute";
  25534. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  25535. this._globalDiv.style.fontSize = "14px";
  25536. this._globalDiv.style.color = "white";
  25537. // Drawing canvas
  25538. this._drawingCanvas = document.createElement("canvas");
  25539. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  25540. this._drawingCanvas.style.position = "absolute";
  25541. this._drawingCanvas.style.pointerEvents = "none";
  25542. this._drawingContext = this._drawingCanvas.getContext("2d");
  25543. this._globalDiv.appendChild(this._drawingCanvas);
  25544. if (this._showUI) {
  25545. var background = "rgba(128, 128, 128, 0.4)";
  25546. var border = "rgb(180, 180, 180) solid 1px";
  25547. // Stats
  25548. this._statsDiv = document.createElement("div");
  25549. this._statsDiv.id = "DebugLayerStats";
  25550. this._statsDiv.style.border = border;
  25551. this._statsDiv.style.position = "absolute";
  25552. this._statsDiv.style.background = background;
  25553. this._statsDiv.style.padding = "0px 0px 0px 5px";
  25554. this._generateheader(this._statsDiv, "STATISTICS");
  25555. this._statsSubsetDiv = document.createElement("div");
  25556. this._statsSubsetDiv.style.paddingTop = "5px";
  25557. this._statsSubsetDiv.style.paddingBottom = "5px";
  25558. this._statsSubsetDiv.style.overflowY = "auto";
  25559. this._statsDiv.appendChild(this._statsSubsetDiv);
  25560. // Tree
  25561. this._treeDiv = document.createElement("div");
  25562. this._treeDiv.id = "DebugLayerTree";
  25563. this._treeDiv.style.border = border;
  25564. this._treeDiv.style.position = "absolute";
  25565. this._treeDiv.style.background = background;
  25566. this._treeDiv.style.padding = "0px 0px 0px 5px";
  25567. this._treeDiv.style.display = "none";
  25568. this._generateheader(this._treeDiv, "MESHES TREE");
  25569. this._treeSubsetDiv = document.createElement("div");
  25570. this._treeSubsetDiv.style.paddingTop = "5px";
  25571. this._treeSubsetDiv.style.paddingRight = "5px";
  25572. this._treeSubsetDiv.style.overflowY = "auto";
  25573. this._treeSubsetDiv.style.maxHeight = "300px";
  25574. this._treeDiv.appendChild(this._treeSubsetDiv);
  25575. this._needToRefreshMeshesTree = true;
  25576. // Logs
  25577. this._logDiv = document.createElement("div");
  25578. this._logDiv.style.border = border;
  25579. this._logDiv.id = "DebugLayerLogs";
  25580. this._logDiv.style.position = "absolute";
  25581. this._logDiv.style.background = background;
  25582. this._logDiv.style.padding = "0px 0px 0px 5px";
  25583. this._logDiv.style.display = "none";
  25584. this._generateheader(this._logDiv, "LOGS");
  25585. this._logSubsetDiv = document.createElement("div");
  25586. this._logSubsetDiv.style.height = "127px";
  25587. this._logSubsetDiv.style.paddingTop = "5px";
  25588. this._logSubsetDiv.style.overflowY = "auto";
  25589. this._logSubsetDiv.style.fontSize = "12px";
  25590. this._logSubsetDiv.style.fontFamily = "consolas";
  25591. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  25592. this._logDiv.appendChild(this._logSubsetDiv);
  25593. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  25594. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  25595. };
  25596. // Options
  25597. this._optionsDiv = document.createElement("div");
  25598. this._optionsDiv.id = "DebugLayerOptions";
  25599. this._optionsDiv.style.border = border;
  25600. this._optionsDiv.style.position = "absolute";
  25601. this._optionsDiv.style.background = background;
  25602. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  25603. this._optionsDiv.style.overflowY = "auto";
  25604. this._generateheader(this._optionsDiv, "OPTIONS");
  25605. this._optionsSubsetDiv = document.createElement("div");
  25606. this._optionsSubsetDiv.style.paddingTop = "5px";
  25607. this._optionsSubsetDiv.style.paddingBottom = "5px";
  25608. this._optionsSubsetDiv.style.overflowY = "auto";
  25609. this._optionsSubsetDiv.style.maxHeight = "200px";
  25610. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  25611. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  25612. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  25613. _this._displayStatistics = element.checked;
  25614. });
  25615. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  25616. _this._displayLogs = element.checked;
  25617. });
  25618. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  25619. _this._displayTree = element.checked;
  25620. _this._needToRefreshMeshesTree = true;
  25621. });
  25622. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25623. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  25624. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  25625. _this._scene.forceShowBoundingBoxes = element.checked;
  25626. });
  25627. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  25628. _this._labelsEnabled = element.checked;
  25629. if (!_this._labelsEnabled) {
  25630. _this._clearLabels();
  25631. }
  25632. });
  25633. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  25634. if (element.checked) {
  25635. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  25636. } else {
  25637. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  25638. }
  25639. });
  25640. ;
  25641. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25642. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  25643. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  25644. if (element.checked) {
  25645. _this._scene.forceWireframe = false;
  25646. _this._scene.forcePointsCloud = false;
  25647. }
  25648. });
  25649. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  25650. if (element.checked) {
  25651. _this._scene.forceWireframe = true;
  25652. _this._scene.forcePointsCloud = false;
  25653. }
  25654. });
  25655. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  25656. if (element.checked) {
  25657. _this._scene.forceWireframe = false;
  25658. _this._scene.forcePointsCloud = true;
  25659. }
  25660. });
  25661. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25662. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  25663. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  25664. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  25665. });
  25666. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  25667. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  25668. });
  25669. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  25670. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  25671. });
  25672. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  25673. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  25674. });
  25675. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  25676. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  25677. });
  25678. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  25679. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  25680. });
  25681. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  25682. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  25683. });
  25684. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  25685. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  25686. });
  25687. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25688. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  25689. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  25690. _this._scene.animationsEnabled = element.checked;
  25691. });
  25692. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  25693. _this._scene.collisionsEnabled = element.checked;
  25694. });
  25695. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  25696. _this._scene.fogEnabled = element.checked;
  25697. });
  25698. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  25699. _this._scene.lensFlaresEnabled = element.checked;
  25700. });
  25701. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  25702. _this._scene.lightsEnabled = element.checked;
  25703. });
  25704. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  25705. _this._scene.particlesEnabled = element.checked;
  25706. });
  25707. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  25708. _this._scene.postProcessesEnabled = element.checked;
  25709. });
  25710. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  25711. _this._scene.proceduralTexturesEnabled = element.checked;
  25712. });
  25713. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  25714. _this._scene.renderTargetsEnabled = element.checked;
  25715. });
  25716. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  25717. _this._scene.shadowsEnabled = element.checked;
  25718. });
  25719. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  25720. _this._scene.skeletonsEnabled = element.checked;
  25721. });
  25722. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  25723. _this._scene.texturesEnabled = element.checked;
  25724. });
  25725. this._globalDiv.appendChild(this._statsDiv);
  25726. this._globalDiv.appendChild(this._logDiv);
  25727. this._globalDiv.appendChild(this._optionsDiv);
  25728. this._globalDiv.appendChild(this._treeDiv);
  25729. }
  25730. };
  25731. DebugLayer.prototype._displayStats = function () {
  25732. var scene = this._scene;
  25733. var engine = scene.getEngine();
  25734. var glInfo = engine.getGlInfo();
  25735. 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 vertices: " + scene.getActiveVertices() + "<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>";
  25736. if (this.customStatsFunction) {
  25737. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  25738. }
  25739. };
  25740. return DebugLayer;
  25741. })();
  25742. BABYLON.DebugLayer = DebugLayer;
  25743. })(BABYLON || (BABYLON = {}));
  25744. //# sourceMappingURL=babylon.debugLayer.js.map
  25745. var BABYLON;
  25746. (function (BABYLON) {
  25747. var RawTexture = (function (_super) {
  25748. __extends(RawTexture, _super);
  25749. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25750. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25751. if (typeof invertY === "undefined") { invertY = false; }
  25752. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25753. _super.call(this, null, scene, !generateMipMaps, invertY);
  25754. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25755. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25756. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25757. }
  25758. // Statics
  25759. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25760. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25761. if (typeof invertY === "undefined") { invertY = false; }
  25762. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25763. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25764. };
  25765. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25766. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25767. if (typeof invertY === "undefined") { invertY = false; }
  25768. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25769. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25770. };
  25771. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25772. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25773. if (typeof invertY === "undefined") { invertY = false; }
  25774. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25775. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25776. };
  25777. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25778. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25779. if (typeof invertY === "undefined") { invertY = false; }
  25780. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25781. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25782. };
  25783. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25784. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25785. if (typeof invertY === "undefined") { invertY = false; }
  25786. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25787. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25788. };
  25789. return RawTexture;
  25790. })(BABYLON.Texture);
  25791. BABYLON.RawTexture = RawTexture;
  25792. })(BABYLON || (BABYLON = {}));
  25793. //# sourceMappingURL=babylon.rawTexture.js.map
  25794. var BABYLON;
  25795. (function (BABYLON) {
  25796. var IndexedVector2 = (function (_super) {
  25797. __extends(IndexedVector2, _super);
  25798. function IndexedVector2(original, index) {
  25799. _super.call(this, original.x, original.y);
  25800. this.index = index;
  25801. }
  25802. return IndexedVector2;
  25803. })(BABYLON.Vector2);
  25804. var PolygonPoints = (function () {
  25805. function PolygonPoints() {
  25806. this.elements = new Array();
  25807. }
  25808. PolygonPoints.prototype.add = function (originalPoints) {
  25809. var _this = this;
  25810. var result = new Array();
  25811. originalPoints.forEach(function (point) {
  25812. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  25813. var newPoint = new IndexedVector2(point, _this.elements.length);
  25814. result.push(newPoint);
  25815. _this.elements.push(newPoint);
  25816. }
  25817. });
  25818. return result;
  25819. };
  25820. PolygonPoints.prototype.computeBounds = function () {
  25821. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25822. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25823. this.elements.forEach(function (point) {
  25824. // x
  25825. if (point.x < lmin.x) {
  25826. lmin.x = point.x;
  25827. } else if (point.x > lmax.x) {
  25828. lmax.x = point.x;
  25829. }
  25830. // y
  25831. if (point.y < lmin.y) {
  25832. lmin.y = point.y;
  25833. } else if (point.y > lmax.y) {
  25834. lmax.y = point.y;
  25835. }
  25836. });
  25837. return {
  25838. min: lmin,
  25839. max: lmax,
  25840. width: lmax.x - lmin.x,
  25841. height: lmax.y - lmin.y
  25842. };
  25843. };
  25844. return PolygonPoints;
  25845. })();
  25846. var Polygon = (function () {
  25847. function Polygon() {
  25848. }
  25849. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25850. return [
  25851. new BABYLON.Vector2(xmin, ymin),
  25852. new BABYLON.Vector2(xmax, ymin),
  25853. new BABYLON.Vector2(xmax, ymax),
  25854. new BABYLON.Vector2(xmin, ymax)
  25855. ];
  25856. };
  25857. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25858. if (typeof cx === "undefined") { cx = 0; }
  25859. if (typeof cy === "undefined") { cy = 0; }
  25860. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  25861. var result = new Array();
  25862. var angle = 0;
  25863. var increment = (Math.PI * 2) / numberOfSides;
  25864. for (var i = 0; i < numberOfSides; i++) {
  25865. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25866. angle -= increment;
  25867. }
  25868. return result;
  25869. };
  25870. Polygon.Parse = function (input) {
  25871. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25872. return (!isNaN(val));
  25873. });
  25874. var i, result = [];
  25875. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25876. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25877. }
  25878. return result;
  25879. };
  25880. Polygon.StartingAt = function (x, y) {
  25881. return BABYLON.Path2.StartingAt(x, y);
  25882. };
  25883. return Polygon;
  25884. })();
  25885. BABYLON.Polygon = Polygon;
  25886. var PolygonMeshBuilder = (function () {
  25887. function PolygonMeshBuilder(name, contours, scene) {
  25888. this._points = new PolygonPoints();
  25889. if (!("poly2tri" in window)) {
  25890. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25891. }
  25892. this._name = name;
  25893. this._scene = scene;
  25894. var points;
  25895. if (contours instanceof BABYLON.Path2) {
  25896. points = contours.getPoints();
  25897. } else {
  25898. points = contours;
  25899. }
  25900. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25901. }
  25902. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25903. this._swctx.addHole(this._points.add(hole));
  25904. return this;
  25905. };
  25906. PolygonMeshBuilder.prototype.build = function (updatable) {
  25907. if (typeof updatable === "undefined") { updatable = false; }
  25908. var result = new BABYLON.Mesh(this._name, this._scene);
  25909. var normals = [];
  25910. var positions = [];
  25911. var uvs = [];
  25912. var bounds = this._points.computeBounds();
  25913. this._points.elements.forEach(function (p) {
  25914. normals.push(0, 1.0, 0);
  25915. positions.push(p.x, 0, p.y);
  25916. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25917. });
  25918. var indices = [];
  25919. this._swctx.triangulate();
  25920. this._swctx.getTriangles().forEach(function (triangle) {
  25921. triangle.getPoints().forEach(function (point) {
  25922. indices.push(point.index);
  25923. });
  25924. });
  25925. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25926. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25927. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25928. result.setIndices(indices);
  25929. return result;
  25930. };
  25931. return PolygonMeshBuilder;
  25932. })();
  25933. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25934. })(BABYLON || (BABYLON = {}));
  25935. //# sourceMappingURL=babylon.polygonMesh.js.map
  25936. var BABYLON;
  25937. (function (BABYLON) {
  25938. var SimplificationSettings = (function () {
  25939. function SimplificationSettings(quality, distance) {
  25940. this.quality = quality;
  25941. this.distance = distance;
  25942. }
  25943. return SimplificationSettings;
  25944. })();
  25945. BABYLON.SimplificationSettings = SimplificationSettings;
  25946. /**
  25947. * The implemented types of simplification.
  25948. * At the moment only Quadratic Error Decimation is implemented.
  25949. */
  25950. (function (SimplificationType) {
  25951. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  25952. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  25953. var SimplificationType = BABYLON.SimplificationType;
  25954. var DecimationTriangle = (function () {
  25955. function DecimationTriangle(vertices) {
  25956. this.vertices = vertices;
  25957. this.error = new Array(4);
  25958. this.deleted = false;
  25959. this.isDirty = false;
  25960. this.borderFactor = 0;
  25961. }
  25962. return DecimationTriangle;
  25963. })();
  25964. BABYLON.DecimationTriangle = DecimationTriangle;
  25965. var DecimationVertex = (function () {
  25966. function DecimationVertex(position, normal, uv, id) {
  25967. this.position = position;
  25968. this.normal = normal;
  25969. this.uv = uv;
  25970. this.id = id;
  25971. this.isBorder = true;
  25972. this.q = new QuadraticMatrix();
  25973. this.triangleCount = 0;
  25974. this.triangleStart = 0;
  25975. }
  25976. return DecimationVertex;
  25977. })();
  25978. BABYLON.DecimationVertex = DecimationVertex;
  25979. var QuadraticMatrix = (function () {
  25980. function QuadraticMatrix(data) {
  25981. this.data = new Array(10);
  25982. for (var i = 0; i < 10; ++i) {
  25983. if (data && data[i]) {
  25984. this.data[i] = data[i];
  25985. } else {
  25986. this.data[i] = 0;
  25987. }
  25988. }
  25989. }
  25990. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  25991. 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];
  25992. return det;
  25993. };
  25994. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  25995. for (var i = 0; i < 10; ++i) {
  25996. this.data[i] += matrix.data[i];
  25997. }
  25998. };
  25999. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26000. for (var i = 0; i < 10; ++i) {
  26001. this.data[i] += data[i];
  26002. }
  26003. };
  26004. QuadraticMatrix.prototype.add = function (matrix) {
  26005. var m = new QuadraticMatrix();
  26006. for (var i = 0; i < 10; ++i) {
  26007. m.data[i] = this.data[i] + matrix.data[i];
  26008. }
  26009. return m;
  26010. };
  26011. QuadraticMatrix.FromData = function (a, b, c, d) {
  26012. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26013. };
  26014. //returning an array to avoid garbage collection
  26015. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26016. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26017. };
  26018. return QuadraticMatrix;
  26019. })();
  26020. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26021. var Reference = (function () {
  26022. function Reference(vertexId, triangleId) {
  26023. this.vertexId = vertexId;
  26024. this.triangleId = triangleId;
  26025. }
  26026. return Reference;
  26027. })();
  26028. BABYLON.Reference = Reference;
  26029. /**
  26030. * An implementation of the Quadratic Error simplification algorithm.
  26031. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26032. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26033. * @author RaananW
  26034. */
  26035. var QuadraticErrorSimplification = (function () {
  26036. function QuadraticErrorSimplification(_mesh) {
  26037. this._mesh = _mesh;
  26038. this.initialised = false;
  26039. this.syncIterations = 5000;
  26040. this.aggressiveness = 7;
  26041. this.decimationIterations = 100;
  26042. }
  26043. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26044. var _this = this;
  26045. this.initWithMesh(this._mesh, function () {
  26046. _this.runDecimation(settings, successCallback);
  26047. });
  26048. };
  26049. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26050. var _this = this;
  26051. var targetCount = ~~(this.triangles.length * settings.quality);
  26052. var deletedTriangles = 0;
  26053. var triangleCount = this.triangles.length;
  26054. var iterationFunction = function (iteration, callback) {
  26055. setTimeout(function () {
  26056. if (iteration % 5 === 0) {
  26057. _this.updateMesh(iteration === 0);
  26058. }
  26059. for (var i = 0; i < _this.triangles.length; ++i) {
  26060. _this.triangles[i].isDirty = false;
  26061. }
  26062. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26063. var trianglesIterator = function (i) {
  26064. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26065. var t = _this.triangles[tIdx];
  26066. if (!t)
  26067. return;
  26068. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26069. return;
  26070. }
  26071. for (var j = 0; j < 3; ++j) {
  26072. if (t.error[j] < threshold) {
  26073. var deleted0 = [];
  26074. var deleted1 = [];
  26075. var i0 = t.vertices[j];
  26076. var i1 = t.vertices[(j + 1) % 3];
  26077. var v0 = _this.vertices[i0];
  26078. var v1 = _this.vertices[i1];
  26079. if (v0.isBorder !== v1.isBorder)
  26080. continue;
  26081. var p = BABYLON.Vector3.Zero();
  26082. var n = BABYLON.Vector3.Zero();
  26083. var uv = BABYLON.Vector2.Zero();
  26084. var color = new BABYLON.Color4(0, 0, 0, 1);
  26085. _this.calculateError(v0, v1, p, n, uv, color);
  26086. var delTr = [];
  26087. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26088. continue;
  26089. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26090. continue;
  26091. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26092. continue;
  26093. }
  26094. v0.normal = n;
  26095. if (v0.uv)
  26096. v0.uv = uv;
  26097. else if (v0.color)
  26098. v0.color = color;
  26099. v0.q = v1.q.add(v0.q);
  26100. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26101. continue;
  26102. if (p.equals(v0.position))
  26103. continue;
  26104. v0.position = p;
  26105. var tStart = _this.references.length;
  26106. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26107. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26108. var tCount = _this.references.length - tStart;
  26109. if (tCount <= v0.triangleCount) {
  26110. if (tCount) {
  26111. for (var c = 0; c < tCount; c++) {
  26112. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26113. }
  26114. }
  26115. } else {
  26116. v0.triangleStart = tStart;
  26117. }
  26118. v0.triangleCount = tCount;
  26119. break;
  26120. }
  26121. }
  26122. };
  26123. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26124. return (triangleCount - deletedTriangles <= targetCount);
  26125. });
  26126. }, 0);
  26127. };
  26128. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26129. if (triangleCount - deletedTriangles <= targetCount)
  26130. loop.breakLoop();
  26131. else {
  26132. iterationFunction(loop.index, function () {
  26133. loop.executeNext();
  26134. });
  26135. }
  26136. }, function () {
  26137. setTimeout(function () {
  26138. successCallback(_this.reconstructMesh());
  26139. }, 0);
  26140. });
  26141. };
  26142. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26143. var _this = this;
  26144. if (!mesh)
  26145. return;
  26146. this.vertices = [];
  26147. this.triangles = [];
  26148. this._mesh = mesh;
  26149. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26150. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26151. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26152. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26153. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26154. var indices = mesh.getIndices();
  26155. var vertexInit = function (i) {
  26156. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  26157. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26158. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26159. } else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26160. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  26161. }
  26162. _this.vertices.push(vertex);
  26163. };
  26164. var totalVertices = mesh.getTotalVertices();
  26165. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26166. var indicesInit = function (i) {
  26167. var pos = i * 3;
  26168. var i0 = indices[pos + 0];
  26169. var i1 = indices[pos + 1];
  26170. var i2 = indices[pos + 2];
  26171. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26172. _this.triangles.push(triangle);
  26173. };
  26174. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26175. _this.init(callback);
  26176. });
  26177. });
  26178. };
  26179. QuadraticErrorSimplification.prototype.init = function (callback) {
  26180. var _this = this;
  26181. var triangleInit1 = function (i) {
  26182. var t = _this.triangles[i];
  26183. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  26184. for (var j = 0; j < 3; j++) {
  26185. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  26186. }
  26187. };
  26188. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  26189. var triangleInit2 = function (i) {
  26190. var t = _this.triangles[i];
  26191. for (var j = 0; j < 3; ++j) {
  26192. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  26193. }
  26194. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26195. };
  26196. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  26197. _this.initialised = true;
  26198. callback();
  26199. });
  26200. });
  26201. };
  26202. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  26203. var newTriangles = [];
  26204. var i;
  26205. for (i = 0; i < this.vertices.length; ++i) {
  26206. this.vertices[i].triangleCount = 0;
  26207. }
  26208. var t;
  26209. var j;
  26210. for (i = 0; i < this.triangles.length; ++i) {
  26211. if (!this.triangles[i].deleted) {
  26212. t = this.triangles[i];
  26213. for (j = 0; j < 3; ++j) {
  26214. this.vertices[t.vertices[j]].triangleCount = 1;
  26215. }
  26216. newTriangles.push(t);
  26217. }
  26218. }
  26219. var newVerticesOrder = [];
  26220. //compact vertices, get the IDs of the vertices used.
  26221. var dst = 0;
  26222. for (i = 0; i < this.vertices.length; ++i) {
  26223. if (this.vertices[i].triangleCount) {
  26224. this.vertices[i].triangleStart = dst;
  26225. this.vertices[dst].position = this.vertices[i].position;
  26226. this.vertices[dst].normal = this.vertices[i].normal;
  26227. this.vertices[dst].uv = this.vertices[i].uv;
  26228. this.vertices[dst].color = this.vertices[i].color;
  26229. newVerticesOrder.push(i);
  26230. dst++;
  26231. }
  26232. }
  26233. for (i = 0; i < newTriangles.length; ++i) {
  26234. t = newTriangles[i];
  26235. for (j = 0; j < 3; ++j) {
  26236. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  26237. }
  26238. }
  26239. this.vertices = this.vertices.slice(0, dst);
  26240. var newPositionData = [];
  26241. var newNormalData = [];
  26242. var newUVsData = [];
  26243. var newColorsData = [];
  26244. for (i = 0; i < newVerticesOrder.length; ++i) {
  26245. newPositionData.push(this.vertices[i].position.x);
  26246. newPositionData.push(this.vertices[i].position.y);
  26247. newPositionData.push(this.vertices[i].position.z);
  26248. newNormalData.push(this.vertices[i].normal.x);
  26249. newNormalData.push(this.vertices[i].normal.y);
  26250. newNormalData.push(this.vertices[i].normal.z);
  26251. if (this.vertices[i].uv) {
  26252. newUVsData.push(this.vertices[i].uv.x);
  26253. newUVsData.push(this.vertices[i].uv.y);
  26254. } else if (this.vertices[i].color) {
  26255. newColorsData.push(this.vertices[i].color.r);
  26256. newColorsData.push(this.vertices[i].color.g);
  26257. newColorsData.push(this.vertices[i].color.b);
  26258. newColorsData.push(this.vertices[i].color.a);
  26259. }
  26260. }
  26261. var newIndicesArray = [];
  26262. for (i = 0; i < newTriangles.length; ++i) {
  26263. newIndicesArray.push(newTriangles[i].vertices[0]);
  26264. newIndicesArray.push(newTriangles[i].vertices[1]);
  26265. newIndicesArray.push(newTriangles[i].vertices[2]);
  26266. }
  26267. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  26268. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  26269. newMesh.material = this._mesh.material;
  26270. newMesh.parent = this._mesh.parent;
  26271. newMesh.setIndices(newIndicesArray);
  26272. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  26273. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  26274. if (newUVsData.length > 0)
  26275. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  26276. if (newColorsData.length > 0)
  26277. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  26278. //preparing the skeleton support
  26279. if (this._mesh.skeleton) {
  26280. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  26281. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  26282. }
  26283. return newMesh;
  26284. };
  26285. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  26286. for (var i = 0; i < vertex1.triangleCount; ++i) {
  26287. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  26288. if (t.deleted)
  26289. continue;
  26290. var s = this.references[vertex1.triangleStart + i].vertexId;
  26291. var id1 = t.vertices[(s + 1) % 3];
  26292. var id2 = t.vertices[(s + 2) % 3];
  26293. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  26294. deletedArray[i] = true;
  26295. delTr.push(t);
  26296. continue;
  26297. }
  26298. var d1 = this.vertices[id1].position.subtract(point);
  26299. d1 = d1.normalize();
  26300. var d2 = this.vertices[id2].position.subtract(point);
  26301. d2 = d2.normalize();
  26302. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26303. return true;
  26304. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26305. deletedArray[i] = false;
  26306. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26307. return true;
  26308. }
  26309. return false;
  26310. };
  26311. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26312. var newDeleted = deletedTriangles;
  26313. for (var i = 0; i < vertex.triangleCount; ++i) {
  26314. var ref = this.references[vertex.triangleStart + i];
  26315. var t = this.triangles[ref.triangleId];
  26316. if (t.deleted)
  26317. continue;
  26318. if (deletedArray[i]) {
  26319. t.deleted = true;
  26320. newDeleted++;
  26321. continue;
  26322. }
  26323. t.vertices[ref.vertexId] = vertexId;
  26324. t.isDirty = true;
  26325. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26326. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26327. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26328. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26329. this.references.push(ref);
  26330. }
  26331. return newDeleted;
  26332. };
  26333. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26334. for (var i = 0; i < this.vertices.length; ++i) {
  26335. var vCount = [];
  26336. var vId = [];
  26337. var v = this.vertices[i];
  26338. var j;
  26339. for (j = 0; j < v.triangleCount; ++j) {
  26340. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26341. for (var ii = 0; ii < 3; ii++) {
  26342. var ofs = 0;
  26343. var id = triangle.vertices[ii];
  26344. while (ofs < vCount.length) {
  26345. if (vId[ofs] === id)
  26346. break;
  26347. ++ofs;
  26348. }
  26349. if (ofs === vCount.length) {
  26350. vCount.push(1);
  26351. vId.push(id);
  26352. } else {
  26353. vCount[ofs]++;
  26354. }
  26355. }
  26356. }
  26357. for (j = 0; j < vCount.length; ++j) {
  26358. if (vCount[j] === 1) {
  26359. this.vertices[vId[j]].isBorder = true;
  26360. } else {
  26361. this.vertices[vId[j]].isBorder = false;
  26362. }
  26363. }
  26364. }
  26365. };
  26366. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  26367. if (typeof identifyBorders === "undefined") { identifyBorders = false; }
  26368. var i;
  26369. if (!identifyBorders) {
  26370. var newTrianglesVector = [];
  26371. for (i = 0; i < this.triangles.length; ++i) {
  26372. if (!this.triangles[i].deleted) {
  26373. newTrianglesVector.push(this.triangles[i]);
  26374. }
  26375. }
  26376. this.triangles = newTrianglesVector;
  26377. }
  26378. for (i = 0; i < this.vertices.length; ++i) {
  26379. this.vertices[i].triangleCount = 0;
  26380. this.vertices[i].triangleStart = 0;
  26381. }
  26382. var t;
  26383. var j;
  26384. var v;
  26385. for (i = 0; i < this.triangles.length; ++i) {
  26386. t = this.triangles[i];
  26387. for (j = 0; j < 3; ++j) {
  26388. v = this.vertices[t.vertices[j]];
  26389. v.triangleCount++;
  26390. }
  26391. }
  26392. var tStart = 0;
  26393. for (i = 0; i < this.vertices.length; ++i) {
  26394. this.vertices[i].triangleStart = tStart;
  26395. tStart += this.vertices[i].triangleCount;
  26396. this.vertices[i].triangleCount = 0;
  26397. }
  26398. var newReferences = new Array(this.triangles.length * 3);
  26399. for (i = 0; i < this.triangles.length; ++i) {
  26400. t = this.triangles[i];
  26401. for (j = 0; j < 3; ++j) {
  26402. v = this.vertices[t.vertices[j]];
  26403. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  26404. v.triangleCount++;
  26405. }
  26406. }
  26407. this.references = newReferences;
  26408. if (identifyBorders) {
  26409. this.identifyBorder();
  26410. }
  26411. };
  26412. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  26413. var x = point.x;
  26414. var y = point.y;
  26415. var z = point.z;
  26416. 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];
  26417. };
  26418. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  26419. var q = vertex1.q.add(vertex2.q);
  26420. var border = vertex1.isBorder && vertex2.isBorder;
  26421. var error = 0;
  26422. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  26423. if (qDet !== 0 && !border) {
  26424. if (!pointResult) {
  26425. pointResult = BABYLON.Vector3.Zero();
  26426. }
  26427. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  26428. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  26429. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  26430. error = this.vertexError(q, pointResult);
  26431. //TODO this should be correctly calculated
  26432. if (normalResult) {
  26433. normalResult.copyFrom(vertex1.normal);
  26434. if (vertex1.uv)
  26435. uvResult.copyFrom(vertex1.uv);
  26436. else if (vertex1.color)
  26437. colorResult.copyFrom(vertex1.color);
  26438. }
  26439. } else {
  26440. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  26441. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  26442. var error1 = this.vertexError(q, vertex1.position);
  26443. var error2 = this.vertexError(q, vertex2.position);
  26444. var error3 = this.vertexError(q, p3);
  26445. error = Math.min(error1, error2, error3);
  26446. if (error === error1) {
  26447. if (pointResult) {
  26448. pointResult.copyFrom(vertex1.position);
  26449. normalResult.copyFrom(vertex1.normal);
  26450. if (vertex1.uv)
  26451. uvResult.copyFrom(vertex1.uv);
  26452. else if (vertex1.color)
  26453. colorResult.copyFrom(vertex1.color);
  26454. }
  26455. } else if (error === error2) {
  26456. if (pointResult) {
  26457. pointResult.copyFrom(vertex2.position);
  26458. normalResult.copyFrom(vertex2.normal);
  26459. if (vertex2.uv)
  26460. uvResult.copyFrom(vertex2.uv);
  26461. else if (vertex2.color)
  26462. colorResult.copyFrom(vertex2.color);
  26463. }
  26464. } else {
  26465. if (pointResult) {
  26466. pointResult.copyFrom(p3);
  26467. normalResult.copyFrom(vertex1.normal);
  26468. if (vertex1.uv)
  26469. uvResult.copyFrom(vertex1.uv);
  26470. else if (vertex1.color)
  26471. colorResult.copyFrom(vertex1.color);
  26472. }
  26473. }
  26474. }
  26475. return error;
  26476. };
  26477. return QuadraticErrorSimplification;
  26478. })();
  26479. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  26480. })(BABYLON || (BABYLON = {}));
  26481. //# sourceMappingURL=babylon.meshSimplification.js.map
  26482. var BABYLON;
  26483. (function (BABYLON) {
  26484. var Analyser = (function () {
  26485. function Analyser(scene) {
  26486. this.SMOOTHING = 0.75;
  26487. this.FFT_SIZE = 512;
  26488. this.BARGRAPHAMPLITUDE = 256;
  26489. this._debugCanvasWidth = 320;
  26490. this._debugCanvasHeight = 200;
  26491. this._scene = scene;
  26492. this._audioEngine = scene.getEngine().getAudioEngine();
  26493. if (this._audioEngine.canUseWebAudio) {
  26494. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  26495. this._webAudioAnalyser.minDecibels = -140;
  26496. this._webAudioAnalyser.maxDecibels = 0;
  26497. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  26498. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  26499. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  26500. }
  26501. }
  26502. Analyser.prototype.getFrequencyBinCount = function () {
  26503. return this._webAudioAnalyser.frequencyBinCount;
  26504. };
  26505. Analyser.prototype.getByteFrequencyData = function () {
  26506. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  26507. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  26508. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  26509. return this._byteFreqs;
  26510. };
  26511. Analyser.prototype.getByteTimeDomainData = function () {
  26512. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  26513. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  26514. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  26515. return this._byteTime;
  26516. };
  26517. Analyser.prototype.getFloatFrequencyData = function () {
  26518. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  26519. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  26520. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  26521. return this._floatFreqs;
  26522. };
  26523. Analyser.prototype.drawDebugCanvas = function () {
  26524. var _this = this;
  26525. if (this._audioEngine.canUseWebAudio) {
  26526. if (!this._debugCanvas) {
  26527. this._debugCanvas = document.createElement("canvas");
  26528. this._debugCanvas.width = this._debugCanvasWidth;
  26529. this._debugCanvas.height = this._debugCanvasHeight;
  26530. this._debugCanvas.style.position = "absolute";
  26531. this._debugCanvas.style.top = "30px";
  26532. this._debugCanvas.style.left = "10px";
  26533. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  26534. document.body.appendChild(this._debugCanvas);
  26535. this._registerFunc = function () {
  26536. _this.drawDebugCanvas();
  26537. };
  26538. this._scene.registerBeforeRender(this._registerFunc);
  26539. }
  26540. if (this._registerFunc) {
  26541. var workingArray = this.getByteFrequencyData();
  26542. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  26543. this._debugCanvasContext.fillRect(0, 0, this._debugCanvasWidth, this._debugCanvasHeight);
  26544. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  26545. var value = workingArray[i];
  26546. var percent = value / this.BARGRAPHAMPLITUDE;
  26547. var height = this._debugCanvasHeight * percent;
  26548. var offset = this._debugCanvasHeight - height - 1;
  26549. var barWidth = this._debugCanvasWidth / this.getFrequencyBinCount();
  26550. var hue = i / this.getFrequencyBinCount() * 360;
  26551. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  26552. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  26553. }
  26554. }
  26555. }
  26556. };
  26557. Analyser.prototype.stopDebugCanvas = function () {
  26558. if (this._debugCanvas) {
  26559. this._scene.unregisterBeforeRender(this._registerFunc);
  26560. this._registerFunc = null;
  26561. document.body.removeChild(this._debugCanvas);
  26562. this._debugCanvas = null;
  26563. this._debugCanvasContext = null;
  26564. }
  26565. };
  26566. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  26567. if (this._audioEngine.canUseWebAudio) {
  26568. inputAudioNode.connect(this._webAudioAnalyser);
  26569. this._webAudioAnalyser.connect(outputAudioNode);
  26570. }
  26571. };
  26572. return Analyser;
  26573. })();
  26574. BABYLON.Analyser = Analyser;
  26575. })(BABYLON || (BABYLON = {}));
  26576. //# sourceMappingURL=babylon.analyser.js.map